Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is the MySQL query taking 25 seconds to give the output?
I have created a MySQL Database in PythonAnywhere but the problem is that it is taking too long to show results. As shown in the image below, it is taking almost 25 seconds to show the databases which I think is not normal. What can I do to solve it? SQL Query -
Making Django model Query case-insensitive
I would like to look up users by their email without worrying about uppercase letters. How would I do this? I tried customer = Customer.objects.get(email__lower="test@gmail.com") and got this error. django.core.exceptions.FieldError: Unsupported lookup 'lower' for EmailField or join on the field not permitted. -
why do i keep getting locking file error install django or django packages?
When I install django or django packages every time I get this error.Pipfile.lock does't occur.Is it a serious problem?If it is, how can ı fix it? -
Does not reflect current user in comment
Hello I am new in the community and in the world of programming so I hope you can excuse my ignorance. I'm creating an Instagram-style application with Django 3.2.5. Where users have profiles to visit and upload photos. I am implementing a commenting system, I have it almost finished or so I think ... Turns out I am stuck ... When generating the comment as a user with a registered profile, the comment is rendered as if it were anonymous. I have investigated and it happens that in the model of the comment I made a relationship with user and profile giving the null parameter as true. When removing this parameter and resubmitting a comment on a post I get an error of 'Not Null Constraint Failed' for profile_id and for user_id (The image shows the first comments made from the admin. And the last one with the null = true parameter in the model) Sample picture Here I leave my models.py class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') user = models.ForeignKey(User, on_delete=models.CASCADE) profile = models.ForeignKey(Profile, on_delete=models.CASCADE) text = models.TextField(max_length=200) created_date = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['created_date'] def __str__(self): return self.text Here I leave my views.py def create_comment(request, pk): … -
how to output the judgement that is related to the title
I am trying to make website which shows the judgements of various cases based on some conditions. I pushing the data from database, where i upload the title of the judgment and the contents of the judgement. Now in the html file i have written this: {% for data in law_data %} {% if data.law_type == 'civil' and data.law_category == 'limitations' %} <div class="tab"> <button class="tablinks" onclick="openLawtype(event,'title')">{{data.title}} &nbsp<i class="fas fa-chevron-circle-right"></i></button> </div> {% endif %} {% endfor %} Here, after checking the conditions the titles are printed as buttons. The titiles are pushed from the database. Now i want that indvidual titles should show the judgements related to them. i wrote the following code for it: {% for data in law_data %} {% if data.title in data.judgments %} {{data.judgments|safe}} {% else %} <p> no data available</p> {% endif %} {% endfor %} However irrespective of whatever button i press all the judgements that are present in the databse are printed. I am unable to develope the logic for how to print the juudgement that contains the title as part of it and print only the judgement that is related to title. It will be very help full if you can help … -
Python Why Django won't let me load a new product
I'm in this page: Filling the details The link of orange image is https://upload.wikimedia.org/wikipedia/commons/c/cb/Oranges_white_background.jpg When I'm pressing 'save' it gives me this: Error message Couldn't understand the issues I tried various ways to solve it like take another picture and re-run the server. From Mosh Hamedi tutorial: https://www.youtube.com/watch?v=_uQrJ0TkZlc&t=20225s at 05:42:20 I do not know what this double space between 'user' and 'old' means and I really need help with this I'm stuck on this from Sunday models.py from django.db import models class Product(models.Model): name = models.CharField(max_length=255) price = models.FloatField() stock = models.IntegerField() image_url = models.CharField(max_length=2083) class Offer(models.Model): code = models.CharField(max_length=10) description = models.CharField(max_length=255) discount = models.FloatField() views.py from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse('Hello World') def new(request): return HttpResponse('New Products') admin.py from django.contrib import admin from .models import Product admin.site.register(Product) pyshop - urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path("products/", include('products.urls')) ] products - urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index), path('new', views.new) ] -
Django template tags for changing key names in a dictionary
I'm working on a kanji website with Django templates. I have a dictionaries made out of an external xml. I set xml tags as keys. Here is an example of one of those dicitionaries (which casually happens to be about dictionaries... paper ones :P) 'dictionaryEntries': {'nelson_c': '43', 'nelson_n': '81', 'halpern_njecd': '3540', 'halpern_kkd': '4354', 'halpern_kkld': '2204', 'halpern_kkld_2ed': '2966', 'heisig': '1809', 'heisig6': '1950', 'gakken': '1331', 'oneill_names': '525', 'oneill_kk': '1788', 'moro': '272', 'henshall': '997', 'sh_kk': '1616', 'sh_kk2': '1724', 'jf_cards': '1032', 'tutt_cards': '1092', 'kanji_in_context': '1818', 'kodansha_compact': '35', 'maniette': '1827'} Using the following code on template, they are displayed on the website: <ul> {% for key, value in dictionaryEntries.items %} <li><b>{{key}}: </b>{{value}}</li> {%endfor%} </ul> And they get something like following on html: <ul> <li><b>nelson_c: </b>2991</li> <li><b>nelson_n: </b>3715</li> <li><b>halpern_njecd: </b>3497</li> <li><b>halpern_kkd: </b>4309</li> <li><b>halpern_kkld: </b>2179</li> <li><b>halpern_kkld_2ed: </b>2933</li> <li><b>heisig: </b>1555</li> <li><b>heisig6: </b>1675</li> <li><b>gakken: </b>29</li> <li><b>oneill_names: </b>214</li> <li><b>oneill_kk: </b>67</li> <li><b>moro: </b>21670</li> <li><b>henshall: </b>42</li> <li><b>sh_kk: </b>44</li> <li><b>sh_kk2: </b>44</li> <li><b>sakade: </b>34</li> <li><b>jf_cards: </b>71</li> <li><b>henshall3: </b>44</li> <li><b>tutt_cards: </b>43</li> <li><b>crowley: </b>9</li> <li><b>kanji_in_context: </b>49</li> <li><b>busy_people: </b>2.4</li> <li><b>kodansha_compact: </b>1327</li> <li><b>maniette: </b>1569</li> </ul> However, as you can see, key values such as nelson_c are not very user-friendly. I don't want to change the tag name on xml. Is there a way, maybe via tags, to change … -
Django project with Eureka server
Can any one help me how to do django project with Eureka server end to end proper implementation -
Django - How do I leave some fields empty when I click "Save as new"?
I am trying to clone an existing item exactly as is, make edits, and save the new version in the admin. However, I do not want to pre-fill specific fields. I need to leave those specific fields empty in the cloned version and have the user fill them in. How can I do this? What function do I have to override? -
The view system.views.Login didn't return an HttpResponse object. It returned None instead
I'm newbie to Django. I'm stuck at one thing that, valueError at /login/. I've tried my best to search and try to solve this but i didn't find my problem solution. In Following First Code Sample From Which I Got Error, def get(self, request): if request.user.is_authenticated: username = request.user stud = Stud.objects.filter(adm=username).exists() cord = Cord.objects.filter(Id=username).exists() if stud: return redirect('appStatus') elif cord: return redirect('cordIndex') else: return redirect('admin') else: form = self.form(None) return render(request, self.template, {'form': form}) Error traced from terminal: ValueError: The view system.views.Login didn't return an HttpResponse object. It returned None instead. -
django {"non_field_errors":["Unable to log in with provided credentials."]} (authtoken)
models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token @receiver(post_save, sender=settings.AUTH_USER_MODEL) # creates token when user registers def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) class cUserManager(BaseUserManager): # saves the user def create_user(self, email, password, **others): email = self.normalize_email(email) user = self.model(email=email, **others) user.set_password(password) user.save() return user def create_superuser(self, email, password, **others): others.setdefault('is_staff', True) others.setdefault('is_superuser', True) return self.create_user(email, password, **others) class cUser(PermissionsMixin, AbstractBaseUser): email = models.EmailField(unique=True) username = models.CharField(max_length=128, unique=True) password = models.CharField(max_length=256, unique=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = cUserManager() urls.py from django.urls import path from . import views from rest_framework.authtoken.views import obtain_auth_token urlpatterns = [ # Auth Views path('login', obtain_auth_token, name='login'), ] Sample User "id": 1, "email": "user@gmail.com", "username": "User", "password": 123, "is_staff": true, "is_superuser": true, "created_at": "2021-08-10 - 16:25:19", I am trying to login the user, but whenever i do it throws this error: {"non_field_errors":["Unable to log in with provided credentials."]}, the data that gets sent to the obtain_auth_token url is the username and password, everything is good in settings.py so no need to show it here... so … -
xhtml2pdf: Output generated PDF as in-memory object (its bytes)
I'm working with Python 3, Django and the xhtml2pdf package. I want to create a PDF from an HTML string, but I don't want to write the PDF on disk, but rather just to get its bytes, as in using BytesIO or StringIO. I've read the xhtml2pdf documentation: In-memory files can be generated by using StringIO or cStringIO instead of the file open. Advanced options will be discussed later in this document. And this is one the latest thing I've tried: def html_to_pdf(html): """Writes a PDF file using WeasyPrint from a given HTML stream Parameters ---------- html : str A HTML valid string. Returns ------- bytes A bytes sequence containing the rendered PDF. """ new_output = BytesIO() pisa_status = pisa.CreatePDF(html, dest=new_output) return new_output.read() But this isn't working. Any idea how to output the generated PDF and in-memory object and thus return its bytes? -
how to pass kwargs in ajax urls in django? Reverse for '' with arguments '('',)' not found. 1 pattern tried: ['partners/analytics/(?P<id>[0-9]+)/$']
I have the following code in one of my templates: var id = "{{a.id}}"; $.ajax({ url :'{% url 'this:dashboard' id %}',, type : 'POST', data : { }, }); I get the following error? Reverse for '' with arguments '('',)' not found. 1 pattern(s) tried: ['dash/here/(?P<id>[0-9]+)/$'] my url is: path('here/<int:id>/', views.dashboard, name="dashboard"), -
How to render django model instances in particular order using django templates?
I have for div in my html with their id each like this: <div class="row"> <div class="myclass" id="id1"></div> <div class="myclass" id="id2"></div> <div class="myclass" id="id3"></div> <div class="myclass" id="id4"></div> </div> Now how can I render the instance of the model in the order specified below ? first instance in first div of the row second instance in second div of the row third instance in third div of the row fourth instance in fourth div of the row and fifth instance in first div of the row so one and so forth. Any help would be appreciate even if it is using javascript hope it would be lot more simpler there. -
Django project only works locally, not on Heroku?
When I run my django project on my local pc, it works perfectly fine and I can sign up/log in/log out on my site. When I deploy it to Heroku, it doesn't work anymore, giving me the following error: OperationalError at /login/ no such table: auth_user I know this question exists, and I've already tried all the solutions, but it still hasn't worked. I've done migrate and makemigrations on both the python and heroku side, along with the commit command at different intervals. I also don't even have the usercreateform, and OP's error for that question appeared on their local pc, not just Heroku. I also tried creating a super user, which I could on my local pc, but not on Heroku. If it helps, my procfile is: web: gunicorn django_project.wsgi --log-file - I had a hard time determining my procfile, so maybe that's the problem? The django_project part is just the name of the folder that includes settings.py and wsgi.py. Forms.py: class NewCommentForm(forms.ModelForm): class Meta: model = Comment fields = ['content'] class NewMessageForms(forms.ModelForm): class Meta: model = Message fields = ['content','reciever'] -
web_1 | MySQLdb._exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)")
I am building an application with Djnago and MySql. I want to use docker for the deployment of my application. I have prepared a requirement.txt, docker-compose.yml and a Dockerfile docker-compose.yml version: '3' services: db: image: mariadb restart: always ports: - 3306:3306 environment: MYSQL_DATABASE: stage_emsi MYSQL_USER: root MYSQL_PASSWORD: password MYSQL_ROOT_PASSWORD: password web: build: . command: python manage.py runserver 0.0.0.0:8000 ports: - "8000:8000" volumes: - .:/code depends_on: - db image: web:django Dockerfile FROM python:3 ENV PYTHONUNBUFFERED=1 RUN mkdir /code WORKDIR /code RUN pip install mysqlclient COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ error b_1 | Watching for file changes with StatReloader web_1 | Performing system checks... web_1 | web_1 | System check identified no issues (0 silenced). web_1 | Exception in thread django-main-thread: web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection web_1 | self.connect() web_1 | File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner web_1 | return func(*args, **kwargs) web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 200, in connect web_1 | self.connection = self.get_new_connection(conn_params) web_1 | File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner web_1 | return func(*args, **kwargs) web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/mysql/base.py", line 234, in get_new_connection web_1 | connection = Database.connect(**conn_params) web_1 | File "/usr/local/lib/python3.9/site-packages/MySQLdb/__init__.py", line … -
password dont change in views.py on django
I'm trying to change a user's password on my views.py and whenever I change the password, I lose my connection and access to my account my view.py: user = User.objects.get(id=request.user.id) user.password = make_password(request.POST.get("password")) user.save() -
How do I dynamically create methods for Django models?
I have been studying Python for several months and for the first time I got stumped. I have a sample Django code like this: class SomeOptions(models.Model): FIRST = 1 SECOND = 2 THIRD = 3 @classmethod def get_first(cls): return SomeOptions.objects.get(pk=cls.FIRST) @classmethod def get_second(cls): return SomeOptions.objects.get(pk=cls.SECOND) @classmethod def get_third(cls): return SomeOptions.objects.get(pk=cls.THIRD) It looks disgusting. But it works exactly the way I want it to. SomeOptions.get_first() >> 'Some data from db' I want to remove these methods and make them get generated dynamically. I even managed to do it this way: class Dispatcher(object): def __init__(self, model, method_name): self.model = model self.method_name = method_name def __call__(self): return self.get_required_attribute_value() def get_required_attribute_value(self): required_attribute_name = self.get_required_attribute_name() required_attribute_value = getattr(self.model, required_attribute_name) value_from_database = self.model.objects.get(pk=required_attribute_value) return value_from_database def get_required_attribute_name(self): _, required_attribute_name = self.method_name.split('_') return required_attribute_name.upper() class SomeOptions(models.Model): FIRST = 1 SECOND = 2 THIRD = 3 @classmethod def __getattr__(cls, attr): return Dispatcher(cls, attr) I got more code, but the most important thing is that the Dispatcher class is universal and can be used for any model. The problem is this: SomeOptions().get_first() >> 'Some data from db' SomeOptions.get_first() >> AttributeError: type object 'SomeOptions' has no attribute 'get_first' How can I get the code to work without creating a SomeOptions() … -
Get n number of random records using nested serializers Django REST framework
I'm trying to get random 'n' number of records from foreign key related models. Suppose I have two models named Exam and Questions. I need an API endpoint to get n number of questions for one particular subject(ex. for math, n random math questions). The endpoint is working well in retrieving all the questions for a particular subject. models.py class Exam(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Question(models.Model): exam = models.ForeignKey(Exam, on_delete=models.CASCADE) question = models.CharField(max_length=255) def __str__(self): return '{} - {}'.format(self.question) serializers.py class QuestionSerializer(serializers.ModelSerializer): questions = serializers.CharField(read_only=True) answer = serializers.CharField(read_only=True) class Meta: model = Question fields = '__all__' class ExamSerializer(serializers.ModelSerializer): name = serializers.CharField(read_only=True) questions = QuestionSerializer(many=True, read_only=True, source='question_set') class Meta: model = Exam fields = '__all__' api_views.py class ExamQuestionRetrieveAPIView(generics.RetrieveAPIView): authentication_classes = [JWTTokenUserAuthentication] serializer_class = ExamSerializer queryset = Exam.objects.all() lookup_field = 'name' After going through the doc, I tried to filter and get random records using the to_representation() method but failed. Any help is greatly appreciated. -
Django v3 NoReverseMatch at /signup/
I have a error after signup: Reverse for 'activateuser' with keyword arguments '{'uidb64': 'NzA', 'token': 'ar65ve-0c2f1aaa20521539b574c02e5a6844f5'}' not found. 1 pattern(s) tried: ['activateuser/$'] my url: ... path('signup/', accounts.views.signupuser, name='signupuser'), url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', ... my view: def signupuser(request): if request.user.is_authenticated: return redirect('/charts/drawchart/v1/metrics/addresses/active_count/') else: form = SignUpForm() if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) mail_subject = 'Activate your blog account.' message = render_to_string('accounts/activate_account_mail.html', { 'user': user, 'domain': current_site.domain, 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token':account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() return redirect('loginuser') else: return render(request, 'accounts/signup.html', {'form': form}) else: return render(request, 'accounts/signup.html', {'form': form}) def activateuser(request, uidb64, token): try: uid = urlsafe_base64_decode(uidb64) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() login(request, user) context = {'uidb64':uidb64, 'token':token} return render(request, '/charts/drawchart/v1/metrics/addresses/active_count/', context) else: return HttpResponse('Activation link is invalid!') and finally my template: {% autoescape off %} Hi {{ user.username }}, Please click on the link to confirm your registration, http://{{ domain }}{% url 'activateuser' uidb64=uid token=token %} {% endautoescape %} -
Django admin interface missing css styling in production
The user interface is working well, and all CSS styling and static files are served correctly, but the admin interface is missing CSS styling. I looked at similar posts but in those posts people had the issue with both the user and the admin interface. My issue is only with the admin interface. Please see my static file settings below from settings.py: STATIC_URL = '/static/' #Location of static files STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') And this is my nginx configuration: server { listen 80; server_name MY_SERVER_IP; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/MYUSERNAME/myproject; } location /media/ { root /home/MYUSERNAME/myproject; } I already executed python manage.py collectstatic on the server and got this message: 0 static files copied to '/home/MYUSERNAME/myproject/staticfiles', 255 unmodified. I restarted nginx after that and also tried emptying my browser cache, but the issue persisted. -
Django: how to create a dictionary of objects and display in templates
Hey I have had a look at similar questions but none really relate to what I am trying to do, they either explain how to order things in the admin panel or simply iterating over object dictionaries. I have created a basic photo model that contains a value gallery_order so I can edit them in Admin. I wish to populate my template with the pictures according to the gallery_order values in order from 1 upward. I guess the best way to handle it is with a dictionary but I do not know where to initialize it, if I put it in the picture model then each picture holds a dict with all the pictures order number and url in it which seems mental. My current model: class Picture(models.Model): title = models.CharField(max_length=36, blank=False, unique=True) gallery_order = models.IntegerField(default=0) image = models.ImageField(upload_to='photos/', blank=False) def __str__(self): return self.title My template code: <head> <meta charset="utf-8"> {% block content %} <div class="row"> {% if pictures %} {% for picture in pictures %} <div class="col-md-12"> <div class="card mb-0"> <img class="card-img-top" src="{{ picture.image.url }}"> </div> </div> {% endfor %} {% endif %} </div> {% endblock content %} </head> my admin code: @admin.register(Picture) class PictureAdmin(admin.ModelAdmin): list_display = ('gallery_order', 'title', … -
Need to override django auto_now_add in pytest factory
Due to auto_now_add in django models sent_at is not working in pytest factory. Need to overrive sent_at for pytest factory class ABC(models.Model): x = models.ForeignKey(X, on_delete=models.CASCADE, related_name="xx") y = models.ForeignKey(Y, on_delete=models.CASCADE, related_name="yy") sent_at = models.DateTimeField(auto_now_add=True) class ABCFactory(factory.django.DjangoModelFactory): x = factory.SubFactory(XFactory) y = factory.SubFactory(YFactory) sent_at = timezone.now() - timezone.timedelta(seconds=40) -
Allow only positive decimal numbers for decimal fields
Within my Django models I have created a decimal field. price = models.DecimalField(default=0, decimal_places=2 How can I make it so that the price is never negative. Is there a way to limit the decimal number to only positive numbers? I have tried MinValueValidator and it did not work.. -
Django crawler just scraping first page
I have a crawler that runs perfectly with simple Python but running it on Django inside an app, only grabs the links from the first page. To run the crawler I'm executing celery -A src worker -l INFO. Any idea why it starts working but suddenly stops? Could it be a Django problem?