w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Making a foreign key User model extension in Django required
In django 1.3.1 I use this code and works fine: from django.contrib.auth.models import User class FilterSearchQueries(models.Model): title = models.CharField(max_length=250) owner = models.ForeignKey(User) place = models.CharField(max_length=250) query = models.TextField()

Categories : Python

How can I create custom form for User model Django
you want to create a form? create a form say forms.py from django.contrib.auth.models import User from django import forms class CreateUserForm(forms.Form): required_css_class = 'required' username = forms.RegexField(regex=r'^[w.@+-]+$', max_length=30, label="Username", error_messages={'invalid': "This value may contain only letters, numbers and @/./+/-/_ characters."}) email = forms.EmailField(label="E-mail") password1 = forms.CharField(widget=forms.PasswordInput, label="Password") password2 = forms.CharField(widget=forms.PasswordInput, label="Password (again)") def clean_username(self):

Categories : Python

django social auth , create user model with email as primary key
Well I am doing facebook login for my ios app. What I am doing is Login to facebook from my app and get the facebook access token Send the facebook email and access token to the django backend Then what I do is, instead of using the django default authenticate method which takes the username and password to authenticate a user, I overwrite my own authenticate method. Doing this is really easy just read Django Custom Authentication In my custom authentication class I verify the email-token pair sent from the front using fb sdk for python and that is it. After than I can login the user using the django in built login

Categories : Python

how to set a foreign key in django model?
Like this: class interviewtable(models.Model): app = models.ForeignKey(application) interview = models.CharField(max_length=200) interview_on = models.CharField(max_length=200) interview_notes = models.CharField(max_length=200) Django with automatically add id thus app would be app_id. Also, you don't want to use max_length on integer field. If you want big integer use BigIntegerField() Read the documentation properly: https://docs.djangoproject.com/en/1.5/

Categories : Python

How to enforce referential constraints (foreign keys)
Try to add "engine=InnoDB" when you create the tables. Depending on version and platform, the default storage format for tables is MyISAM, and there referential integrity is not checked. Here is an example from 5.0.91-log MySQL Community Server running on Linux: mysql> CREATE TABLE Department -> (dno INTEGER NOT NULL, -> PRIMARY KEY (dno)); Query OK, 0 rows affected (0.04 sec) mysql> CREATE TABLE Employee -> (eno INTEGER NOT NULL, -> works_at INTEGER NOT NULL, -> PRIMARY KEY (eno), -> FOREIGN KEY (works_at) REFERENCES Department(dno)); Query OK, 0 rows affected (0.03 sec) mysql> INSERT INTO Employee (eno, works_at) VALUES (17, 4711); Query OK, 1 row affected (0.02 sec) mysql> DROP TABLE Employee; Query OK, 0 rows affected (0.00 se

Categories : Mysql

Why become referential constraints inconsistent after updating foreign key?
Figured out the problem: apparently it makes quite the difference when to set navigational properties to null, as EF might otherwise interpret that as an intended change / update (at least that is what I suspect). The following version of the MarkAs method works: private void MarkAs(User user, UserAddress address, User.AddressType type) { if (context.Entry(user).State == EntityState.Detached) { // clear navigation properties before attaching the entity user.DefaultInvoiceAddress = null; user.DefaultDeliveryAddress = null; context.Users.Attach(user); } // address doesn't have to be attached if (type.HasFlag(User.AddressType.DefaultInvoice)) { // previously I tried to clear the navigation property

Categories : C#

django model foreign key created index
You can use the db_column parameter to call the column whatever you like. https://docs.djangoproject.com/en/dev/ref/models/fields/#db-column countyName = models.ForeignKey(counties, primary_key=True, db_column='whatever')

Categories : Python

Django foreign key model is not saving reference
Here up.user = u u.save() You are not saving the up anywhere. So u.save() should be up.save() u.save() up.user = u up.save()

Categories : Python

Limit Recursive Foreign Key Depth in Django Model
Maybe something like this? def save(self, *args, **kwargs): if Foo.objects.filter(foo=self.foo).count() > 10: raise Exception("not more than 10") else: super(Foo, self).save(*args, **kwargs) Update: For self referential fields with django-mptt you could do something like this: def save(self, *args, **kwargs): if Foo.objects.filter(foo=self.foo).get_descendant_count() > 10: raise Exception("not more than 10") else: super(Foo, self).save(*args, **kwargs)

Categories : Django

django "is a manually-defined m2m relation through model...which does not have foreign keys to"
I usually reverse m2m definitions as below. In your code above you're seeing a conflict in table names due to the underscore in your model class names. If you remove the underscores it should work. Reversing the relationships could work if you want to keep the underscores. class Option_Choices(models.Model): """ choices for each option """ name = models.CharField(max_length=30) product_options = models.ManyToManyField("Product_Options", related_name='choices') class Product_Options(models.Model): """ products can have many options """ OPTION_TYPE=( ('Color', 1), ) name = models.CharField(max_length=30) option_type = models.IntegerField(choices=OPTION_TYPE) products = models.ManyToManyField("Product", related_name='options')

Categories : Django

Django Model Form - Unable to update table with foreign key
Since you are editing, you need to get the form object using the object instance. In your case, it tries to create a new object, but since this pk already exists, it is throwing the integrity error. form = ContactForm(request.POST, instance=contact_obj) Move the creation of contact_obj up to the beginning of the view method Something like this: from django.core.exceptions import MultipleObjectsReturned def contact(request, template_name): try: contact_obj = Contact.objects.get(user=request.user) except: #You might want to handle multiple objects returned case here too.. contact_obj = None form = ContactForm(instance=contact_obj) if request.method == "POST": form = ContactForm(request.POST, instance=contact_obj) if form.is_valid():

Categories : Python

Django Inline Model Admin filter Foreign Field
Django: accessing the model instance from within ModelAdmin? class PictureInlineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(PictureInlineForm, self).__init__(*args, **kwargs) self.fields['site'].queryset = Site.objects.filter( deal=self.instance.deal) class PictureInline(admin.ModelAdmin): form = PictureInlineForm

Categories : Django

Django - Accessing model from django.contrib's User class via ManyToManyKey
There you go: if user.is_authenticated() and story not in liked_stories: In this line the error is thrown. The code you have posted does not resemble the code you are executing.

Categories : Django

cakephp how do you create a model with only foreign keys?
This seems like a normal example of HasManyThrough [see more details in the CakePHP book]. But - you'll still want to have an id field, whether you want to use it or not.

Categories : PHP

Django password reset on custom user model on Django 1.5?
You should use get_user_model from django.contrib.auth import get_user_model User = get_user_model() User.objects.all()

Categories : Django

Django foreign key in manager's create function
ForeignKey is an abstraction. The field's value is another object, but it is represented in the table as the value of the PK of that object.

Categories : Django

How to inherit mongoengine.django.auth.User for Custom User Model?
From what I can see, you just create a UserProfile with one-to-one relationship to build in User model from django. So this is not true: SOCIAL_AUTH_USER_MODEL = 'users.UserProfile' You should create your own User model. Follow this. Example: from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(unique=True, max_length=45, db_index=True) first_name = models.CharField(max_length=45) last_name = models.CharField(max_length=45) email = models.EmailField(unique=True) status = models.SmallIntegerField() activation_code = models.CharField(max_length=50, null=True, blank=True) is_active = models.BooleanField(default=False) is_staff =

Categories : Django

Change username for authenticated user in django User model
That would work, but there's no need to get the user again. request.user is already the user object. owner = request.user owner.username = newusername owner.save()

Categories : Django

django admin - select reverse foreign key relationships (not create, I want to add available)
Do you mean that for a given School instance you want to be able to get a list of all the students related to that school? In which case you use the related_name attribute of the ForeignKey relationship you specified. You haven't defined the related_name where you do: school = models.ForeignKey(School) which is fine, it just uses the default related name which is the name of the child class (student) followed by _set so for your school instance: school = School.objects.get(pk=1) students = school.student_set.all() # or .filter() or .exclude() etc then you can pass that student queryset into your template.

Categories : Python

getting parent in self referential model
You need to modify the association parent_category. There you have to specify the foreign key. belongs_to :parent_category, class_name: "Category", foreign_key: 'parent_id'

Categories : Ruby On Rails

How to Model self-referential Entities in SQL
Yes, that would be it, but you can simplify: Table Element idElement | name Table Weakness idRow | idElement |idElementStrongAgainst No need to add a strength table, you just have to look at the weakness table entering by the other column. So to find the strengths of water you do SELECT strVS.Name FROM Element AS el JOIN Weakness on el.idElement = Weakness.idElement JOIN Element As strVS on weakness.idElementStrongAgainst= strVS.idElement WHERE el.Name = 'water' and to find the weaknesses: SELECT weakVS.Name FROM Element AS el JOIN Weakness on el.idElement = Weakness.idElementStrongAgainst JOIN Element As weakVS on weakness.idElement = weakVS.idElement WHERE el.Name = 'water'

Categories : SQL

How would I create a CBV using django rest framework which will either retrieve a model instance or create a new one?
for classbased views in django-rest-framework this is usually done by: a GET request to the resource will retrieve records a POST request to the same resource will create a record I believe there are a couple examples of this in the django rest framework documentation

Categories : Django

ruby on rails form_for self referential model
I was able to figure out how to move the logic out of the form. Basically the object being passed to the form_for helper needs to be initialized. I put the initialization logic into user helper and passed the method to the form_for helper. so this is what you get user helper method def initializing_relationships current_user.relationships.build(followed_id: @user.id) end in the form you call initializing_relationships <%= form_for(initializing_relationships) do |f| %> This really cleans up the form.

Categories : Ruby On Rails

undefined method `create' for nil:NilClass when trying to create profile in user model
after_create :create_profile is just enough, not necessary to define create_profile method, it's provided by rails. Example: class User < ActiveRecord::Base has_one :profile after_create :create_profile end

Categories : Ruby On Rails

Using .csv as user model in Django
Your question is very vague and you didn't ask for specifics so here is a general overview of what you'll need to do. If you intend to use django's built-in authentication system then you'll have to setup a database; even if its sqlite. Once you have setup a database, run manage.py syncdb to create the necessary authentication tables (by default, the settings.py that django creates is already setup for the authentication system, so you don't have to make any other changes). Once you have that done, you'll have to write a fixture to load the users from the csv file into the authentication tables. You can read up on that in the documentation under providing initial data for models. Now you are ready to set passwords and permissions. Your next task will be to make sure that the csv file i

Categories : Django

django user model - when do i need it?
Since Django 1.5 you can create your own User Model with your custom fields. And tell Django to use that model for auth. Link to documentation: Custom User Model Update: If you are using Django 1.4, then django-primate can help you to define custom user model.

Categories : Python

django user model - get other custom fields
Shouldn't it be user.bewertung.users_bewertung? Try going into the shell and using dir() on the user: python manage.py shell from django.contrib.auth.models import User usrs = User.objects.all() dir(usrs[0]) It should show you the available methods for that user. You should be able to use something like this to discover the correct method. You might be able to narrow it down better with an __isnull filter on the users: usrs = User.objects.filter(bewertung__isnull=False) dir(usrs[0]) Update Perhaps you need to try _set: ratings = user.users_bewertung_set.all() or ratings = user.bewertung_set.all() Another Possibility Perhaps the problem is that the Bewertung model doesn't have the user that you are logging in. Perhaps you need to check if it exists, before referencing

Categories : Python

Django - Removing username from user model
If You look at the source code of the django.contrib.auth.models file then you will see that definition of the AbstractUser class is rather short and starts like this: class AbstractUser(AbstractBaseUser, PermissionsMixin): ... It inherits from the AbstractBaseUser and PermissionMixin. You could define your custom model and also inherit it from the mentioned classes to get permissions support. If you want all other model fields then yes, you will need to copy them, but it's also an opportunity to customize things to match your needs.

Categories : Django

Is is possible to have the Django slugfield unique per user or other model
The slugify function itself (django.template.defaultfilters.slugify) only works on it's input so that's not what gets you such result. wrt/ your original question, ie "Is it possible to have a slugfield unique per user or other model", it's just a matter of declaring the relevant fields as unique_together in your model's Meta, ie class Category(models.Model): # code here class Page(models.Model): category = models.ForeignKey(Category) slug = models.SlugField("slug") class Meta: unique_together = ( ("category", "slug"), ) Then if you have some code that autogenerate / prepopulate the slug field you'll have to tweak it manually to take care of the category...

Categories : Django

Custom User Model in admin on Django 1.5
As you say, the UserCreationForm references auth.User directly. The Django docs on custom users and built in auth forms state that you must rewrite it for any custom user model. UserCreationForm Depends on the User model. Must be re-written for any custom user model. There is a related ticket Ticket 20086, which was initially closed as invalid, because the user creation form is working as documented. There is a full example on the same page, which shows you how to rewrite the forms and register a custom user model in the admin.

Categories : Python

User-oriented sparql on views and referential graphs
I've never tried to do something like this with the API but it should be possible. I would probably recommend not using SparqlView implementations unless the criteria for what data can be seen by each user is only expressible as a SPARQL query, a SparqlView is fairly expensive in memory terms since it takes a copy of the original data and is not currently a direct view over the underlying data (theoretically this is possible but would require a lot more coding and would trade off lower memory usage for performance). From what you have described I would suggest the best approach might be to use a custom ISparqlDataset implementation, likely deriving from the decorator WrapperDataset. This way you can intercept all the calls that SPARQL queries will make and restrict exactly what each ins

Categories : Misc

Saving custom user model with django-allauth
Side note With Django 1.5 custom user model, the best practice is to use the get_user_model function: from django.contrib.auth import get_user_model # forms.py class SignupForm(forms.Form): first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) age = forms.IntegerField(max_value=100) class Meta: model = get_user_model() # use this function for swapping user model def save(self, user): user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.age = self.cleaned_data['age'] user.save() # settings.py ACCOUNT_SIGNUP_FORM_CLASS = 'web.forms.SignupForm' Maybe it's not related, but I thought it would be worth noticing.

Categories : Python

Custom User model for Django with Facebook Login
If your users should be enabled to login/register with username, mail and password -> use a OneToOne relationship to django's usermodel to store facebook credentials. If your usermodel entirely depends on facebook data and you don't want your users to login with username/pass -> substitute the usermodel with AUTH_USER_MODEL = 'myapp.MyUser'. You might also want to take a look at django-allauth which solves much of your problems in a sweet little package.

Categories : Django

Assigning values to extended User model in Django
Using a separate model with a OneToOne is no longer recommended, since you can extend the User model directly instead. That said, what's wrong here is that your signal is creating the Appuser, but then you try and create another one. Instead, get the one that was created by the signal: user = User.objects.create_user('John Doe') appuser = Appuser.objects.get(user=user) appuser.accesstoken = '634646473' appuser.socialid = 6436 appuser.save() Note that normally you can get from user to appuser by just doing user.appuser, but this probably won't work at this point because the appuser didn't exist at the time you got the User. The next time you get either the Appuser or the User from the db, the direct reference will work.

Categories : Django

How can I import the user model in Django and select all of the objects
settings.AUTH_USER_MODEL is a string. It is not a model object. You need to do something like this: try: from django.contrib.auth import get_user_model except ImportError: # django < 1.5 from django.contrib.auth.models import User else: User = get_user_model() Now, queryset = User.objects.all() -- OR -- if you are using only django 1.5, you can simply do: from django.contrib.auth import get_user_model queryset = get_user_model().objects.all()

Categories : Django

Django 1.5 Custom User Model unknown column
password is part of AbstractBaseUser so it should be added in your AuthUser model as well in table. As you have managed=False for this model, you need to add that explicitly.

Categories : Django

Django custom user model subclassed (by Zinnia)
I think I get your problem. By default, Django does not downcast model instances. For exemple, take the following example: from django.db import models class Parent(models.Model): name = models.CharField() class Child(Parent): pass Parent(name="parent").save() Child(name="child").save() Parent.objects.all() # will return Parent instances Child.objects.all() # will return Child instances In your situation, well, you have Zinnia working with Author instances, and the rest of your project with CustomUser instance. So basically you could downcast every CustomUser instance. You can achieve this using an existing django application, such as django-polymorphic (which, in my opinion, is a must have when working with concrete inheritance). However, if all your users are not author

Categories : Django

Django migrate model with user in a foreignkey fails
This probably isn't your problem if you're not using a custom user model, but remember to always use get_user_model() or when referencing the User class. Also, when defining a foreign key, settings.AUTH_USER_MODEL works, too, as in: class MyModel(models.Model): person = models.ForeignKey(settings.AUTH_USER_MODEL)

Categories : Django

Create same model in multiple databases - Django
You should look at the syncdb command - you can call it programmatically like so: from django.core.management import call_command call_command('syncdb') In your case, you'll want to use named arguments for any options you would have passed in at the command line: call_command('syncdb', noinput=True, database=user_db) Hope that helps. Check this out also: https://docs.djangoproject.com/en/dev/ref/django-admin/#running-management-commands-from-your-code

Categories : Python

Create an instance of a Django model with a FileField
You can open the existing file on the filesystem, wrap it in a Django File instance, and pass that in to the field directly: >>> from django.core.files import File >>> from myproject.myapp.models import FileModel >>> with open('/path/to/existing_file.txt') as f: ... wrapped_file = File(f) ... m = FileModel(model_file=wrapped_file) ... m.save() ... >>> m.model_file.name u'files/existing_file.txt'

Categories : Django



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.