Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django loaddata command error - cannot find fixutres
I can't figure this out.. I've tried what seems like every possible variation, loaddata can't find fixtures in any of my apps. It works in previous versions of Django but on 3.1.5 it does not work. CommandError: No fixture named 'products' found. python manage.py loaddata products python manage.py loaddata products.json python manage.py loaddata products --app product python manage.py loaddata product/fixtures/products python manage.py loaddata product/fixtures/products.json python manage.py loaddata */fixtures/*.json Here's my folder structure myproject ├─product ├─fixtures ├─products.json ├─models.py -
Use user_passes_test after login_required in function based view
I have written a passing condition for user which is as follows: def check_admin(user): isAdmin = False if user.role == "ADMIN": isAdmin=True return isAdmin This is working fine in class based view: class AgentUpdate(LoginRequiredMixin,UpdateView): model = User form_class = UserUpdateForm template_name_suffix = '_update_form' success_url='/agents' @method_decorator(user_passes_test(check_admin)) def dispatch(self, *args, **kwargs): return super(AgentUpdate, self).dispatch(*args, **kwargs) Bu when i use it in function based view it is giving me error 'AnonymousUser' object has no attribute 'role' @login_required @user_passes_test(check_admin) def upload_topic(request): ---- Rest of the view--- -
Ajax/Axios cookies not being set, but still being included in following requests
For some reason cookies set by server are not being saved, can't access them from within my js code, in devtools in Application tab in cookies section it's all empty, but somehow when I make a request to the server after the initial one, those cookies that apparently didn't save are being included in the header. I have set withCredentials to true in axios config, as well as CORS_ALLOW_CREDENTIALS to true on my backend. Here are the headers from the request that should save cookies: Response Header: access-control-allow-credentials: true access-control-allow-origin: <frontend url> content-length: 22 content-type: text/html; charset=utf-8 date: Mon, 01 Feb 2021 12:04:09 GMT server: nginx/1.19.2 set-cookie: csrftoken=<token>; expires=Mon, 31 Jan 2022 12:04:09 GMT; Max-Age=31449600; Path=/; SameSite=Lax set-cookie: sessionid=<sessionid>; expires=Mon, 01 Feb 2021 13:04:09 GMT; HttpOnly; Max-Age=3600; Path=/ strict-transport-security: max-age=31536000 vary: Cookie, Origin x-frame-options: SAMEORIGIN Request Headers: :authority: <backend url> :method: POST :path: /login/ :scheme: https accept: application/json, text/plain, */* accept-encoding: gzip, deflate, br accept-language: en-US,en;q=0.9 cache-control: no-cache content-length: 66 content-type: application/json;charset=UTF-8 dnt: 1 origin: <frontend url> pragma: no-cache referer: <current frontend url query> sec-fetch-dest: empty sec-fetch-mode: cors sec-fetch-site: same-site user-agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36 As you can see in the response I'm getting … -
Online store deployment error, with many models
As soon as I click on the link, a standard error is written to me. Tried to increase the request processing time but the error persists. I also updated the database completely and changed the host address. Before adding a new model, everything worked, but as soon as I made a couple of changes it stopped working. Here is my code https://github.com/Daryna00/My File location Preset >home >media >merchan >order >Preset >product >staticfiles >templates >' >db.sqlite3 >debug.log >manage.py >Procfile >requirements.txt >runtime.txt Procfile web: gunicorn Preset.wsgi After entering the command such errors. (venv) D:\PycharmProjects\My\Preset>heroku logs --tail 2021-02-01T11:48:20.661821+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load 2021-02-01T11:48:20.661821+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked 2021-02-01T11:48:20.661822+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 680, in _load_unlocked 2021-02-01T11:48:20.661822+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 790, in exec_module 2021-02-01T11:48:20.661823+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed 2021-02-01T11:48:20.661823+00:00 app[web.1]: File "/app/home/urls.py", line 2, in <module> 2021-02-01T11:48:20.661835+00:00 app[web.1]: from .views import index, what_is_it, sign_in, register, logout_user, my_page, ajax_reg_login, contact, change_order_count, delete_from_card, add_to_card, get_pdf, questions_answer 2021-02-01T11:48:20.661835+00:00 app[web.1]: File "/app/home/views.py", line 19, in <module> 2021-02-01T11:48:20.661836+00:00 app[web.1]: from xhtml2pdf import pisa 2021-02-01T11:48:20.661836+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/xhtml2pdf/pisa.py", line 18, in <module> 2021-02-01T11:48:20.661836+00:00 app[web.1]: from xhtml2pdf.default import DEFAULT_CSS 2021-02-01T11:48:20.661837+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/xhtml2pdf/default.py", line 5, in … -
ImportError: No module named attr while starting any docker-compose file [closed]
Tried reinstalling docker but didn't help Traceback (most recent call last): File "/usr/bin/docker-compose", line 11, in <module> load_entry_point('docker-compose==1.17.1', 'console_scripts', 'docker-compose')() File "/usr/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 480, in load_entry_point return get_distribution(dist).load_entry_point(group, name) File "/usr/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 2693, in load_entry_point return ep.load() File "/usr/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 2324, in load return self.resolve() File "/usr/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 2330, in resolve module = __import__(self.module_name, fromlist=['__name__'], level=0) File "/usr/lib/python2.7/dist-packages/compose/cli/main.py", line 20, in <module> from ..bundle import get_image_digests File "/usr/lib/python2.7/dist-packages/compose/bundle.py", line 12, in <module> from .config.serialize import denormalize_config File "/usr/lib/python2.7/dist-packages/compose/config/__init__.py", line 6, in <module> from .config import ConfigurationError File "/usr/lib/python2.7/dist-packages/compose/config/config.py", line 44, in <module> from .validation import match_named_volumes File "/usr/lib/python2.7/dist-packages/compose/config/validation.py", line 12, in <module> from jsonschema import Draft4Validator File "/usr/local/lib/python2.7/dist-packages/jsonschema-3.2.0-py2.7.egg/jsonschema/__init__.py", line 11, in <module> from jsonschema.exceptions import ( File "/usr/local/lib/python2.7/dist-packages/jsonschema-3.2.0-py2.7.egg/jsonschema/exceptions.py", line 9, in <module> import attr ImportError: No module named attr -
python manage.py runserver giving nameError: Python not defined
I am using the following command: (env) C:\Users\Raktim_PC\PycharmProjects\pythonProject\mysite>python manage.py runserver This results in the following error: Traceback (most recent call last): File "manage.py", line 1, in <module> python#!/usr/bin/env python NameError: name 'python' is not defined I am getting started with Django framework and was following an online tutorial. I am in the outer mysite folder under which another mysite and mnagae.py resides when I am running the command leading to this error. Any ideas on what might be causing this and a possible solution? -
How to display list items in descending order in django?
I've created a website that streams cartoons. On the first page, the user gets to see the entire list of cartoons. When clicked, a page showing the details of the cartoon as well its corresponding seasons loads. When a specific season is clicked. It shows the list of episodes that season has. Now what happens is that it displays the episodes normally, however, it shows them in a jumbled format. I want to show it in descending order. How am I supposed to go about doing that? Here are my files. If you didn't understand this description of my problem(which you probably didn't) you can see the website for yourself http://cartoonpalace.herokuapp.com: Views.py from django.shortcuts import render from django.http import HttpResponse from django.views.generic import ListView, DetailView from .models import CartoonSeason, Cartoon, Episode # Create your views here class CartoonListView(ListView): model = Cartoon template_name = "index.html" class CartoonSeasonView(DetailView): model = Cartoon template_name = "season.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["seasons"] = CartoonSeason.objects.filter(cartoon=self.object) return context class SeasonDetailView(DetailView): model = CartoonSeason template_name = "episode_list.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["episodes"] = Episode.objects.filter(season=self.object) return context class EpisodeDetailView(DetailView): model = Episode template_name = "episode.html" Models.py # Create your models here. from django.db import models … -
Django rest framework queryset gives me .pk i want .name
my model class Vacatures(models.Model): title = models.CharField(max_length=50) employer = models.ForeignKey(Employer, on_delete=models.CASCADE) my .view class VacaturesOverzichtMobile(generics.ListAPIView): model = Vacatures serializer_class = VacaturesSerializer queryset = Vacatures.objects.all() def get_queryset(self): queryset = Vacatures.objects.all() return queryset So in the model there is Employer as Foreingkey. The api call in .view is working fine. The only thing is i get the employer as employer.pk , but i want the name of the Employer which is in the EmployersModel. Can i tune the queryset so that it returns employer.name for example instead of employer.pk -
Changing db_table on Django doesn't work after migrations, and adding a user (AbstractUser) foreign key breaks __str__()
This is a 2 problem post, which i suspect are somehow connected. My posts app on Django doesn't migrate properly (I think), and adding the 'author' (Users AbstractUser model) breaks my code with the error: str returned non-string (type tuple) whenever I try to add a row. I changed the name of the table using db_table (so it will change Postss to Posts on the admin page) and added an output to the __str__ function, I tried a few variations of output for the str function but non of them worked. I even tried to comment it out. and still. no changes in the table name or the error. I tried changing my str functions a few times and got the same result. when deleting the str function, I still get that same result. I have a few wild guesses about this situation: it might not work with an abstract users class for some reason, and do not know to to work around this and why this happens at all. (removeing the author=... row resolves this problem but doesn't change the table name, but I do need the user fk there). it might not be migrating properly due to my … -
Django: Include template with constructed name if available
I have a one template say: default_form.html which receives in its context a variable, say variant. I can of course render the contents of the variable with {{ variant }} And here: https://stackoverflow.com/a/28076380/4002633 I see a wonderful way to load a template if it exists. It works nicely if I have a template called variant as follows: {% try_include variant %} But I am hoping to go one step further. I would like to use a constructed template name, in the example above and include if it exists a template named default_form_variant.html. I imagine something like this: {% try_include "default_form_{{variant}}.html" %} but even more general rather than encoding the current template's name, getting that, if possible, from the context itself or in a custom tag from the parser. I am struggling to see how and where in the custom tag definition I'd have access to three things at once: The name of the current template: default_form.html in this case. The argument to the tag: variant in this case The ability to construct a template name from the first two (easy enough with os.path) and inject it into the do_include handler. -
choices are not showing in the selectbox in django
I am trying to add categories in my project. So that whenever user post a blog he will add category also but in the select box it is not showing I tried this : from django import forms from .models import Post,Category,Comment choices = Category.objects.all().values_list('name','name') choice_list = [] for item in choices: choice_list.append(item) class AddForm(forms.ModelForm): class Meta: model = Post fields = ('title','title_tag','author','category','body','snippet','header_image') widgets = { 'title' : forms.TextInput(attrs={'class':'form-control','placeholder':'Title of the Blog'}), 'title_tag' : forms.TextInput(attrs={'class':'form-control','placeholder':'Title tag of the Blog'}), 'author' : forms.TextInput(attrs={'class':'form-control','value':'','id':'elder','type':'hidden'}), 'category' : forms.Select(choices=choice_list, attrs={'class':'form-control','placeholder':"blog's category"}), 'body' : forms.Textarea(attrs={'class':'form-control','placeholder':'Body of the Blog'}), 'snippet' : forms.Textarea(attrs={'class':'form-control'}), } -
Is the server running on host host (192.46.237.35) and accepting TCP/IP connections on port 5432? Django&PostgreSQL
Basically i am trying to connect my postgresql database to my DjangoApp inside my Linode server,but i get this error. I have everything included here. Why do i get this error?Does somebody have the solution? -
CustomAuthBackend() missing 1 required positional argument: 'ModelBackend'
My models were fine, migrate successfully and I am able to create superuser. I am not able to go to admin login page as the error shows up "CustomAuthBackend() missing 1 required positional argument: 'ModelBackend'" In Custom Backends: def CustomAuthBackend(ModelBackend): def authenticate(self, request, email=None, password=None, phone=None): my_user_model = get_user_model() user = None if email: try: user = my_user_model.objects.get(email=email) except: return None #Return None if no such user elif phone: try: user = my_user_model.objects.get(phone=phone) except: return None #Return None is no such user if user: if user.check_password(password): return user else: return None def get_user(self, user_id): my_user_model = get_user_model() try: return my_user_model.objects.get(pk=user_id) except my_user_model.DoesNotExist: return None In Settings: AUTH_USER_MODEL = 'authengine.User' AUTHENTICATION_BACKENDS = ['authengine.backends.CustomAuthBackend'] Screenshot -
Permission Denied with react-google-login
I am using a Django backend and using django-rest-framework-social-oauth2 to manage my social logins. I am using react for my frontend and I am using the react-google-login package. But the problem is whenever I try to authenticate, the permission denied warning is shown as you can see in the pictures. I have tried putting in localhost and the IP address but to no avail. Any help is appreciated. Permission Denied -
Django ValueError: Cannot assign must be an instance
when i try to insert data to my database through manage.py shell, i got this error ValueError: Cannot assign "'Ciawigebang'": "Desa.kecamatan" must be a "Kecamatan" instance. this is my models.py from django.db import models class Kecamatan(models.Model): kecamatan = models.CharField(max_length=30) def __str__(self): return self.kecamatan class Desa(models.Model): desa = models.CharField(max_length=30) kecamatan = models.ForeignKey(Kecamatan, null=True, blank=True, on_delete=models.CASCADE) def __str__(self): return self.desa here my json file snippet scrap.json [ { "Kecamatan": "Ciawigebang", "Desa": [ "Ciawigebang", "Ciawilor", "Cigarukgak", "Cihaur", "Cihirup", "Cijagamulya", "Cikubangmulya", "Ciomas", "Ciputat", "Dukuhdalem", "Geresik", "Kadurama", "Kapandayan", "Karangkamulya", "Kramatmulya", "Lebaksiuh", "Mekarjaya", "Padarama", "Pajawanlor", "Pamijahan", "Pangkalan", "Sidaraja", "Sukadana", "Sukaraja" ] },{ "Kecamatan": "Cibeureum", "Desa": [ "Cibeureum", "Cimara", "Kawungsari", "Randusari", "Sukadana", "Sukarapih", "Sumurwiru", "Tarikolot" ] },{ "Kecamatan": "Cibingbin", "Desa": [ "BANTAR PANJANG", "CIANGIR", "Cibingbin", "Cipondok", "CISAAT", "Citenjo", "DUKUHBADAG", "Sindang Jawa", "SUKA MAJU", "SUKAHARJA" ] }... ] this is the code i use to insert the data to database from python manage.py shell import json from apps.models import Desa, Kecamatan with open('scrap.json') as f: daerahs = json.load(f) for daerah in daerahs: for x in daerah['Desa']: y=Desa(desa=x, kecamatan=daerah['Kecamatan']) y.save() how to solve this? there's so many similar question but i can't figure it out how to solve this problem in my case. Thanks for your help... -
How to query value in numeric order?
Suppose I have a model class Industry(models.Model): name = models.Charfield(max_length = 100) status = models.IntegerField() order = models.IntegerField() How can i query data in view basing on numeric values i have given in order column to some Industry and others in alphabetical order. industry_results = Industry.objects.filter(filters,status='1').order_by('name','-id').values('name','id').exclude(name__isnull=True).distinct('name') -
Django REST: Dynamically add Model Fields
I'm working on a Django Rest project where I'm given two MySQL tables: metrics: Contain a row for each potential metric daily_data: Contains a row for each data entry where the column names refer to metrics from the 'metrics' table What I want to do now, is creating new entries in 'metrics' which should be automatically added to existing 'daily_data' entries (with a default value) and displayed on the website. Here is how the current models looks like: class Metrics(model.Model): metric_id = models.CharField(max_length=255, primary_key=True) is_main_metric = models.BooleanField(default=False) name = models.CharField(max_length=255, blank=False, null=False) description = models.CharField(max_length=255, blank=False, null=False) lower_bound = models.FloatField(default=0.0, null=False) upper_bound = models.FloatField(default=0.0, null=False) class Meta: verbose_name_plural = "Metrics" db_table = "metrics" class DailyData(models.Model): location = models.CharField(max_length=255, blank=False, null=False) date = models.DateField(blank=False, null=False) # then a static field for each metric is added that corresponds to a 'metric_id' in the table 'metrics': metric_01 = models.FloatField(default=0.0, null=False) metric_02 = models.FloatField(default=0.0, null=False) metric_03 = models.FloatField(default=0.0, null=False) ... class Meta: verbose_name_plural = "Daily Data" db_table = "daily_data" Later on, the Javascript code iterates over all 'metrics' to display them with the corresponding values from a requested 'daily_data' entry. Here is a small example: let resp = await axios.get(`${API_URL}/daily_data/?location=berlin&date=2021-01-07`); let data = resp.data[0]; … -
Set Django auto-increment primary key to specific value
I have an Order model for which I grabbed a bunch of orders from an older system. As we wanted to preserve the ID, I set it manually during the migration. However, this has thrown of the auto-increment key. It's no longer correct. How can I set the auto-increment to start from a specific value? -
Filter Data via DateTimeField in Local Timezone [DJANGO]
Date and time are saved in the MySQL db in UTC. I need to filter for objects saved via date depending on the user timezone. For example, John who is in 'Africa/Lagos' timezone did a transaction on Feb 1, 2021 at 12:00AM in his local time and it will be saved in the DB as Jan 31, 2021 23:00 UTC. When I run the below query on Feb 1, 2021 it won't come up because of the +1 hr difference. time_zone = pytz.timezone("Africa/Lagos") today_date = timezone.now().astimezone(time_zone).date() today_transaction = Credit.objects.filter(created_date__contains=today_date) Where today's date is Feb 1, 2021. But because it was saved in the DB in UTC, the exact date in local timezone won't be returned. The query will return []. Is it possible to make the conversion today_date in the DB level? What am I missing? -
How to run celery from different location?
My folder structures are like below root ---django_files ---django_app1 ---django_app2 ---scripts --some sh files I want to run celery from root folder. I write code like this celery -A django_files.proj.celery_conf:app worker --loglevel=info It says no module named django_files. I guess my command line is not correct,how can i run then from root folder? -
Django ValidationError Doesn't Show Up
I am learning a django and I was practicing registration. But before doing that, I wanted to test the validationerrors but it doesn't show up the error message on the screen even if the form is not valid. I want my program to write on screen an error message when student_tc and student_password don't match. views.py messages = [] def student_register(request): if request.method == "POST": form = StudentRegisterForm(data=request.POST) if form.is_valid(): student_name = form.cleaned_data.get('student_name') student_surname = form.cleaned_data.get('student_surname') student_no = form.cleaned_data.get('student_no') student_contact = form.cleaned_data.get('student_contact') student_email = form.cleaned_data.get('student_email') student_tc = form.cleaned_data.get('student_tc') student_gender = form.cleaned_data.get['student_gender'] student_branch = form.cleaned_data.get('student_branch') student_password = form.cleaned_data.get('student_password') data = {'student_name': student_name, 'student_surname': student_surname, 'student_no': student_no, 'student_contact': student_contact, 'student_email': student_email, 'student_tc': student_tc, 'student_gender': student_gender, 'student_branch': student_branch, 'student_password': student_password} messages.append(data) form.save() return render(request, 'student_registered.html') else: return render(request, 'student_register.html', context={'form': form}) form = StudentRegisterForm() return render(request, 'student_register.html', context={'form': form}) forms.py class StudentRegisterForm(forms.ModelForm): class Meta: model = Student fields = ['student_name', 'student_surname', 'student_tc', 'student_gender', 'student_no', 'student_contact', 'student_email', 'student_branch', 'student_password'] widget = {'student_password': PasswordInput} def __init__(self, *args, **kwargs): super(StudentRegisterForm, self).__init__(*args, **kwargs) for field in self.fields: self.fields[field].widget.attrs = {'class': 'form-control'} def clean(self): student_password = self.cleaned_data.get('student_password') student_tc = self.cleaned_data.get('student_tc') if student_password != student_tc: raise forms.ValidationError('Password and TC don't match') return student_password def clean_email(self): student_email = self.cleaned_data.get('student_email') student_email … -
Internationalization does not work in pythonanywhere
I have deployed my Django website to PythonAnywhere last week and in the meantime, I made some changes to texts on the website. Now, I am trying to translate these pieces of text using the internationalization package in PythonAnywhere, but somehow it does not work. When I run python manage.py makemessages -l en, my django.po file is updated and I am able to add the translations, but once I run python manage.py compilemessages -l en, the English translations do not show up on the website. The first day, I did get the translations to work, but now they don't anymore. What could be the cause of this? And could anybody help me find a way to solve the issue? Thanks! -
How to launch django with socket io on nginx gunicorn/uwsgi
is there any tutorial or guide to properly launch python socketion with django on nginx gunicorn/uwsgi server? I have tried those at official documentation, but not successful. -
Django app extremely slow after upgrading Django from 3.0.8 to 3.1.5 and channels from 2.4.0 to 3.0.3
So I've developped Django app using Django 3.0.8 and served it as an asgi app with channels 2.4.0 and daphne. At that point in time those were the latest versions. The application was working nicely with web sockets and django views working adequately, and channels handled treading great. So all was great and world seemed like a beautiful place... until some evil inside me pushed to upgrade Django to 3.1.5 which required upgrading channels to 3.0.3. So now app still works, all pages are served and web sockets work, but all HTTP requests are queued and handled in one thread, which makes the application extremely slow. I've tried to read the docs for channels 3 and all release notes for Django and channels, yet I'm not seeing what has changed and what changes I need to introduce to make my app run like it was before. Here are all versions of related packages Django==3.1.5 channels==3.0.3 channels_redis==3.2.0 asgiref==3.3.1 daphne==3.0.1 I also use Redis 6. My routing looks like this application = ProtocolTypeRouter({ "http": get_asgi_application(), 'websocket': AuthMiddlewareStack( URLRouter( websocket_urls.urlpatterns ) ), }) Any suggestions on what I'm doing wrong here are welcome. -
is there a way to get the count of conflicts while using Django ...bulk_create(.., ignore_conflicts=True)?
I am using bulk_create to upload some data from excel to django db. Since the data is huge I had to use bulk_create instead of .create and .save. But the problem is that I need to show the user how many duplicate data has been found and has not been uploaded due to integrity error. Is there a way to get the number of errors or duplicate data while using bulk upload?