Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I deploy django with apache2
I have Django project that I need to deploy on a VPS and give it domain and SSL certificate and I did that but I still need the ssl certificate so I found that certbot and It worked on the apache well but when I try it using wsgi.py it does nothing at all so I've searched about how to deploy using apache or nginx and all the tutorials didn't work for me so how can I deploy django project using apache2. -
A Django app to take user uploaded locatio
I want to build a Django app to allow users upload their locations which will later be displayed on a map. I would also like to have a search feature where visitors can search and find those uploaded locations. Any help? -
How do I create a custom Django AllAuth Socialaccount model?
Here is a summary of app I am attempting to create: I want users (who are primarily students) to register in my app using their Google Accounts. The service I am using to manage this creation of accounts is Django-AllAuth. Django-AllAuth has a very limited Social Account Model (it only saves username, email, name and their roles). I want to have further fields that I save in my DB. I want to save my users' Year Group and Favourite Subject. How a user registers on my website: User is redirected to a "Sign in With Google" page. Google will return the following fields: the user's name, Google ID and email. Then, I want to prompt the user to a "Finish registering Account" page. In this page, the user will have to fill out input fields for their Username, Year Group and Favourite Subject I cannot find any solutions for this specific case. My Questions How do I create a custom Social Accounts Model in Django-AllAuth? How do I ask users to fill out another Finishing Registering Form? I am aware that you can redirect users to a Finishing Registering Form via this code in the settings.py file. However, this form … -
DRF: Serialization with cross reference table
I have 3 models, the first one contains controller names and their IDs, the second measurements and their IDs and the third has foreign keys to both and is used as a cross reference based on IDs. With the following serializer and view i can have my API return the measurements each controller has. Serializer: class MeasurementsSerializer(serializers.ModelSerializer): # used in stationsMeasurementsInfo view def create(self, validated_data): pass def update(self, instance, validated_data): pass class Meta: model = Measurements fields = ['code', 'measurement', 'unit', 'type'] View: class stationsMeasurementsInfo(generics.ListAPIView): #returns the measurements a station tracks #authentication_classes = (TokenAuthentication,) #permission_classes = (IsAuthenticated,) serializer_class = MeasurementsSerializer def get_queryset(self): source = self.kwargs['sourceName'] name = self.kwargs['stationName'] final = Measurements.objects.filter(microcontrollersmeasurements__microcontroller__name=name) return final def list(self, request, *args, **kwargs): res = super(stationsMeasurementsInfo, self).list(request, *args, **kwargs) res.data = {"source": self.kwargs['sourceName'], "stations": [{ "station": self.kwargs['stationName'], "measurements": res.data } ] } return res The problem is that i cannot actually retrieve the name of the controller, currently i manually insert it in the list which means that i cannot retrieve the measurements of multiple controllers with a single API call. How would i go about fixing this issue? -
Page not found (404) No article found matching the query
#models.py from django.db import models from django.contrib.auth import get_user_model from django.urls import reverse from ckeditor.fields import RichTextField class Article(models.Model): title = models.CharField(max_length=200) body = RichTextField() photo =models.ImageField(upload_to='images/', blank=True) date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE ) def str(self): return self.title def get_absolute_url(self): return reverse('article_detail', args=[str(self.id)]) class Comment(models.Model): article = models.ForeignKey(Article, related_name="comments", on_delete=models.CASCADE) comment = models.TextField(max_length=150) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE ) date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.comment def get_absolute_url(self): **return reverse('article_detail', args=[str(self.id)])** class Meta: ordering = ['-date'] -
How to create django dropdown list
I need to create a dropdown list in a datatable field using django in order to display all the countries and enable the user to choose one and get a response. I have tried this code but it does not work. models.py class Datatable(models.Model): COUNTRY_CHOICE = ( ('MA', 'MA'), ('FR', 'FR'), ('US', 'US'), ) Country = models.CharField(blank=True, choices=COUNTRY_CHOICE, max_length=100) datatable.html <th class="Country"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Custumer Country </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> <a class="dropdown-item" href="#MA">MA</a> <a class="dropdown-item" href="#FR">FR</a> <a class="dropdown-item" href="#US">US</a> </div> </th> Any help would be great. Thank you ! -
Proxying shiny-server through Django and nginx
I'm running a docker containerized django app with nginx as a reverse proxy and want to include several shiny apps I've inherited. I want django to sit between shiny-server (which serves the apps) and the client (i.e. NOT reverse proxy certain urls directly to shiny-server). However shiny-server seems to be trying to use some kind of websocket and hence while some elements of the ui render properly, the main files (leaflet maps, plots etc) don't. Instead I get a gray overlay. The console displays some cryptic error messages i.e. Connection closed. Info: {"isTrusted":false}. My nginx configuration is as follows: #Connect to upstream shiny apps server upstream shiny { server shiny:80; } #Connect upstream django server via uWSGI upstream django { server django:8001; } #Required for shiny's WebSockets map $http_upgrade $connection_upgrade { default upgrade; '' close; } server { listen 80; server_name 127.0.0.1; resolver 127.0.0.11; #Production settings #listen 8000; #server_name 195.134.90.182; charset utf-8; client_max_body_size 100M; #Serve django's media (Not Implemented) location /media/ { alias /var/www/media; } location /static/ { alias /var/www/static; } location / { proxy_http_version 1.1; # you need to set this in order to use params below. proxy_pass http://django; proxy_set_header X-forwarded-FOR $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header … -
Problem with updating the value in 1 column in Django database
I have a search model that is saving all search terms that users are typing. Everything is fine except updating total_searches column that I want to update if user will insert exactly the same query. For instance if 3 users will put python in search bar I want to increment value in total_searches column. If the text will be different then create a new "row" in my table. Right now, Django is inserting a new row every time when I search for something and it is just putting 1 in total_searches. How can I fix this? models.py class SearchQueryTracker(models.Model): id = models.AutoField(primary_key=True) author = models.ForeignKey(User, blank=True, null=True, on_delete=models.DO_NOTHING, unique=False) #settings INSTALLED_APPS total_results = models.IntegerField('Search results', default=0) total_searches = models.IntegerField('User searches', default=0) search_term = models.CharField(max_length=1000, blank=True, null=True) searched_on = models.DateTimeField('searched on', default=timezone.now) views.py @login_required def SearchViewFBV(request): query = request.GET.get('q') query_list = request.GET.get('q', None).split() user = User.objects.get(email=request.user.email) find_duplicate_results = SearchQueryTracker.objects.filter(search_term=query).update(total_searches=F('total_searches') + 1) search_tracker = SearchQueryTracker() articles = Article.objects.filter(status=1).order_by('-publish') questions = QA.objects.filter(status=1).order_by('-publish') # combine querysets queryset_chain = chain( articles, questions, ) qs = sorted(queryset_chain, key=lambda instance: instance.pk, reverse=True) count = len(qs) search_tracker.total_results = count search_tracker.total_searches = find_duplicate_results search_tracker.author = user search_tracker.search_term = query search_tracker.save() context = { 'query': query, 'count': count, 'query_list': qs, … -
Django not installing in pipenv on Mac
I'm trying to install Django in pipenv, but it keeps giving me error messages user@users-MacBook-Pro-2 \~ % cd Desktop user@users-MacBook-Pro-2 Desktop % mkdir storefron user@users-MacBook-Pro-2 Desktop % cd storefron user@users-MacBook-Pro-2 storefron % virtualenv install django zsh: command not found: virtualenv user@users-MacBook-Pro-2 storefron % pipenv install django zsh: command not found: pipenv user@users-MacBook-Pro-2 storefron % please any help here user@users-MacBook-Pro-2 storefron % pipenv install django zsh: command not found: pipenv This was suppose to help install Django on the pip virtual environment in the storefron folder created. on the desktop -
Get count of related items and subtract that from attribute in django
I've got three models and I'm trying to simplify my querries a bit. I'm trying to return a list of Course objects that have not been completely registered/paid for. So I need to get a count of the Payment objects, and then see if that is equal to the total available_seats on a Course object. I've got a Payment, Course, and Registration model: class Payment(models.Model): payment = models.ForeignKey(Payment, on_delete=models.PROTECT) registration = models.ForeignKey(Registration, on_delete=models.PROTECT) is_refunded = models.BooleanField(default=False) class Course(models.Model): course = models.ForeignKey(Course, on_delete=models.PROTECT) location = models.ForeignKey(Location, on_delete=models.PROTECT) seat_count = models.IntegerField() class Registration(models.Model): person = models.ForeignKey(Person, on_delete=models.PROTECT) course = models.ForeignKey(Course, on_delete=models.PROTECT) comments = models.CharField(max_length=200, blank=True, null=True) I only want to consider a seat 'taken' if a Payment has been made - so a count of Payment for a given Course is what I'm trying to get. I was trying something like this: payments = ( Payment.objects.filter( registration__course__id=OuterRef("pk"), is_refunded=False ).values("pk") # .annotate( # total_seats_available=F("registration__course__seat_count") # - Count("registration") # ) # .values("total_seats_available") ) courses = ( Course.objects.filter(id__in=course_ids) .prefetch_related( Prefetch( "registration_set", queryset=Registration.objects.prefetch_related( "payment_set" ), ) ) .annotate( paid_seats=Case( When( Exists(payments), then=Count(payments), ), default=None, ), has_available_seats=Case( # No Payment have been recorded When(paid_seats=None, then=Value(True)), # Payment exist and total_seats_available should calc When(paid_seats__gt=0, then=Value(True)), # Default to … -
Django save variable from views to models
I need help with one thing in my django project. I have class games in my views.py which is connected to the path in URLs. The game's class can now take the game_id, player_id, and score values and then use a variable to output them on the result.html page, which works. Instead of listing these values on the page, I need to store these values in a SQL database in Django in a pre-created location using models. models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user_rec = models.ForeignKey(User, on_delete=models.CASCADE) birth_date = models.DateField(null=True, blank=True) game1_score = models.IntegerField(null=True, blank=True) game2_score = models.IntegerField(null=True, blank=True) game3_score = models.IntegerField(null=True, blank=True) class Meta: verbose_name_plural = 'Profile' def __unicode__(self): return u"%s's Subscription Info" % self.user_rec @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() views.py from django.http import HttpResponse from django.contrib.auth.models import User from django.contrib import messages from django.shortcuts import redirect, render from django.contrib.auth import authenticate, login, logout from authentication.models import Profile from rocnikovka import settings from django.core.mail import EmailMessage, send_mail from django.contrib.sites.shortcuts import get_current_site from django.template.loader import render_to_string from django.utils.http import urlsafe_base64_encode,urlsafe_base64_decode from django.utils.encoding import force_bytes, force_str … -
Can we import local csv file data in Django?
i dont to develop a search system in which we are going to import data from csv file which is local file in our computer, i want to import the csv file in django to store it's value in dictionary. but i am not able to import the data in django. here is code and image, and this is view.py file code in which i add csv from unicodedata import name from django.shortcuts import redirect, render from django.http import HttpResponse from django.template import context import csv def index(request): context = {'name':'xyz'} file = open("railway_stations.csv") csvreader = csv.reader(file) rows = [] d = dict() for row in csvreader: rows.append(row) for r in rows: d.update({r[0]:r[1]}) print(r[0]) print(d["Prescot"]) file.close() return render(request, 'home.html',context) and my railway_stations.csv file is in following image \ please please suggest me who to do it. (who to import csv to view.py file) i just try simple import csv to import the csv, i am expecting how to import the csv file in a view.py file so that i am render all the data in html file.also i do it in python in fine way but now i am facing difficulty in django or you can also suggest me good … -
How Can I implement device-based authentication with Django & DRF?
How can I implement device-based authentication with Django and DRF? The screenshot attached below explains my question better. This application is using Django & React and also has a mobile application. The mobile app also has options to remove devices. How can I implement such a feature with DRF? Is it possible with JWT or what other auth mechanisms should I use? Is there any implementation out there? Has anyone implemented such a thing? Also, I've attached what I get when inspecting the API. -
Django : Resend request forms
In Django, how can I perform a post request from template and redirect to the same template without having resend request on refresh? I tried adding javascript to avoid reload but still, it happens -
Getting anonymoususer in request.user if same user login at same time in django
/* anonymoususer in request.user */ @csrf_exempt def user_login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') if User.objects.filter(username=username): user = authenticate(username=username, password=password) if user: login(request, user) response = JsonResponse({'status': 'success', 'user_id': user.ienter code hered, 'org_id': userprofile[0]['organization_id']}) return response else: response = JsonResponse({'status': 'error', 'msg': 'Incorrect Username/password'}) return response else: response = JsonResponse({'status': 'error', 'msg': 'Username Does not Exists'}) return response else: return render(request, 'login/sign-in.html') @csrf_exempt def dashboard(request): user_id = request.user if user_id: return render(request, 'dashboard.html') return render(request, 'login/sign-in.html') -
Can you make sure only one object related to another object has a certain field set?
I have a model called Video, and it has related objects on another model called Label. Example here: class Video(models.Model): pass class Label(models.Model): video = models.ForeignKey(Video, related_name="labels") current = models.NullBooleanField() I need to be able to find the current label on a video by doing something like my_video.labels.filter(current=True), and this query should only ever return one label, so only one label on the video should have that field set to True. Is there a way of ensuring this on the model/db? Thanks -
CreateAPIView overwrite POST to call model functions
I am making a banking system for a school project. It is my first time working with APIviews in Django and I have a problem. I would like to be able to make a transaction between two accounts. I have a model called Ledger. In the model.py I also have the two functions: CreateTransaction: Is the function there is supposed to POST to the ledger table. Like an audit of the transaction. So it creates two rows in the database. One row for the to_account (to audit the credit) and one row for the from_account (to audit the debit) CompleteTransaction: This is the function there is supposed to complete the transaction. That means that is take the amount and subtracts it from the from_account and adds it to the to_account. class Ledger(models.Model): description = models.CharField(max_length=40) amount = models.FloatField(null=True) t_type = models.CharField(max_length=40) account_id = models.IntegerField() timestamp = models.DateTimeField(auto_now_add=True) customer_id = models.ForeignKey(Customer, on_delete = models.CASCADE, default = None) def __str__(self): return '{} {} {} {} {} {} {} {}'.format(self.description, self.amount, self.account_id, self.t_type, self.timestamp, self.customer_id, self.transaction) def CreateTransaction(description, from_acc, to_acc, amount, customer_id): legder = Ledger() Legder( description=description, amount=float(amount), t_type="CREDIT", account_id=to_acc, customer_id=customer_id ) legder.customer_id = customer_id legder.save() Legder( description=description, amount=float(amount), t_type="DEBIT", account_id=from_acc, customer_id=customer_id ) … -
How to correctly handle different types of users in django rest framework?
I am currently using mixins. My project has a lot of user types which interract differently with the database. This means I need to specify different queries for each type of users and I do that inside the "get_queryset". Example for class view: class ClassViewSet(mixins.Create,Retrieve,Update,Destory,Generic) def get_queryset(self: 'ClassViewSet'): role = self.request.user.role if role == User.ROLE.TEACHER: queryset = ~the classes where the teacher is teaching~ if role == User.ROLE.STUDENT: queryset = ~the class where the student is studying~ return queryset The above example code will return multiple classes if the user is a teacher and one class if the user is a student. Now, I want the to allow teachers to update or delete data from the classes where they teach while students should not be allowed to do anything beside retrieveing one class. How I should do this? I could override the delete and update from the mixins and do the same "if role ..." but is a lot of work. Is there a more efficient/correct way of doing this? -
How to filter divs by model name in Django
I have 'My favorites' page with a list of favorites articles. Users can add to favourite objects from 3 models: article, question, video. What I want is to have a filter by model section so after clicking on a button the website should display only relevant cards. I am using Bootstrap 5. An example of this logic is here, however, I don't see any option to select 2 categories (in my case models). Each button should be connected to each model so if I click question then only titles from question will appear, if article, only from article, if I click article and question then I get cards from these 2 models. I also want to have Show all option. models.py class Article(models.Model): author = models.ForeignKey(User, blank=True, null=True, on_delete=models.DO_NOTHING) title = models.CharField(max_length=200) ... class Meta: verbose_name = 'article' class Question(models.Model): author = models.ForeignKey(User, blank=True, null=True, on_delete=models.DO_NOTHING) title = models.CharField(max_length=200) class Meta: verbose_name = 'question' class Video(models.Model): author = models.ForeignKey(User, blank=True, null=True, on_delete=models.DO_NOTHING) title = models.CharField(max_length=200) ... class Meta: verbose_name = 'video' views.py class FavouriteList(LoginRequiredMixin, ListView): login_url = 'login' redirect_field_name = 'login' template_name = 'hal/Favourites.html' model = Article queryset = Article.objects.all() def get_context_data(self, **kwargs): context = super(FavouriteList, self).get_context_data(**kwargs) tags = Tag.objects.all().values('name', … -
profile not add when user create in django
app name accounts models.py class Profile(models.Model): # Delete profile when user is deleted user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True) about_me = models.TextField(null=True, blank=True) work_on = models.CharField(max_length=100, blank=True) image = models.ImageField(null=True, blank=True, upload_to="profile_image") location = models.CharField(max_length=100,blank=True) def save(self): super().save() def str(self): return self.user.email signals.py from django.db.models.signals import post_save from django.dispatch import receiver from .models import Profile,User @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() apps.py from django.apps import AppConfig class AccountsConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'accounts' def ready(self): import accounts.signals -
graphql-ws subscriptions isn`t workin on prod server
I have issue with production settings. I use graphql-ws for web sockets and it works good at local server ws://localhost:8000/subscriptions but it isn`t working on production server with nginx wss://localhost:8000/subscriptions and wss://<server_name>/subscriptions has 499 mistakes. try to change nginx.conf -
I need to test django filters applying different lookup_expr on the same field
I have a challenge model with fields: name, start_date and end_date. I need to apply different django filters to each field like this class ChallengeFilter(filters.FilterSet): class Meta: model = Challenge fields = { "name": ["exact", "icontains"], "start_date": ["exact", "lte", "gte"], "end_date": ["exact", "lte", "gte"], } when I test the exact lookup_expr it works okay but I need help testing "icontains" or "lte" or "gte" Here's my test for exact def test_challenge_filter_by_name(self, user): c1 = ChallengeFactory(name="chal", owner=user) c2 = ChallengeFactory(name="star", owner=user) data = { "name": "chal", } challenge_filter = ChallengeFilter(data, queryset=Challenge.objects.all()) assert challenge_filter.is_valid() assert challenge_filter.qs.count() == 1 and here's the test I tried with contains but if fails assert 0 == 1 def test_challenge_filter_by_name_contains(self, user): c1 = ChallengeFactory(name="chal", owner=user) c2 = ChallengeFactory(name="star", owner=user) data = { "name": "challenge", } challenge_filter = ChallengeFilter(data, queryset=Challenge.objects.all()) assert challenge_filter.is_valid() assert challenge_filter.qs.count() == 1 I also don't know how to test gte and lte for dates. -
Pdf.js with react and django
I'am trying to develope a pdf viewer with Django framework using React.js as Frontend The problem is that the pdfviewer works perfectly on react project, but when I build it (npm run build) and copy it to the django project it doesn't work. I think that the problems is with paths, care to suggest a method and steps to do that correctly -
DRF: Designate number of entries for queryset using prefetch_related
In my view i am trying to use prefetch_related to get data from 2 related models. The following line gives me the results i want by returning the most recent entry for all controllers in my database # allNames is a list containing all the names of controllers i want to get data for measurements = Microcontrollers.objects.filter(name=allNames[i]).prefetch_related(Prefetch('measurements_basic',queryset=MeasurementsBasic.objects.order_by('-time_taken'))) However when i try to get more entries by adding [:3] at the end it still only returns one for each name in the list. When i try to do so on the prefetch query i get a slice error. AssertionError at /api/CUTAQ/all/testdata/ Cannot filter a query once a slice has been taken. My question is how i can make it so i get the amount of entries i want for each name in the list. -
Vue - Change to different button after @click
I a part of my system involves enabling and disabling accounts. After I click the 'Disable' button I want the system to dynamically remove the 'Disable' button and replace it with an 'Enable' button. In other words, replacing the button with a similar button that reverses what I have already done. I am working within Django and Vue, please see the code below: {% extends 'healthwithfriends/base.html' %} {% block content %} <div id="app"> <div class="container"> <div class="contentContainer"> {% csrf_token %} <div v-for="u in users"> <div class="row"> <div class="col-sm"> <h4 style="text-align: right">[[ u.username ]]</h4> </div> <div class="col-sm" id="u.id" style="text-align: left"> <button type="button" class="btn btn-danger" v-bind:id="u.id+'disable'" v-if="u.is_active" @click="updateStatus(u.id, 'disable')" style="margin-bottom: 0.5em">Disable</button> <button type="button" class="btn btn-success" v-bind:id="u.id+'enable'" v-else @click="updateStatus(u.id, 'enable')" style="margin-bottom: 0.5em">Activate</button> </div> </div> </div> </div> </div> </div> {% block scripts %} This is the JavaScript: async updateStatus(id, status){ let response = await fetch(this.user[0].api, { method: 'PUT_STATUS', // Method itself body: JSON.stringify({'id': id, 'status': status, }), // We send data in JSON format headers: { "Content-Type": "application/json", "X-CSRFToken": document.querySelector("[name=csrfmiddlewaretoken]").value, }, }); if(response.ok){ alert("User status updated.") if (status === "disable"){ document.getElementById(id+"disable").hidden = true; // I want to hide. document.getElementById(id+"enable").hidden = false; // I want to display. } else{ document.getElementById(id+"disable").hidden = false; // I want …