Django - VSCode does not recognize foreign key related names and gives error - django

Post model has a foreign key to User model with posts as its related name.
posts = user.posts.all()
^^^^^
Django works fine obviously. But the error in VSCode is annoying.
How can I make VSCode know this is not an error?

So this is a hack and will improve in the future, but this is the way to solve this right now (outside the mypy plugin, i.e in VS codes built in checker)
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from django.db.models.manager import RelatedManager
class RelModel(Model):
belongs_to = models.ForeignKey(MyModel, related_name="things")
class MyModel(Model):
if TYPE_CHECKING:
things: RelatedManager[RelModel]

Related

Adding choice to a Django ModelForm

I have a basic Django ModelForm working. I am trying to add a Django choice (select/drop-down) to that ModelForm. The code I have has been cobbled together from various example on the web (see below) – as I try to learn Django. So far I cannot find the correct code to add the Django choice. What I have coded is below.
I have tried various combinations of keywords and parameters in forms.py for example:
from django.forms import ModelForm
#
from .models import P2Poll
#
categ_choice= [
('AB', 'AB'),
('CD', 'CD'),
('EF', 'EF'),
('GH', 'GH'),
]
#
class AnyForm(ModelForm):
class Meta:
model = P2Poll
fields = ['q_text', 'Choice1_text', 'Choice2_text','C1_Type','C2_Type']
#
category = forms.ChoiceField(max_length=2, choices=categ_choice)
#
The code has been taken from the following (among others)
django use model choices in modelform
https://docs.djangoproject.com/en/4.0/topics/forms/modelforms/
https://www.geeksforgeeks.org/meta-class-in-models-django/
http://www.learningaboutelectronics.com/Articles/How-to-create-a-drop-down-list-in-a-Django-form.php
When trying the code variation above, I get the following error message:
.. \forms.py", line 28, in Meta
category = forms.ChoiceField(max_length=2, choices=categ_choice)
NameError: name 'forms' is not defined
I have tried a variety of other code attempts to add the choice/select to my Django form, for example:
from django.forms import ModelForm, forms
and I can’t get any to work – there are different error messages, but they all relate to my attempt to add the Django choice to the (model?) form.
Now, as I understand, creating the (basic) form in Django one has to be fairly detailed about what goes in the form. (As I understand) using ModelForms, one just codes what data should appear on the form and Django makes intelligent/standard choice about the appearance of the form. Maybe I am trying to merge ModelForms with (standard?) Django forms – I don’t know. I am just trying to understand how to add a choice/select to a Django (model) form. I am learning.
Now maybe what I am trying to do is not possible with the “parts” I have assembled.
I have read the Django documentation on forms, and I find it incomprehensible with my level of knowledge. I’m sure my understanding of the documentation will improve as I understand Django more.
Try is:
from django import forms # <-- Updated
from .models import P2Poll
categ_choice = [
('AB', 'AB'),
('CD', 'CD'),
('EF', 'EF'),
('GH', 'GH'),
]
class AnyForm(forms.ModelForm): # <-- Updated
class Meta:
model = P2Poll
fields = ['q_text', 'Choice1_text', 'Choice2_text', 'C1_Type', 'C2_Type']
category = forms.ChoiceField(max_length=2, choices=categ_choice)
The issue was with your approach to import forms.

Django: UserCreationForm not getting Custom User Class

I'm new to Django and I'm running into an odd issue. Using Django 2.2.5 I've created a custom User class, sub-classed from AbstractBaseUser. Other than extending AbstractBaseUser the only major change I made was deleting the username field and adding my own (won't get into why here). I've added the USERNAME_FIELD = "my new username" to the model as well.
This all appeared to work well and I was able to create users. I then installed django-registration, to use that functionality and when I tried to makemigrations I ran into this error:
'django.core.exceptions.FieldError: Unknown field(s) ("My new username") specified for User`
Now, this didn't make any sense to me since the model clearly has a"My new username" field and I'd specified Django should use my User model in setting via AUTH_USER_MODEL. I knew that was working because calling get_user_model() in a shell returned my custom model.
Now here's where it gets weird, I was able to trace the issue to django-registrations, RegistrationForm. This is a form that subclasses Django's UserCreationForm. When RgistrationForm was loading or whatever during makemigrations it was producing the error because the model reference for the form was django.User not my custom user model. RegistrationForm does not declare a model and uses UserCreationForm model which happens to be User from django.contrib.auth.models.
Based on what I've read and how User is written it should reference my model, via the swappable attribute since I've set AUTH_USER_MODEL and it's supposed to swap to the model located in that settings option. For some reason, though it's not working and I don't know enough about Django to debug further.
I'm very confused by this since get_user_model() references the exact same setting and it works.
I've been able to fix this for the moment by editing the RegistrationForm model to add model = "Custom user model in django-registration's forms. I'd rather not have to distribute a custom version of this package with the rest of the site at the moment.
Any idea what's going on with swappable that might be causing this issue?
Edit 1/27/19: Update I tried sub-classing the relevant django-registration classes, but it turns out that simply importing RegistrationForm causes the issue. Importing UserCreationForm does not immediately cause a problem but if I try to check UserCreationForm.Meta.model."My new username" it provides this error:
AttributeError: type object 'User' has no attribute 'UVI_Handle'
This is consistent with the error above. At this point I'm not sure how to proceed again. I could subclass UserCreationForm, but none of django-registration will pick up on that so there doesn't seem to be a point in using it, since I'll have to copy the whole thing.
Instead of changing the package code, you should subclass:
In the case where your user model is compatible with the default
behavior of django-registration, (see below) you will be able to
subclass RegistrationForm, set it to use your custom user model as the
model, and then configure the views in django-registration to use your
form subclass. For example, you might do the following (in a forms.py
module somewhere in your codebase – do not directly edit
django-registration’s code):
from registration.forms import RegistrationForm
from mycustomuserapp.models import MyCustomUser
class MyCustomUserForm(RegistrationForm):
class Meta:
model = MyCustomUser
Above is taken from here, you should also change the urls, which is also described there.

Django-mptt registration for an existing model

I tried to apply mptt in my django program on a existing model using the method provided on the main site of mptt, which is as follow:
import mptt
from mptt.fields import TreeForeignKey
from django.contrib.auth.models import Group
# add a parent foreign key
TreeForeignKey(Group, blank=True, null=True, db_index=True).contribute_to_class(Group,'self')
mptt.register(Group, order_insertion_by=['name'])
However, when I open my group list in the admin-site, it says that the group model doesn't have such column named parent_id, I wonder how I can fix it.
BTW the code have been written in models.py,is it possible that I should have written it in admin.py?
reference: Registration of existing models
Edit:
sorry about the comment...migrations does solve the problem ><
However it leads to another question...can I only create a group by code to create a new tree structure, or it's possible for me to do that somewhere in my admin site?
Thanks for the answering and attention:)

How to properly extend django User model

I'm trying to extend the default Django's authentication model with additional fields and functionaliy, so I've decided to just go with extending User model and writing my own authentication backend.
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
class MyUser(User):
access_key = models.CharField(_('Acces Key'), max_length=64)
This is really a basic code yet when trying to syncdb I'm cetting a strange error that Google doesn't know about :
CommandError: One or more models did not validate:
core.sldcuser: 'user_ptr' defines a relation with the model 'auth.User', which has been swapped out. Update the relation to point at settings.AUTH_USER_MODEL.
In my settings.py I've added what I guess is required :
AUTH_USER_MODEL = 'core.MyUser'
Had anyone stumbled upon this error ?
Or maybe I should use a one-to-one way, or a hybrid of 1t1 with proxy ?
What you're doing right now, is creating a subclass of User, which is non-abstract. This means creating a table that has a ForeignKey called user_ptr pointing at the primary key on the auth.User table. However, what you're also doing by setting AUTH_USER_MODEL is telling django.contrib.auth not to create that table, because you'll be using MyUser instead. Django is understandably a little confused :P
What you need to do instead is inherit either from AbstractUser or AbstractBaseUser.
Use AbstractUser if you want everything that User has already, and just want to add more fields
Use AbstractBaseUser if you want to start from a clean state, and only inherit generic functions on the User, but implement your own fields.
REF:
https://docs.djangoproject.com/en/dev/topics/auth/customizing/#extending-the-existing-user-model
https://docs.djangoproject.com/en/dev/topics/auth/customizing/#substituting-a-custom-user-model

Django admin - instance needs to have a primary key value before a many-to-many relationship can be used

edit: I wasn't clear before, I am saving my object in the django admin panel, not in a view. Even when I save the object with no many-to-many relationships I still get the error.
I have a model called TogglDetails that has a ForeignKey relationship with the standard django User model and a MayToManyField relationship with a model named Tag. I have registered my models with django admin but when I try to save a TogglDetails instance I get the error in the title.
Here are my models:
class Tag(models.Model):
name = models.CharField(max_length=30)
def __unicode__(self):
return self.name
class TogglDetails(models.Model):
token = models.CharField(max_length=100)
user = models.ForeignKey(User)
tags = models.ManyToManyField(Tag, blank=True, null=True)
def __unicode__(self):
return self.user.username
class Meta:
verbose_name_plural = "toggl details"
As far as I can tell, there should be no issues with my models and django admin should just save the instance without any issues. Is there something obvious that I have missed?
I am using Django 1.3
The answer to my question was this: Postgres sequences without an 'owned by' attribute do not return an id in Django 1.3
The sequences in my postgres database did not have the "Owned by" attribute set and so did not return an id when a new entry was saved to the db.
As stated by other users:
Postgres sequences without an 'owned by' attribute do not return an id in Django 1.3
The sequences in my postgres database did not have the "Owned by" attribute set and so did not return an id when a new entry was saved to the db
In addition:
This is most likely caused by a backwards incompatible change that renders some primary key types in custom models beyond reach for Django 1.3. See Django trac tickets https://code.djangoproject.com/ticket/13295 and http://code.djangoproject.com/ticket/15682 for more information.
I solved the problem by running the follow commands for the affected tables/sequences.
Specifically running the command:
manage.py dbshell
ALTER SEQUENCE tablename_colname_seq OWNED BY tablename.colname;
change tablename_colname_seq and tablename.colname
Don't let us guess and add the Error message to your question, this gives most information about where it fails.
Have you imported the User model?
from django.contrib.auth.models import User
I've had this problem as well and the only thing I could do was make the M2M fields blank and not set them until I hit Save and Continue Editing.
I think this just may be a framework wart, as you will notice the User section of the Admin site also has a very strict "You can only edit these fields until you save the model".
So my recommendation is to adopt that scheme, and hide the M2M form field until the model has a Primary Key.
I tried Django 1.3 using CPython, with different database setups. I copy-pasted the models from the question, and did some changes: first I added
from django.contrib.auth.models import User
at the top of the file and I put the reference to Tag between quotes. That shouldn't make any difference. Further, I created the following admin.py:
from django.contrib import admin
import models
admin.site.register(models.Tag)
admin.site.register(models.TogglDetails)
For Sqlite3, the problem described doesn't occur, neither for MySQL. So I tried PostgreSQL, with the postgresql_psycopg2 back end. Same thing: I can't reproduce the error.
So as far as I can figure, there's nothing wrong with the code in the question. The problem must be elsewhere.