Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: "no such table: auth_user" on attempt to create superuser using custom user model
Custom user model I use works great on my another project, but here it refuses to allow creating superuser returning error I pointed out in title. Normal users can be created easily. Here is models.py class UserManager(BaseUserManager): def create_user(self, username, password=None): if not username: raise ValueError('Please select your username') if not email: raise ValueError('Tell us your email address') user = self.model( email = self.normalize_email(email), username = username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email, password): user = self.create_user( email = self.normalize_email(email), username = username, password = password, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser): first_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=30, blank=True) email = models.EmailField(unique=True) username = models.CharField(max_length=50, unique=True) date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now_add=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) bio = models.TextField(max_length=500, blank=True) role = models.CharField(max_length=20, default='user') USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email', 'username'] objects = UserManager() def __str__(self): return self.first_name + ' ' + self.last_name def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True Any help is appreciated, thank you. -
Can I not use django.contrib.contenttypes?
I use django-admin startproject mysite and created a sample django project. I don't think the sample project has any models so I commented out "django.contrib.contenttypes" in INSTALLED_APPS in settings.py. I also commented out all middlewares. I then wrote a simple view from django.shortcuts import render def index(request): return render(request, 'hello.html') and hello.html is just a blank file. Once I access the page, django throws exception Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. Can anyone help explain the exception? The sample project doesn't have any model, why do I need django.contrib.contenttypes? Can django websites live without django.contrib.contenttypes? -
is there a way to automatically update database structure in django as soon as new field added/updated?
Basically subj. I know that there are some implementations, using django-idmapper but I haven't found any instructions how to implement that in an actual project. The idea is that during the development it would superuseful if the change in the database (new models added to models.py, new fields added to existing models, etc. would automatically lead to database reset, and new migrations applied. In development only, of course. Any ideas or ready-made solutions that are available? -
TypeError: __init__() got an unexpected keyword argument 'required'
I have an error when using the field_classes attribute, in my form: class UserChangeForm(UserChangeForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['username'].widget.attrs.update({'class': 'form-control form-control-sm'}) self.fields['url'].widget.attrs.update({'class': 'form-control form-control-sm'}) self.fields['avatar'].widget.attrs.update({'class': 'custom-file-input'}) self.fields['biography'].widget.attrs.update({ 'class': 'form-control form-control-sm', 'placeholder': 'Cuéntanos un poco sobre ti', 'style': 'height: 70px; max-height: 150px; min-height: 70px;' }) class Meta: model = User fields = ['username', 'avatar', 'biography', 'url'] field_classes = {'avatar': forms.FileInput} labels = {'biography': 'Biografia', 'url': 'URL'} If I comment out the field_classes = {'avatar': forms.FileInput} line, everything works fine and without any errors, but why is this happening? ERROR: Exception in thread django-main-thread: Traceback (most recent call last): File "/home/lcteen/miniconda3/envs/django/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/home/lcteen/miniconda3/envs/django/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/core/management/base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/urls/resolvers.py", line 398, in check for pattern in self.url_patterns: File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/lcteen/miniconda3/envs/django/lib/python3.7/site-packages/django/urls/resolvers.py", line 579, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", … -
generating unique id(8 digits) for every user
my models.py is : class clients(models.Model): client_id = models.IntegerField(unique=True, null=False, blank=False, primary_key=True) ' ' my serializers.py is: class UserSerializer(serializers.ModelSerializer): class Meta: model = clients fields = ('client_identity_id','client_id','client_firstname','client_middlename','client_lastname','client_country','money','client_num') read_only_fields = ('money','client_id') my views.py is: def post(self,request): data=request.data serializer = UserSerializer(data=data) if serializer.is_valid(): serializer.save() client_A = clients.objects.get(client_identity_id=data['client_identity_id']) def create_unique_id(): id=int(''.join(random.choices(string.digits, k=8))) return id create_unique_id() unique = False while not unique: if not clients.objects.get(client_id=id): unique = True else: create_unique_id() client_A.client_id = id client_A.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) when i make a post request it show me error "Field 'client_id' expected a number but got built-in function id" , what should i do ? what i want is , when i make a post request it should generate an 8 digits unique id and save it,, and how can i generate an 8 length unique id contain letters and numbers ?? -
Django unable to connect to remote mysql
I am trying to connect remote mysql from from django (python 3). I was facing django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on 'ns3100739.supercar.pl' (110)") I have also changed /etc/mysql/my.conf and added following lines bind-address = ns3100739.supercar.pl and tried to restart MySQL with sudo privilege but MySQL not restarting. -
Pdf error after download as Content-Disposition' = attachment
In my rest framework, I have a retrieve method on ModelViewSet as def retrieve(self, request, *args, **kwargs): instance = self.get_object() serializer = self.get_serializer(instance) print(serializer.data) pdf = serializer.data['pdf'] response = Response(pdf, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="invoice.pdf"' return response pdf is the model field of the FileField type. I am able to automatically download the pdf file on URL but when I try to open the pdf it gives an error, on chrome is says "Failed to load PDF document" and on pdf viewer is says "not a supported file type or the file has been damaged, (send as an email attachment and not correctly decoded)" What more I need to do to make it work correctly. While the pdf is of the correct format and can be opened directly, Thanks -
Updating Model Field from Views.py
I have a feeling I am missing something obvious and syntax related here so I apologize in advance. I would like the status of a user to be automatically updated when they successfully process a form. # Models.py class Account(AbstractBaseUser): status_list = ( ('R',"RED"), ('B',"BLUE"), ('G',"GREEN"),) status = models.CharField(max_length=1, choices=status_list, default='R') value = models.CharField(max_length=30, unique=False, blank=True) #Forms.py class Form(forms.ModelForm): class Meta: model = Account fields = ('value', ) # Views.py def View(request): if request.POST: form = Form(request.POST, instance=request.user) if form.is_valid(): form.initial = {"value": request.POST['value'],} form.save() #Here is the issue V Account.objects.filter(status=Account.status).update(status='B') return redirect('status') I have tried the solutions presented in both of these two posts: 1. Editing model field from Views.py 2. Object has no attribute 'update' as well as a host of other random and excessively creative combinations. Does anyone happen to know the proper syntax for this call? -
How to filter ModelAdmin autocomplete_fields results from clientside input
This is a followup on this thread: How to filter ModelAdmin autocomplete_fields results with the context of limit_choices_to Uberdude proposed a solution which works great to customize the autoselect queryset based on the field which triggered the request, but I would also need to filter based on input from the client side, most specifically a checkbox which is not a model field, and only for some of the fields in the form as in this form excerpt. I managed to apply the checkbox to the widget by overriding your AutocompleteSelect widget as: class AutocompleteSelectCb(AutocompleteSelect): def render(self, name, value, attrs=None): s = super().render(name, value, attrs) return mark_safe('<div style="margin-bottom:10px;"><input type="checkbox" id="parent1"\ name="parentx" value="1">Search among all kennels</div>' + s) and use that widget only when the fields are present in a autocomplete_cb_fields attribute in the admin: autocomplete_fields = ['breed'] autocomplete_cb_fields = ['father', 'mother'] However, I am not sure how to get my AutocompleteSelectCb widget to send the status of the checkbox so that it can be processed in the get_search_results method. I assume with some js, but how? Any idea? -
How to cache queries in django?
I am fairly new to the concept of caching, trying to use a custom middleware to cache DB queries in django. I tried using Johnny cache but its cache invalidation logic isn't that optimised in my use case. I have a huge table, from which multiple read/write queries are being made. Johnny cache reads into the cache and invalidates it if any write query is made on the particular table. I want to have a more specific cache invalidation in my case. What are some other standard ways to do this? -
Aggregating fields in graphene/django queries
I am writing a graphene/django ORM query, where I need to aggregate the values of a particular field on all my query result objects and return it with the query. Not quite sure how to do that, as this involves some post-processing. Would appreciate it if someone can offer some guidance. Here's some sample code. Django model class 'Market' has an integer field 'num_vendors'. The Graphene wrapper is 'MarketNode' that wraps around the 'Market' model class: Model class: class Market(models.Model): num_vendors = models.IntegerField(....) Graphene class: class MarketNode(DjangoObjectType): Meta: model: Market I'd like the query to return 'market_count' (there are multiple markets) and 'vendor_count' (sum of all 'vendors' across all markets). So the query would look like: allMarkets { market_count vendor_count edges { node { ... ... num_vendors ... } } } For the market_count, I am following this example (this works fine): https://github.com/graphql-python/graphene-django/wiki/Adding-counts-to-DjangoFilterConnectionField For vendor_count (across all markets), I assume I need to iterate over the results and add all the num_vendors fields, after the query is complete and resolved. How can I achieve this? This must be a fairly common-use case, so I am sure graphene provides some hooks to do this. -
How to get login of user who added new position and save it with new record
I'm just starting the adventure with Django. I have almost finished my first very small application but I have last one small problem to solve. I would like to know who added the new record to the database and save his login. No problem to show login on website... Problem is because I don't know how to get login of user who added new position and save it with new record. Because my application is not in english I prepared smallest version of it: my models.py file: from django.db import models from datetime import datetime import socket import getpass from django.contrib.auth.models import User class City(models.Model): city = models.CharField(max_length=40) description = models.CharField(max_length=200, null=True, blank=True) def __str__(self): return self.city class Workers(models.Model): hostname = socket.gethostname() login_username = getpass.getuser() user = User.username name = models.CharField(max_length=200) age = models.DecimalField(max_digits=3, decimal_places=0) hobby = models.CharField(max_length=300) city = models.ForeignKey(City, on_delete=models.CASCADE) description = models.CharField(max_length=200, null=True, blank=True) added_date = models.DateTimeField('added date', default=datetime.now()) computer = models.CharField(max_length=30, default=hostname) computer_user = models.CharField(max_length=10, default=login_username) logged_user = models.CharField(max_length=100, default='user') #<<== place for login user def __str__(self): return self.name my views.py file: from django.shortcuts import render, redirect from .models import Workers from .forms import WorkersForm def all_records(request): records = Workers.objects.all().order_by('id').reverse() context = { 'records': records } … -
Hello im getting this error: TemplateDoesNotExist at / blog/home.html, blog/post_list.html
I have the blog/home.html but idk why the post_list pop up. this only happens when I try to deploy my app to Heroku, when it do the python manage.py runserver everything works. Help is appreciated. -
django email verification before signup allowed
I am trying to build an email verification portion of my application. So the user enters their email, hits submit, and they will get an email with a one-time "token" or link that allows them to access the actual sign up page. How do I go about this with the newer version of django since the from django.contrib.auth.tokens import PasswordResetTokenGenerator from django.utils import six code doesn't seem to be working? The actual error says cannot import name six from django.utils. I see in other answers Getting error cannot import name 'six' from 'django.utils' when using Django 3.0.0 latest version that it has to do with six being dropped from django 3.0. Is there a better way to do verification emails upon registration? -
Setting up SendGrid using Django - User input "from_email"
All the Google searching in the world hasn't answered my question, so hoping someone can help me out. I have a Django based "Contact Me" webpage, which uses a form and the Django send_mail function. My app is hosted through Heroku. When I try to submit an email on my form, the form tries send_mail(subject, message, from_email, ["mypersonal@email.com"]) But I get the following error: (550, b'The from address does not match a verified Sender Identity. Mail cannot be sent until this error is resolved. Visit https://sendgrid.com/docs/for-developers/sending-email/sender-identity/ to see the Sender Identity requirements') This seems to imply to me that the "from_email" needs to be MY verified email on SendGrid, and not the email of the person trying to contact me? What am I missing? My goal is to have user submissions be sent to my @gmail.com address -
pycharm IDE warning on django doc: Expected type 'timedelta', got 'DateTimeField' instead python 3.7
in Django's doc is the following code snippet from django.db import models from django.utils import timezone import datetime class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) Pycharm highlights self.pub_date and shouts Expected type 'timedelta', got 'DateTimeField' instead How do I get rid of this and do things right? -
Form not saving new object to database
I have a form named ProtocolUserCredentialsForm. The main objective of processCredsForm is is to save the user input for the data_source_username, user, data_source, and data_source_password and assign it these creds in a new object in a database. Get displays the actual form and the html. For Post, it sends the user to a new page with form.html, by clicking submit on the first page (that has upgrade_user_creds.html and the form). When the user clicks the submit button, I need the credentials to save and for a new object to be created. I am just confused on why this is not creating a new ProtocolUserCredentials object in the database when I check admin? There isn't any errors coming up as well. class UpdateCredsView(TemplateView): template_name = 'update_user_creds.html' def processCredsForm(self, request): creds_form = ProtocolUserCredentialsForm(data=request.POST) context = {} obj = ProtocolUserCredentials() obj.user = creds_form['user'] obj.data_source = creds_form['data_source'] obj.data_source_username = creds_form['data_source_username'] obj.data_source_password = creds_form['data_source_password'] if creds_form.is_valid(): credentials = creds_form.save(commit=FALSE) credentials.save if not creds_form.is_valid(): if not (creds_form.non_field_errors()): context['form_errors'] = creds_form.errors context['form1'] = creds_form def get(self, request): context = {} allcreds = ProtocolUserCredentials.objects.all() context = {'form1': ProtocolUserCredentialsForm(), 'allcreds': allcreds} return render(request, 'update_user_creds.html', context) def post(self, request): post_data = request.POST context = {} context = {''} if 'submit_nautilus_creds' … -
Can't install Django to windows. It gives a error called "ModuleNotFoundError: No module named 'pip._vendor.packaging'"
I installed virtual Environment and entered this code py -m pip install virtualenvwrapper-win Then I created a virtual environment called "myproject_01" using this command. mkvirtualenv myproject_01 Then I tried to install Django using this command but it gives an error ""ModuleNotFoundError: No module named 'pip._vendor.packaging'". py -m pip install Django Please help me to fix this error.This is the error I get when I try to install Django -
Specify nested fields Django
I was looking into Django Rest Framework Documentation and I read about Nested Serialization, and how Depth could be used, there it specify the depth of relationships: class AccountSerializer(serializers.ModelSerializer): class Meta: model = Account fields = ['id', 'account_name', 'users', 'created'] depth = 1 But doing in this way, all filds get the depth of 1, how can I specify wich field I want to be nested, like, for account_name, use a depth = 1, and for user a depth = 2 -
Forms fields respecting DRY django
Given some forms in Django (take the following for simplicity) class LoginRegisterForm(forms.Form): email = forms.EmailField(label="Email", max_length=100) password = forms.CharField(label="Password", widget=forms.PasswordInput(), max_length=100) We're trying to restrict the submission of these forms if there are additional fields submitted so we have the following added method to our form class def correct_fields(self): return set(self.data.keys()) == {"Email", "Password"} And the following code in the views.py method corresponding to the submission of this form: if form.is_valid() and form.correct_fields: How can we avoid having to write Email and Password in both the definition of the form and the correct_fields method? Does django offer a build-in function to prevent forms being submitted if the correct fields are not submitted? (The form is still submitted if the correct fields and some additional fields are given). If this functionality is not given, how do I avoid writing the fields twice? -
Django send_mail method : Include session userid in mail message
I was able to use send_mail method and it works without any problem. What I am trying to achieve is to include session's username in mail message. My views.py allow a certain authenticated user to create numbers. On successful addition of numbers, an email is triggered to the administrators, which at the moment does not include user's userid. So the administrators have no way of knowing which user created the numbers. My attempt to get userid displayed in mail body below. I also tried another variant - #send mail subject= 'Numbers created by {request.user}' message = 'This user {request.user} has created numbers. ' from_email= settings.EMAIL_HOST_USER to_list = [settings.EMAIL_ADMIN] -
HTTP ERROR 405 when i submit my form.how to fix this?
first i went to url /idontknow/ the html of the template belonging to this url: <body> <form action="{% url 'polls:idk' %}" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </body> it loaded my form input the data and then submitted the form. after i submitted it gave me the 405 error , how to solve this such that when i submit i want the same page to reload but with my submiited data inside form. MY View: class IDK(FormView): form_class=NameForm template_name = "polls/idk.html" success_url = "polls/idontknow/" def form_valid(self, form): print("DATA="+form) return super(IDK, self).form_valid(form) my urls: path('idontknow/', views.IDK.as_view(), name='idk'), -
How can I fix this sign up function?
from django.contrib.auth.forms import UserCreationForm from django.shortcuts import render, redirect from django.urls import reverse_lazy def SignUp(request): if request.user.is_authenticated: return redirect('home') else: form = UserCreationForm success_url = reverse_lazy('login') return render(request, 'signup.html', {'form': form}) When I try to sign up it just refreshes the page, but nothing works, the user isn't registered. So how can I fix this? Thanks -
Using Either Slug or PK in URL (Python - Django)
I want the user to access posts using either the PK or Slug. I can get http://localhost:8000/post/8/ to work but not http://localhost:8000/post/working-in-malaysia/. I have looked at a few posts on Stack Overflow but I don't want http://localhost:8000/post/8/working-in-malaysia. And I don't want it to be a case of either the PK works. Or the slug works. I want the user to be able to enter either. Below is the code I have tried. I tried to merge together code I saw in a number of other posts. Sadly to no avail. urls.py urlpatterns = [ path('', PostListView.as_view(), name='blog-home'), path('post/<int:pk>/', views.post_detail, name='post-detail'), #path('post/<slug:the_slug>/', views.post_detail, name='post-detail-slug'), path('post/<slug:url>/', views.post_detail, name='post-detail-slug'), path('post/new/', PostCreateView.as_view(), name='post-create'), path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'), path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'), path('about/', views.about, name='blog-about'), path('facebook/',TemplateView.as_view(template_name='blog/index.html'), name="facebook") ] views.py class PostDetailView(DetailView): model = Post # Should match the value after ':' from url <slug:the_slug> #slug_url_kwarg = 'the_slug' slug_url_kwarg = 'url' pk_url_kwarg = "id" # Should match the name of the slug field on the model slug_field = 'url' # DetailView's default value: optional query_pk_and_slug = True def dispatch(): post = get_object_or_404(Post) comments = post.comments.filter(active=True, slug=slug) new_comment = None if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.post = post new_comment.save() else: comment_form = … -
Django select random post elemets efficiently
I have some post models where the ID is a UUID. Now I want to display some random post proposals the user may also like to see at my post_detail template... This is how I process the post proposals the user may also like to see at views.py: def post_proposals(proposal_count): post_elements = sorted( chain( Model1.objects.all(), Model2.objects.all(), Model3.objects.all() ) ) post_elements_list = list(post_elements) # Conversion to list is requierd by random post_proposals = random.sample(post_elements_list, proposal_count) return post_proposals def post_detail(request, pk): ... args = { 'post': post, 'post_proposals': post_proposals(proposal_count=10), ... template.html: {% for post_proposal in post_proposals %} <h1>{{ post_proposal.title }}</h1> {% endfor %} The problem now is that this would kill my database performance from my understanding... As soon as I have a lot of posts stored at my database the query will become massive. I first have to get all elements of 3 models and then get 10 random entries from the list each time a post gets displayed to the user. I also found the following which seems to be quite useful: https://elpenia.wordpress.com/2010/05/11/getting-random-objects-from-a-queryset-in-django/ Sadly I can't use that solution as I work with UUIDs which are non-sequential strings instead of int values I would have with IDs.