Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: 'class Meta' got invalid attribute(s): constraints. how can i solve this problem
when i run python .\manage.py makemigrations i get this error TypeError: 'class Meta' got invalid attribute(s): constraints but i think in my Class Meta: all good but for some reason i get this problem. However, when i run in the terminal my server is run but in the server not run enter image description here this is my view.py (api.py) file api.py # Django from django.contrib.auth import authenticate, login from django.shortcuts import render, redirect from django.contrib.auth.forms import AuthenticationForm # Rest-Framework from rest_framework import status from rest_framework.authtoken.models import Token from rest_framework.generics import RetrieveAPIView, ListCreateAPIView from rest_framework.views import APIView, Response # Project from .models import User from .serializers import RegisterViewSerializer, SignInOutSerializer, SignInSerializer, UserListSerializer, \ UserUpdateSerializer, CodeSerializer from .utils import send_sms class RegisterView(APIView): def post(self, request): schema = RegisterViewSerializer(data=request.data) schema.is_valid(raise_exception=True) email = str(schema.validated_data['email']).lower() password = schema.validated_data['password'] first_name = schema.validated_data['first_name'] last_name = schema.validated_data['last_name'] phone_number = schema.validated_data['phone_number'] birth_date = schema.validated_data['birth_date'] verify_code = schema.validated_data['verify_code'] is_verify = schema.validated_data['is_verify'] check_user = User.objects.filter(username__iexact=email) if check_user.exists(): return Response({'error': 'user exists'}, status=status.HTTP_400_BAD_REQUEST) user = User.objects.create_user(username=first_name, email=email, password=password) user.first_name = first_name user.last_name = last_name user.phone_number = phone_number user.birth_date = birth_date user.verify_code = verify_code user.is_verify = is_verify user.save() token, _ = Token.objects.get_ot_create(user=user) return Response({'token': token.key})` class SignInView(APIView): def post(self, request): schema = SignInSerializer(data=request.data) … -
Django - Calculating age until a date in DB
I'm new to Django. Please help me with this issue. This is the model that I want to write query on. class ReservationFrame(models.Model): id = models.AutoField(primary_key=True) start_at = models.DateTimeField(db_index=True) information = models.JSONField(default=dict) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) The json field (ReservationFrame.information) has this format { upper_age_limit: 22, lower_age_limit: 30 } I want to calculate the age of login user until ReservationFrame.start_at, and return the corresponding ReservationFrame if upper_age_limit <= user.age <= lower_age_limit The formula that I'm using to calculate age is start_at.year - born.year - ((start_at.month, start_at.day) < (born.month, born.day)) I'm using annotate but getting errors. person_birthday = request.user.person.birthday frames_without_age_limit = reservation_frames.exclude(Q(information__has_key = 'upper_age_limit')&Q(information__has_key = 'lower_age_limit')) reservation_frames = reservation_frames.annotate( age=ExtractYear('start_at') - person_birthday.year - Case(When((ExtractMonth('start_at'), ExtractDay('start_at')) < (person_birthday.month, person_birthday.day), then=1), default=0)) reservation_frames = reservation_frames.filter( Q(information__lower_age_limit__lte = F('age'))| Q(information__lower_age_limit=None) ) reservation_frames = reservation_frames.filter( Q(information__upper_age_limit__gte = F('age'))| Q(information__upper_age_limit=None) ) TypeError: '<' not supported between instances of 'ExtractMonth' and 'int' -
How can i add numbers in django admin panal user usernames
this is just to make stack overflow happy not my question I'm developing a system based on Django admin. So all models could be edited also only from admin site. Model has a char field 'user'. I want to set current logged in admin username (or firstname, or lastname) as default value to 'user' field. How could I implement this? Default values are set as parameters when defining model fields, so I guess no request object could be recieved? Maybe I should set the value when creating instance of model (inside init method), but how I could achieve this? -
Trying to relate tables in Django
trying to POST request and create new location. now the filed country_id cues many troubles. those are the classes class Country(models.Model): id = UUIDField(primary_key=True, default=uuid.uuid4, editable=False) country_name = CharField(max_length=255) federal_rate = FloatField() social_security = FloatField() comment = CharField(max_length=255) class Location(models.Model): participant_id = ForeignKey('Participant', on_delete=CASCADE, related_name="locations") country_id = ForeignKey('Country', on_delete=CASCADE, related_name="country") start_date = DateField() end_date = DateField() region = CharField(max_length=255) tax_policy = CharField(max_length=255, null=True) Serializer class CountrySerializer(serializers.ModelSerializer): class Meta: model = Country fields = "__all__" class LoactionSerializer(serializers.ModelSerializer): country_id = CountrySerializer(many=False) class Meta: model = Location fields = "__all__" now the only why that I mange to join the tables are adding the country_id line in the seirializer, and whem im trying to create new location, an error occur this is the way I'm trying to add new location { "start_date": "2021-10-10", "end_date": "2021-11-18", "region": "markian-land", "tax_policy": "N/A", "participant_id": "c5c1a00c-4263-418a-9f3a-3ce40a1ea334", "country_id": "9067e71f-c6b9-4ecc-ad6b-461843063aee" } the Error - {"country_id": {"non_field_errors": ["Invalid data. Expected a dictionary, but got str."]}} when i mange to send as dict, but i have another error that asking for all Country fields, so i get the specific country from data base, and when im sending it i got json error -
redirect to next url in dajngo
hi i want redirect user to next url but its not working and redirect to home url when user want go to detail page , if the user is not logged in , the user redirect to login page and next_url = '/post/1/' but when the user is logged in , next_url = None and redirect to home page What is the problem? def user_login(request): next_url = request.GET.get('next') if request.method == 'POST': form = UserLoginForm(request.POST) if form.is_valid(): cd = form.cleaned_data user = authenticate(request, username=cd['username'], password=cd['password']) if user is not None: login(request, user) messages.success(request, 'you logged in successfully', 'success') if next_url: return redirect(next_url) return redirect('home:index') else: messages.error(request, 'wrong username or password', 'warning') else: form = UserLoginForm() return render(request, 'account/login.html', {'form':form}) -
How to display a user friendly error message from a UniqueConstraint?
I have a model with a unique field: class MyModel(models.Model): start_date = models.DateField( verbose_name='Start date', blank=False, null=False, unique=True, error_messages={'unique':"This start date has already been registered."} ) However, when I save an instance of this model that violates this UniqueConstraint I get an IntegrityError rather than the form error message. duplicate key value violates unique constraint "myapp_mymodel_start_date_af14e233_uniq" DETAIL: Key (end_date)=(2021-10-21) already exists. How do I output a "clean" user-friendly error message? -
Pycharm is no more identifying my existing django project and opening as django project
I did git pull to take new changes from remote to my local django project. After doing that when I click on manage.py to open my django project. It is not opening it as django project as it used to do before. It can be seen from the black marked area as it is not showing my apps and when i try to edit other files in my apps it gives me dialog box saying this. It is so annoying can anyone tell me hwo to fix my pycharm??? -
Django/React - Azure App Service can't find static files
I've deployed my Django React app previously through a dedicated server and now I am trying to achieve the same with Azure Web App function so I can use CI/CD easier. I've configured my project as below but only my django appears to deploy as I get a '404 main.js and index.css not found'. This makes me think there is an issue with my static file configuration but I'm unsure. .yml file: name: Build and deploy Python app to Azure Web App - test123 on: push: branches: - main workflow_dispatch: jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: npm install, build, and test run: | npm install npm run build --if-present working-directory: ./frontend - name: Set up Python version uses: actions/setup-python@v1 with: python-version: '3.8' - name: Create and start virtual environment run: | python -m venv venv source venv/bin/activate - name: Install dependencies run: | pip install -r requirements.txt python manage.py collectstatic --noinput - name: Zip artifact for deployment run: zip pythonrelease.zip ./* -r - name: Upload artifact for deployment job uses: actions/upload-artifact@v2 with: name: python-app path: pythonrelease.zip # Optional: Add step to run tests here (PyTest, Django test suites, etc.) deploy: runs-on: ubuntu-latest needs: build environment: name: … -
How to execute Google social authentication using dj-rest-auth in React JS
I am following this 2-part tutorial of using dj-rest-auth in django part 1 - part 2 by: Mohamad Fadhil and I have no problem with the backend in Django but I was wondering if anyone could show me how to implement this on react instead of Nuxt? -
How do swap the indexes of a Posts?
I have model with order indices, for example - 1, 2, 3, 5, 8, 10... (empty indices were allegedly removed - 4, 6, 7, 9...) I need to get the index and swap it with the nearest index next to it. (for Up and Down move). What I have: def set_order_index(item: Posts, distinction: int): items_to_swap = Posts.objects.filter( order_index=item.order_index + distinction) if len(items_to_swap) > 0: item_to_swap = items_to_swap[0] item_to_swap.order_index = item.order_index item_to_swap.save() item.order_index += distinction item.save() And for Up views '+1': def up_item(request, id): item = Posts.objects.get(id=id) set_order_index(item, +1) return redirect('index') And for Down '-1'... But my set_order_index only does +1 and -1 always, and if it gets the same value, then swaps places. That is if index 3, the set_order_index will only make 4 (+1), but I need to swap 3 with 5. Because there is no index 4. And if I use Post with index 10 to Down - I need to swap with 8, but my set_order_index only do -1, and I get only 9. But I need 10 to swap with 8 immediately. In my head, I understand how to do this through QuerySet, getting the indices of all that is > and < and then select … -
Django Custom Filter Tags and access query
Hi need some help on Django custom filter tag, much appreciated! I have registered a filter tag to access dictionary in HTML files like below: DIRECTORY - blog>templatetags>post_extras.py @register.filter def get_item(dictionary, key): return dictionary.get(key) A dictionary named dict_post, the key is the post id, and the values is the query set. Let say to get dictionary key of 1: DIRECTORY - blog>templates>blog>home.html {{ dict_post|get_item:1 }} It returns 'title' and 'date_posted' in a queryset Post('dsdsdsdqqq111', '2021-10-03 10:24:40.623754+00:00') It worked well for the filter tag, but when I want to access some query after the filter tags , it return errors. How to only get the title? I have tried the code like below, but return errors DIRECTORY - blog>templates>blog>home.html {{ dict_post|get_item:1.title }} Error: VariableDoesNotExist at / Looking for help, thanks! -
Model idea to make add to cart service with exclusive sub_service
I am making project where user can add services Like pest_control to their cart. Also additionally user can also add Exclusive sub_service like cleaning_house, sanitizing_house to existing service -pest_control to their cart view cart data structure be like this: { "service":"Pest Control:, "service_price":500, "sub_service":[ { "service_name":"House Cleaning", "service_price":150, }, { "service_name":"Sanitizing House", "service_price":100, } ] } So, How would be Models for cart would be so that above data structure can be achieve, and if parent services is removed from cart then child also be removed. and child service is added without parent then it must not allow my Existing service model is: class Services(models.Model): service_id = models.AutoField(primary_key=True) parent_id = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True,related_name='sub_service') price = models.FloatField(null=True, blank=True) service_name = models.CharField(max_length=100) service_icon = models.CharField(max_length=500, null=True, blank=True) service_image = models.CharField(max_length=500, null=True, blank=True) service_description = models.TextField( null=True, blank=True) duration = models.CharField(max_length=100,null=True,blank=True) crew = models.IntegerField(null=True,blank=True) -
Django crashes when two users run a C extension at the same time
Summary of the problem I am calling my own C extension for Python in Django, which is in charge of some long computations. The extension works fine and even the user can navigate through the Django app while the C extension makes its computations, since I have implemented Global Interpreter Lock (GIL) management inside the extension. However, when another user tries to execute the extension (while it is running for the initial user), Django crashes (process is killed) without any error message. Minimal Reproducible Example In the code below, you can see the Django view that calls (via a request POST) the C extension ftaCalculate. import ftaCalculate from django.views.generic.base import TemplateView # Computation class ComputationView(TemplateView): template_name = 'Generic/computation_page.html' @staticmethod def get_results(request): if request.method == "POST": # When button is pressed # Long computations cs_min = ftaCalculate.mcs(N, tree) else: cs_min = None return render(request, ComputationView.template_name, {'cs_min': cs_min}) Django crashes when two users run in parallel the function ftaCalculate.mcs. Is it normal that this behavior happens or am I missing something that needs to be implemented in the C extension? -
Operations between multiple columns from multiple tables
I am working on a project with Django and I faced an issue on database level when sometimes I need to apply mathematical operations across multiple fields of multiple tables. I did some research and could not find anything exactly suitable to do on Django Model level, so for now I wrote custom raw SQL for my problems. An example would be this: SELECT (s.a_s * tc.value) AS hours FROM {s} as s, {t_c} as tc WHERE s.id=%s and tc.key='s_per_tc' My question is: is it possible to sort this kind of issue with Django Model module, or should I keep writing custom queries for such operations? The operations might become more complex involving 3+ tables, etc. -
How do I create and save an unknown amount of variables to Django Model?
I am working with the twitter api via tweepy and I am unsure how to save an unknown quantity of media urls to a model object. The media section is where I am stuck. Some tweets will have media urls and some wont, while some may have numerous media urls. How do I create an unknown amount of media url variables and then how do I add that to the update_or_create? I appreciate all your help... been trying to figure this out for awhile now. user = api.get_user(screen_name=team) timeline = tweepy.Cursor( api.user_timeline, id=team, exclude_replies=True, include_rts=False).items(20) handle = user['screen_name'] location = user['location'] description = user['description'] for tweet in timeline: tweet_id = tweet['id'] date = tweet['created_at'] content = tweet['text'] `This is where I am stuck` if 'media' in tweet.entities: for media in tweet.extended_entities.media: url = media['media_url'] Tweets.objects.update_or_create( tweet_id=tweet_id, defaults={ 'handle': handle, 'tweet_id': tweet_id, 'location': location, 'description': description, 'date': date, 'content': content, 'url': url} ) -
django model user create index for first_name, last_name
I use settings.AUTH_USER_MODEL as default user model And I want to create index on public.auth_user.first_name public.auth_user.last_name Are there any elegant way to create this indexes ? -
Circular references in REST API
I'm developing a REST API (using Django Rest Framework) and am struggling with the problem of potential circular references in the data that is returned from each endpoint. I have decided to keep the API flat, rather than nested, as I think it makes a lot of other things (permissions, for example) more straight-forward. So say, for instance, that I am doing the classic blog + posts + comments structure... class Post(models.Model): title = models.CharField() content = models.TextField() author = models.ForeignKey(User) class Comment(models.Model): post = models.ForeignKey(Post) content = models.TextField() If my API has endpoints like:- /api/posts/1/ and:- /api/comments/1/ then they could easily end up serializing to:- { 'title': 'My Title', 'content': 'The content', 'author': { // user name, email etc. } } and:- { 'post': { 'title': 'My Title', 'content': 'The content', 'author': { // user name, email etc. } }, 'content': 'The comment' } Which is fine. But it means that I have to "know" to do select_related on Users when I'm fetching comments, simply because by doing that, I'm fetching the post that the comment is attached to and that has an author which is a User. I can see this getting messy and I'm foreseeing circular references … -
Error running WSGI application in Pythonanywhere
I have researched a lot and found this is a very common question. But the fact is I believe somehow pythonanywhere can not detect my settings.py file. Moreover, I have checked with the settings file directory and it is the same path as I have input in the WSGI file. I have also installed the required pip files but still getting the same errors. Error running WSGI application ModuleNotFoundError: No module named 'widget_tweaks' File "/var/www/ewallet_pythonanywhere_com_wsgi.py", line 33, in <module> application = get_wsgi_application() File "/home/ewallet/.virtualenvs/myenv/lib/python3.7/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/home/ewallet/.virtualenvs/myenv/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/ewallet/.virtualenvs/myenv/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/ewallet/.virtualenvs/myenv/lib/python3.7/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) Here is the wsgi.py import os import sys path = '/home/ewallet/E-wallet/ewallet/ewallet/' if path not in sys.path: sys.path.append(path) from django.core.wsgi import get_wsgi_application os.environ['DJANGO_SETTINGS_MODULE'] = 'ewallet.settings' application = get_wsgi_application() Here is the directory image Kindly help me to find the bug here. Thank you -
Using the same form multiple times over a single column in a template Django
I gotta a school management web app. In my app teachers can create exams and then add grades to that. I've created a separate model for grades. This is my models right now: class Grade(models.Model): student = models.ForeignKey( Student, on_delete=models.CASCADE, related_name="grade_user", ) subject = models.ForeignKey( Subject, on_delete=models.CASCADE, related_name="grade_subject", ) grade = models.DecimalField(max_digits=6, decimal_places=2) class Exam(models.Model): ... grades = models.ManyToManyField( Grade, related_name="exam_grades", blank=True, ) Now I've created a form like following: Teachers fill the fields and then using a single button this should be submitted. But the problem is that I don't know how to implement such implementation. I read somethings about formsets but I want the fields to be in a single column. Is there any way to get this done? -
Mongodb django settings
I have a django project which in local it works fine. I deploy on a remote server but mongodb it seems doesn’t work because I have this partial traceback: djongo.exceptions.SQLDecodeError: Keyword: FAILED SQL: SELECT "station"."station_name", "station"."id_station" FROM "station" Params: () Pymongo error: OrderedDict([('ok', 0.0), ('errmsg', 'command find requires authentication'), ('code', 13), ('codeName', 'Unauthorized')]) Version: 1.3.6 Sub SQL: None FAILED SQL: None Params: None Version: None The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/kafka/anaconda3/envs/djangocrops/lib/python3.9/site-packages/django/db/utils.py", line 97, in inner return func(*args, **kwargs) File "/home/kafka/anaconda3/envs/djangocrops/lib/python3.9/site-packages/djongo/cursor.py", line 70, in fetchmany raise db_exe from e djongo.database.DatabaseError The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/kafka/anaconda3/envs/djangocrops/lib/python3.9/threading.py", line 973, in _bootstrap_inner self.run() File "/home/kafka/anaconda3/envs/djangocrops/lib/python3.9/threading.py", line 910, in run I set my mongodb (on the server it runs locally) in settings and in a utils.py file: DB django settings: DATABASES = { 'default': { 'ENGINE' : 'djongo', 'NAME' : 'meteodata', 'HOST': '127.0.0.1', #localhost', 'PORT': 27017, 'USERNAME': 'admin', 'PASSWORD': 'mypwd', 'MONGO_URI': "mongodb://admin:mypwd@127.0.0.127017/meteodata" } } utils.py from pymongo import MongoClient import pymongo def get_db_handle(db_name, host, port, username, password): #, username, password): client = MongoClient(host=host, port=int(port), username=username, password=password, authSource="admin", )# localhost 27017 … -
how to solve cors policy
I have installed django-cors-headers and in settings.py : MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', ] ALLOWED_HOSTS = os.environ.get("ALLOWED_HOSTS","").split() CORS_ALLOW_ALL_ORIGINS = True but i get cors policy error and cant connect to api : Access to XMLHttpRequest at 'https://event-alpha.mizbans.com/api/meetings/?memory=0' from origin 'https://alpha.mizbans.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. xhr.js:177 GET https://event-alpha.mizbans.com/api/meetings/?memory=0 net::ERR_FAILED what should i do?(ps: i got this error on the deployed version) -
Is there a way to resign variable in Django template?
I'm working on a Django Project. I'll want to resign a variable in the Django template. Here is the code of views.py (index function): def index(request): global title return render(request, "encyclopedia/index.html", { "title": title }) Here is the code of index.html: {% extends "encyclopedia/layout.html" %} {% block title %} Encyclopedia {% endblock %} {% block body %} <h1>All Pages</h1> <!-- I want to resign the title variable here --> {% endblock %} Is there any way we can resign the variable? -
after moving project to another dir it show this error ImportError: cannot import name 'python_2_unicode_compatible' from 'django.utils.encoding'
my project was running correctly before I moved my project to another directory and it started to show this error I did not change anything but I moved it in my d drive $ python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\waqar\AppData\Local\Programs\Python\Python39\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Users\waqar\AppData\Local\Programs\Python\Python39\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "D:\my project\My All Project\school\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "D:\my project\My All Project\school\venv\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "D:\my project\My All Project\school\venv\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "D:\my project\My All Project\school\venv\lib\site-packages\django\core\management\__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "D:\my project\My All Project\school\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "D:\my project\My All Project\school\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "D:\my project\My All Project\school\venv\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "D:\my project\My All Project\school\venv\lib\site-packages\django\apps\config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "C:\Users\waqar\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", … -
About Django Test
Assumption I'm developing an application with Django. The authentication is implemented using "django-allauth". Problem I'm try to write unit tests, but I don't know if I should write tests for the authentication process, because tests are already written like this. Can anyone teach me if I should write tests for the authentication process? -
AttributeError: 'MetaDict' object has no attribute 'get_field' django_elasticsearch
I want to use elasticsearch within django app and send some data from model object to it but there is a problem with I am already using django-elasticsearch-dsl library. here`s my django_elasticsearch configuration: from django_elasticsearch_dsl import Document, fields from django_elasticsearch_dsl.registries import registry from core.models.src.errorLog import errorLog @registry.register_document class ErrorLogDocument(Document): class Index: name = 'errors' settings = { 'number_of_shards': 1, 'number_of_replicas': 0 } class Django: model = errorLog fields = [ 'time', 'date', 'error', 'place', ] but when I run my app I get this error and don`t know how to handle this: django_field = django_attr.model._meta.get_field(field_name) AttributeError: 'MetaDict' object has no attribute 'get_field' Can anyone help this???? Blockquote enter code here