Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make more than one fields primary key and remove auto generated id in django models
Suppose in a relational database schema we have a student, a subject and a teacher which connect to each other with a relation teaches. Also, the relation has an attribute time that stores the time of the lesson. This is the most complete yet simplified example I can think to describe my case. Now, the most pythonic and django-wise way I can think of trying to reach a correct solution is, after creating a model class for student, subject and teacher, to create a new class Teaches, which has the foreign keys for the three other classes; also it has the property date field for time. This class would look something like this: class Teaches(models.Model): teachers = models.ForeignKey(Teacher, on_delete_models.CASCADE) subjects = models.ForeignKey(Subject, on_delete_models.CASCADE) students = models.ForeignKey(Student, on_delete_models.CASCADE) time = models.DateField class Meta: constraints = [ fields=['teachers', 'subjects', 'students'] name='teacher_subject_student_triplet' ] I added the Meta class because this is what this answer recommends as the correct approach. The problem is that that in the migrations file I can still see the id field. The only way I've seen there is to remove it is to set another field as Primary Key, but in my case I cannot do that, having more … -
Django wsgi file not configured correctly
I am attempting to get my django application working using wsgi and httpd on RH8. There seems to be a formatting issue pointing wsgi at the virtual environment. In the example I am following, there is an activate.py file. Am I missing something? I can see activate in other formats (activate.ps1 for example) in the bin directory. Here is my wsgi.py """ WSGI config for mysite project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/4.0/howto/deployment/wsgi/ """ python_home = '/opt/django/djangoenv' activate_this = python_home + '/bin/activate' with open(activate_this) as f: code = compile(f.read(), activate_this, 'exec') exec(code, dict(__file__=activate_this)) import os import sys from django.core.wsgi import get_wsgi_application BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(BASE_DIR) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dcn_automation.settings') application = get_wsgi_application() Here is the path to my virtual environment: /opt/django/djangoenv/bin/ When I run the server manually, I get this error: $ python3 manage.py runserver 0.0.0.0:8000 Performing system checks... System check identified no issues (0 silenced). September 21, 2022 - 11:01:02 Django version 4.1.1, using settings 'dcn_automation.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib64/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/lib64/python3.8/threading.py", line 870, in run … -
Django User Filtering and Pagination
I've built a filtering function to process user selected filtering on my Product model, however I'm having trouble making it work correctly with pagination. My view can process both a search bar query and product filtering. Currently I'm not sure how to allow the paginator to pass the next page of results. As you can see in the view / filtering function below this setup just processes a new request and returns all currently. View: @login_required @permission_required('products.view_product', raise_exception=True) def productQueryListView(request): context = { 'fascias': Fascia.objects.all() } if request.GET.get('page') == None: # Searchbar Query if request.GET.get('q') != None: queryResults = searchProducts(request) # Filter Query else: queryResults = processProductQuery(request) paginator = Paginator(queryResults, 50) page_number = request.GET.get('page') product_list = paginator.get_page(page_number) context.update({ 'product_list': product_list, 'product_count': paginator.count }) return render(request, 'products/product-query.html', context) Filter Function: def processProductQuery(request): fascias = request.GET.getlist('fascia') statuses = request.GET.getlist('status') initialDelivery = request.GET.get('initialdelivery') initialUpload = request.GET.get('initialupload') delivered = request.GET.get('delivered') uploaded = request.GET.get('uploaded') productQuery = Product.objects.all().distinct() if len(fascias) > 0: productQuery = productQuery.filter(fascia__in=fascias).distinct() if len(statuses) > 0: productQuery = productQuery.filter(status__in=statuses).distinct() if initialDelivery and len(initialDelivery) > 0: initialDelivery = datetime.datetime.strptime(initialDelivery, '%Y-%m-%d') productQuery = productQuery.filter(initial_delivery__date=initialDelivery).distinct() if initialUpload and len(initialUpload) > 0: initialUpload = datetime.datetime.strptime(initialUpload, '%Y-%m-%d') productQuery = productQuery.filter(initial_upload__date=initialUpload).distinct() if delivered and len(delivered) > 0: delivered = … -
Django Migrations - How can I migrate my own django models without any inbuild models like auth,sessions,sites,admin etc
I have a requirements so that its not possible to change given schema. I dont need any django inbuild models such as admin,auth,sessions,messages etc.. how can I migrate my models without the inbuild models. I will be gratefull if you can help me. Thank you. -
How to reuse a model-field's default automatically, when such field (its name) doesn't constitute the data fed to model-form constructor?
app.models.py: from django.db import models from main.custom_fields import HTTPURLField from main.function_validators import validate_md5 class Snapshot(models.Model): url = HTTPURLField(max_length=1999) content_hash = models.CharField(max_length=32, default='00000000000000000000000000000000', validators=[validate_md5]) timestamp = models.DateTimeField(auto_now=True) app.forms.py: from django import forms from .models import Snapshot class SnapshotModelForm(forms.ModelForm): class Meta: model = Snapshot fields = ('url', 'content_hash') app.views.py: from .forms import SnapshotModelForm def index(request): snapshot_form = SnapshotModelForm(data={'url': ' https://stackoverflow.com/ '}) if snapshot_form.is_valid(): model_instance = snapshot_form.save() I want my SnapshotModelForm instance (snapshot_form) to be populated also with a 'content_hash' and it' sdefault value (given in Snapshot class definition), when not fed via POST data or other kind (input) data used by ModelForm's constructor. -
Is it possible to change the inbuild validator Messages in Django Models
When ever i miss the email it should throw some other error message rather than Enter a valid email address models.py class Publisher(models.Model): email=models.EmailField(blank=True,null=True) serializer.py class PublisherSerializer(serializers.ModelSerializer): class Meta: model = Publisher fields = '__all__' -
Unique validation error with base_field of a django array field during update
I want the phone numbers inside my phones field to be unique across all customers. it works fine during creating a new customer, But during update i got a unique validation error. def prevent_replicated_phone(phone): # Count all customers which own the same number phone_holders = Customer.objects.filter(phones__contains=[phone]).count() if phone_holders > 0 : raise ValidationError( f'The phone number: {phone} already exist', class Customer(models.Model): def __str__(self) : return self.customer_name id = models.BigAutoField(primary_key=True) customer_name = models.CharField(max_length=100, null=False, blank=False, unique=True) phones = ArrayField(models.CharField(max_length=10, validators=[validate_phone_number, prevent_replicated_phone]), default=list, null=True, blank=True) customer_type = models.CharField(max_length=10,default='patient', choices=CUSTOMER_TYPE) Let say i have a customer hold the phones ['0795364588']. I send a put request to update the customer phones with new array ['0795364588', '0668123544']. Updating the customer phones with postman How i can solve this. -
Django return custom HTTP message
I'm trying to be compatible with an app-side bug(). I want to return a response with custom HTTP message For example, I get HTTP/1.1 429 TOO_MANY_REQUESTS now, I want get HTTP/1.1 429 CUSTOM_MESSAGE Howerver, I can get only h2 200 -
I can store password when want to create a user in django
Model this is my extended model with one to one field class Etudiant(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,null=True,blank=True) nom = models.CharField(max_length=50) prenom = models.CharField(max_length=50) username = models.CharField(max_length=50) num_cart = models.IntegerField(default=0) email = models.EmailField(max_length=254) date_naissance = models.DateField(auto_now=False, auto_now_add=False,blank=True,null=True) password = models.CharField(max_length=50,null=True,blank=True) groupe = models.ForeignKey("Group", on_delete=models.CASCADE,null=True,blank=True) this is the forms of user form and etudiant form forms.py class UserForm(forms.ModelForm): class Meta: model = User fields = ('username','first_name', 'last_name', 'email','password') widgets = { 'username' : forms.TextInput(attrs={'class':'form-control'}), 'first_name' : forms.TextInput(attrs={'class':'form-control'}), 'last_name' : forms.TextInput(attrs={'class':'form-control'}), 'email' : forms.EmailInput(attrs={'class':'form-control'}), 'password' : forms.PasswordInput(attrs={'class':'form-control'}), } class EtudiantForm(forms.ModelForm): class Meta: model = Etudiant fields = ('num_cart','date_naissance','groupe') widgets = { 'num_cart' : forms.NumberInput(attrs={'class':'form-control'}), 'date_naissance' : forms.DateInput(attrs={'class':'form-control'}), 'groupe' : forms.Select(attrs={'class':'form-control'}), } this views for store data to db all the data stored just the password I see "Invalid password format or unknown hashing algorithm. " #views.py def ajouter_etudiant(request): user_form = UserForm() etudiant_form = EtudiantForm() if request.method == 'POST': user_form = UserForm(request.POST) if user_form.is_valid() : user_form.save() user = User.objects.get(username = request.POST['username']) groupe_name = Group.objects.get(id=request.POST.get('groupe')) Etudiant.objects.create( user = user, username = user.username, nom = user.last_name, prenom = user.first_name, num_cart = 123456789123456789, email = user.email, date_naissance = request.POST.get('date_naissance'), groupe = groupe_name ) return redirect('all_etudiant') return render(request,'etudiant/ajouter-etudiant.html',{'form' : user_form,'form2':etudiant_form}) -
How to use prefetch_related to retrieve multiple rows similar to SQL result
I’ve a question about the usage of prefetch_related. Based on my understanding I need to use prefetch_related for reverse foreign key relationships As an example I have a User(id, name) model and SchoolHistory(id, start_date, school_name, user_id[FK user.id]) model. A user can have multiple school history records. If I’m querying the database using the following SQL query: SELECT user.id, name, start_date, school_name FROM user INNER JOIN school_history ON school_history.user_id = user.id the expected result would be: | User ID | Name | Start Date | School | | 1 | Human | 1/1/2022 | Michigan | | 1 | Human | 1/1/2021 | Wisconsin | This is the current result that I’m getting instead with ORM and a serializer: | User ID | Name | school_history | 1 | Human | [{start_date:1/1/2022 , school:Michigan}, {start_date:1/1/2021 , school:Wisconsin}] | This is the ORM query that I’m using: User.objects.prefetch_related( Prefetch( ‘school_history’ query_set=SchoolHistory.objects.order_by(‘start_date’) ) ) Is there a way for the ORM query to have a similar result as SQL? I want multiple rows if there are multiple schools associated with that user -
DRF SlugRelatedField causes extra queries with the argument `queryset` when making get request
in debug tool bar, I can tell there are duplicate queries pointing to source and target and also workflow. So I decide to make those two fields read_only=True and remove the queryset argument. And things work perfectly. my code looks like: # model class Activity(models.Model): class Meta: db_table = "activity" uuid = serializers.UUIDField(read_only=True) some fields ... class Flow(models.Model): class Meta: db_table = "workflow_flow" objects = FlowManager() source = models.ForeignKey( "Activity", db_index=True, related_name="outgoing", to_field='uuid', db_constraint=False, on_delete=models.CASCADE, max_length=32, null=True, blank=True, default="" ) target = models.ForeignKey( "Activity", db_index=True, related_name="incoming", to_field='uuid', db_constraint=False, on_delete=models.CASCADE, max_length=32, null=True, blank=True, default="" ) workflow = models.ForeignKey( "WorkFlow", db_index=True, related_name="flows", to_field='uuid', db_constraint=False, on_delete=models.CASCADE, max_length=32, ) # serializer class FlowSerializer(ModelSerializer): class Meta: fields = "__all__" model = Flow condition = serializers.CharField( default="", required=False, allow_null=True, allow_blank=True, write_only=True ) # foreign key source = serializers.SlugRelatedField( queryset=api_models.Activity.objects.all(), slug_field="uuid", ) target = serializers.SlugRelatedField( slug_field="uuid", queryset=api_models.Activity.objects.all() ) workflow = serializers.SlugRelatedField(slug_field="uuid", queryset=api_models.WorkFlow.objects.all()) # viewset class FlowViewSet(ModelViewSet): queryset = api_models.Flow.objects.all().select_related("source", "target", "workflow").all() lookup_field = 'uuid' serializer_class = api_serializers.FlowSerializer But I need to create those two fields any idea? I know I can change them to CharField Instead But I want a correct way to handle this. By reading the source code of the SlugRelatedField queryset is used for … -
How to implement a HTTP API with django
I have read that HTTP APIs are faster and more light-weight than REST APIs. However I only find resources that explain how to build REST APIs in django. How do you build a HTTP API and not a REST API in django? -
access URL data in serializers class in Django Rest Framework
I'm getting None while accessing the data of the request. views.py def get(self, request, post_id, post_language_id, user_id): ... paginator = CustomPageNumberPagination() response = paginator.generate_response(language_liked_data, PostLanguageLikedSerializer, request) return response but I need user_id from the URL so I found a way to access data through context. so I can access the value in the serializer. views.py def get(self, request, post_id, post_language_id, user_id): ... language_liked_data = PostLanguageLike.objects.filter(post_language_id=post_in_lang.id) post_language_like_serializer = PostLanguageLikedSerializer(language_liked_data, context={'user_id': user_id}, many=True) return Response({"response": True, "return_code": "success", "result": {"liked_users": post_language_like_serializer.data}, "message": success["success"]}, status=200) serializers.py class PostLanguageLikedSerializer(serializers.ModelSerializer): is_following = serializers.SerializerMethodField() ... class Meta: model = PostLanguageLike fields = [...,'is_following'] def get_is_following(self, obj): # here I want to access URL data. user_id = self.context.get("user_id") user_followings = UserFollowing.objects.filter(user_id=user_id, following_user_id=obj.user.id) is_following = True if len(user_followings) > 0 else False return is_following the issue is I'm not able to use context={'user_id': user_id} with paginator.generate_response is there any better way to get URL data in the serializer? -
Django local variable 'context' referenced before assignment
where is my mistake? Can anyone see it? view.py error -
Swagger not responding when adding urls from another django app
I have a simple Django app and want to include urls to project urls. Project urls look like this: from drf_spectacular.views import ( SpectacularAPIView, SpectacularSwaggerView, ) from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/schema/', SpectacularAPIView.as_view(), name='api-schema'), path('api/docs/', SpectacularSwaggerView.as_view(url_name='api-schema'), name='api-docs'), path('api/user/', include('user.urls')), #path('api/', include('LinkTaskApp.urls')), ] And LinkTaskApp urls look like this: from django.urls import path from .views import AccountListView urlpatterns = [ path('account/', AccountListView.as_view(), name='account-list'), ] As soon as I uncomment in the main urls: #path('api/', include('LinkTaskApp.urls')), I get following error when I start Swagger: Failed to load API definition. Errors Hide Fetch error Internal Server Error /api/schema/ In browser, it looks like this: Request URL: http://127.0.0.1:8000/api/schema/ Request Method: GET Status Code: 500 Internal Server Error Remote Address: 127.0.0.1:8000 Referrer Policy: same-origin Any Ideal how to successfully include this url and get swagger to work? -
how to run python manage.py migrate inside a docker container that runs Django with apache2
I'm running Django app inside Docker container with apache2, I need to add the command python manage.py migrate inside the Dockerfile or docker-compose but am unable to run it . Dockerfile FROM ubuntu RUN apt-get update # Avoid tzdata infinite waiting bug ARG DEBIAN_FRONTEND=noninteractive ENV TZ=Africa/Cairo RUN apt-get install -y apt-utils vim curl apache2 apache2-utils RUN apt-get -y install python3 libapache2-mod-wsgi-py3 RUN ln /usr/bin/python3 /usr/bin/python RUN apt-get -y install python3-pip #Add sf to avoid ln: failed to create hard link '/usr/bin/pip': File exists RUN ln -sf /usr/bin/pip3 /usr/bin/pip RUN pip install --upgrade pip RUN pip install django ptvsd COPY www/demo_app/water_maps/requirements.txt requirements.txt RUN pip install -r requirements.txt ADD ./demo_site.conf /etc/apache2/sites-available/000-default.conf EXPOSE 80 WORKDIR /var/www/html/demo_app CMD ["apache2ctl", "-D", "FOREGROUND"] CMD ["python", "manage.py", "migrate", "--no-input"] docker-compose version: "2" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=database_innvoentiq - POSTGRES_USER=database_user_innvoentiq - POSTGRES_PASSWORD=mypasswordhere - PGDATA=/tmp django-apache2: build: . container_name: water_maps environment: - POSTGRES_DB=database_innvoentiq - POSTGRES_USER=database_user_innvoentiq - POSTGRES_PASSWORD=mypasswordhere - PGDATA=/tmp ports: - '80:80' volumes: - ./www/:/var/www/html depends_on: - db what happens here is that the container exists after running the last CMD in the Dockerfile -
Why am I getting a No Reverse Match error when submitting using UpdateView?
I'm currently using UpdateView to add edit functionality to my Django project. It's working correctly insofar as I can edit my data, however when I submit the new data, it returns a NoReverseMatch error: NoReverseMatch at /MyHealth/edit/8 Reverse for 'health_hub_history' not found. 'health_hub_history' is not a valid view function or pattern name. I've researched it and added a get_absolute_url to my model, but it isn't working. Any help would be appreciated! models.py: from django.db import models from django.contrib.auth.models import User from django.urls import reverse class HealthStats(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField(auto_now=True) weight = models.DecimalField(max_digits=5, decimal_places=2) run_distance = models.IntegerField(default=5) run_time = models.TimeField() class Meta: db_table = 'health_stats' ordering = ['-date'] def get_absolute_url(self): return reverse('health_hub_history') def __str__(self): return f"{self.user} | {self.date}" urls.py: from django.urls import path from django.contrib.staticfiles.storage import staticfiles_storage from django.views.generic.base import RedirectView from . import views app_name = 'HealthHub' urlpatterns = [ path('', views.home, name='home'), path('MyHealth/', views.health_hub, name='health_hub'), path('MyHealth/update', views.UpdateHealth.as_view(), name='health_hub_update'), path('MyHealth/history', views.health_history, name='health_hub_history'), path('favicon.ico', RedirectView.as_view(url=staticfiles_storage.url("favicon.ico"))), path('MyHealth/delete/<item_id>', views.delete_entry, name='health_hub_delete'), path('MyHealth/edit/<int:pk>', views.EditHealth.as_view(), name='health_hub_edit'), ] Views.py: class EditHealth(UpdateView): model = HealthStats template_name = 'health_hub_edit.html' fields = ['weight', 'run_distance', 'run_time'] health_hub_edit.html: {% extends 'base.html' %} {% load static %} {%load crispy_forms_tags %} {% block content %} <div class="container-fluid"> <div class="row"> <div … -
Django - multiple context in single view
lune 90 context is working but line 112 context is not working in HTML Page Then, What should I do? code image -
django filter with the properties of the last object
I am trying to refactor this piece of code to improve time complexity by reducing the number of loops. items = DataActionItem.objects.filter(status='resolved', site_id=settings.SITE_ID) resolved = [] for item in items: init = [resolved.history_date for resolved in item.history.filter(status='resolved', history_date__lte=datetime.datetime.today(), history_date__gt=datetime.datetime.today() - datetime.timedelta( days=7)) if getattr(resolved.prev_record, 'status') != 'resolved'] resolved.append(max(init).date()) rc = Counter() rc.update(resolved) So far, this is what I have. DataActionItem.history.filter(site_id =40, status='resolved', history_date__lte=datetime.datetime.today(), history_date__gt=datetime.datetime.today()-datetime.timedelta(days=7)).values('id', 'history_date').distinct().annotate(day=TruncDate('history_date'), ).values('day').annotate(n=Count('id')).order_by('day') While writing this query, I got stuck at the point when I was checking the previous object. See below. getattr(resolved.prev_record, 'status') != 'resolved' I would like to compare each object in the query set to the last object and only return the ones that their previous history objects do not have a resolved status. If someone can help me cut down the number of loops in the original query, that will be great. -
Django4: Ajax AttributeError
I'm trying to create this Ajax request: The views file is as follows: reports/views.py from django.shortcuts import render from profiles.models import Profile from django.http import JsonResponse from .utils import get_report_image from .models import Report from .forms import ReportForm # Create your views here. def create_report_view(request): form = ReportForm(request.POST or None) if request.is_ajax(): image = request.POST.get('image') name = request.POST.get('name') remarks = request.POST.get('remarks') img = get_report_image(image) author = Profile.objects.get(user=request.user) if form.is_valid(): instance = form.save(commit=False) instance.image = img instance.author = author instance.save() # Report.objects.create(name=name, remarks=remarks, image=img, author=author) return JsonResponse({'msg': 'send'}) return JsonResponse({}) utils.py import base64, uuid from django.core.files.base import ContentFile def get_report_image(data): _ , str_image = data.split(';base64') decoded_img = base64.b64decode(str_image) img_name = str(uuid.uuid4())[:10] + '.png' data = ContentFile(decoded_img, name=img_name) return data urls.py from django.urls import path from .views import create_report_view app_name = 'reports' urlpatterns = [ path('save/', create_report_view, name='create-report'), ] forms.py from django import forms from .models import Report class ReportForm(forms.ModelForm): class Meta: model = Report fields = ('name', 'remarks') I'm not sure why but this is the error I'm getting. Does this mean that is_ajax() is no longer accepted with Django 4.1.1? If so how would I need to adjust the code? if request.is_ajax(): AttributeError: 'WSGIRequest' object has no attribute 'is_ajax' [21/Sep/2022 … -
How to pass CSRF token manually for POST requests in ajax Django
We have a Django app which works as an iframe and it works fine in Safari and Chrome Browsers but in Safari it is blocking all the cookies and sessions that causes all the post request to be forbidden due to no CSRF Cookie. So is there any way we can pass this CSRF cookie along with headers using AJAX post. -
How to group ModelMultipleChoiceField with widget CheckboxSelectMultiple into categories?
I have seen some similar questions on this site, but all of them propose an insanely complex solution to such a straight forward task, and it is the same solution that different users have copy/pasted from a single source somewhere. In a forms.Form I have: self.fields['objects'].queryset = Object.objects.all() Should it not be possible to access this objects category field in a template loop for checkboxes so it will be possible to sort them according to which category they belong? If not and one has to create a custom widget or field, it surely must be possible to do with a couple of lines and not 70+ like in other answers here? Thanks for your time and help, it is appreciated. -
how to add for loop in app layout plotly dash
I want to add a for loop in the app layout, but my approach is wrong. Do you have any idea to make this work? for example. app.layout = html.Div(children=[ for x in data: //invalid syntax html.Div([ dcc.Graph( id='my-id', animate=True, figure={'data': graph, 'layout': layout}, ), ]), ] ) it's invalid syntax. But I want to for loop the html.div so that the graph will show repeatedly based on number of data. -
I try to create a superuser but the error is no such table: users_user
the error is : django.db.utils.OperationalError: no such table: users_user this is my model: class User(AbstractUser): pass the settings: AUTH_USER_MODEL = 'users.User' -
Azure App Service: How to run management command for dockerized django application
I've a django applicaiton running in docker-compose in local along with an nginx and frontend applicaiton. I've tried to deploy the applicaiton in azure app service using my custom docker image for the django application. The app deployment was successfull but now i need to run django management command like python manage.py migrate and python manage.py createsuperuser. I tried to use SSH in my django container, but when i tried to connect its showing az webapp create-remote-connection --subscription <id> --resource-group <rg-name> -n <app-anme> & Is there any other way to run django management commands in azure app service with a multi-container application.