Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
How to get the current logged in user? Django models
I want to get the current logged in user to this CreateForm form. Below Im giving my current code, here request.user is not giving me error ValueError at /create-post/ Cannot assign "<SimpleLazyObject: <User: testuser>>": "Post.author" must be a "Author" instance. models.py class Author(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) rate = models.IntegerField(default=0) class Post(models.Model): title = models.CharField(max_length= 50) overview = models.TextField() body_text = RichTextUploadingField(null = True) time_upload = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(Author, related_name='author', on_delete=models.CASCADE) thumbnail = models.ImageField(upload_to = 'thumbnails') publish = models.BooleanField() categories = models.ManyToManyField(Categories) read = models.IntegerField(default=0) slug = models.SlugField(null= True, blank= True) Forms.py class CreateForm(ModelForm): class Meta: model = Post fields = [ 'title', 'overview', 'body_text', 'thumbnail', 'categories', 'publish', ] Views.py def create_post(request): if request.method == 'POST': form = CreateForm(request.POST, request.FILES) if form.is_valid: post = form.save(commit=False) post.author= request.user post.save() return render(request, 'index.html') else: form = CreateForm() return render(request, 'create_post.html', {'form': form}) -
Datatables with Select Form in each row with Django/Python
i'm farely new to django/python but i wanted to create a interface website for a database with patients and their appointments. To make it easy for the users of this interface there was a request to make the appointmentstatus selectable in the datatable directly as seen in the picture. The select form in each row in the picture is not working and is only rendered with html as an example to show what I want to achieve. I was trying to use a function in django to return a form for each row on request with the current status preselected. But I failed miserably... Maybe someone has a hint for me? What I want to create What I have done is to create a form class and a view function that can be reached through a url: urls.py: path('appointments/<int:pk>/quickupdatestatus/', views.AppointmentQuickUpdateStatus, name='appointment-quick-update-status'), view.py: def AppointmentQuickUpdateStatus(request, pk): if request.user.is_authenticated: ap = appointment.objects.get(pk=pk) if request.method == 'POST': ap.status = request.POST.get('status') ap.save() messages.success(request, 'Status erfolgreich bearbeitet!') else: form_class = AppointmentQuickStatusForm(initial={'status': ap.status}) render(form_class) #How can I return just the Form and Render it for every individual row? else: response = redirect('/account/login/') return response form.py: class AppointmentQuickStatusForm(forms.Form): status = forms.ModelChoiceField( label='Status:', queryset=status.objects.all(), required=True, widget=forms.Select(attrs={'class': 'form-control', 'onChange': … -
Django Rest Framework can't parse image data from React front-end
I have a front end where the user can create a 'Post' with or without an image. If the request is done without an image the 'Post' object gets created and there's no problem with it. But when I try to add the image in the post request by using Axios and FormData when Django receives this object my Serializer returns false for is_valid() function call... An example post object contains the following keys: {'text':'some string', 'image': {some_file_object(optional)}} Here's my view: class PostView(APIView): permission_classes = (IsAuthenticated,) parser_class = (MultiPartParser) def post(self, request): user = User.objects.get(username=self.request.user) userSerialize = UserGetSerializer(user, partial=True) _mutable = request.data.copy() _mutable['user'] = userSerialize.data print(_mutable) serializer = PostSerializer(data=_mutable) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(status=status.HTTP_400_BAD_REQUEST) Here's my serializer class PostSerializer (serializers.ModelSerializer): text = serializers.CharField(max_length=500, required=True) user = UserSerializer(many=False) likes = serializers.SerializerMethodField(read_only=True) image = serializers.ImageField(required=False) class Meta: model = Post fields = ('__all__') def get_likes(self, obj): likes = obj.like_set.filter(post=obj.id) return LikeSerializer(likes, many=True).data Here's my Model: class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="user", on_delete=models.CASCADE, blank=True) text = models.TextField(max_length=500) date_posted = models.DateTimeField(auto_now_add=True) hidden = models.BooleanField(default=False) date_hidden = models.DateTimeField(blank=True, null=True) hidden_by = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True, related_name='hidden_by') image = VersatileImageField( upload_to='post_images/', ppoi_field='image_ppoi', blank=True, null=True) image_ppoi = PPOIField() def __str__(self) -> str: return … -
UWSGI - Launch script with manage.py
I need to run a script into my Django project. I'm using this approach, that works, but I'm looking for more valid alternatives. uwsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "MyApp.settings") application = get_wsgi_application() __import__('myapp.script') import os os.environ = {'DJANGO_SETTINGS_MODULE': 'MyApp.settings'} import django django.setup() def main(): # some script using django db pass main() I've already look on uwsgi documentation and django, but can't find a way to run the manage.py. I don't like to use this approach because every time I need to set DJANGO_SETTINGS_MODULE, because I also want to run it locally. I prefere using the runscript. So, there is a way to call the manage.py from the wsgi module in order to use the runscript to run the script.py? Or, do you know another approach like the uwsgi.ini or something else? -
Is it possible to get a list of all deleted items in a django model without the use of safedelete or softdelete?
I'd like to have a record for all deleted items presented to the user. I've used safedelete but I want to change. -
Testing with Django's TestCase and async don't work with Database
So I'm using django_channels to handle some WebSocket stuff and since (Django 3.1)[https://docs.djangoproject.com/en/dev/topics/testing/tools/#testing-asynchronous-code] you can create unittest-like tests for testing async and decided to go with that. It happens to be that for some reason when accessing the Consumer can't reach the data. I'm using model_bakery (but also tried with plain Django ORM) and have a very simple test. class TestChatConsumer(TestCase): url = '/ws/chat/' def setUp(self): self.user = baker.make_recipe('registration.user') self.chat = baker.make_recipe('chat.chat') async def test_setup_channel_layer_ok(self): consummer = WebsocketCommunicator( application=AuthMiddlewareStack(ChatConsumer.as_asgi()), path=self.url, ) consummer.scope['user'] = self.user await consummer.connect() await consummer.send_json_to({ 'type': 'setup_channel_layer', 'chat': self.chat.pk, }) response = await consummer.receive_json_from() self.assertEqual(response['type'], 'info') self.assertEqual(response['content']['message'], 'Chat connected!') The problem is that on the test the entry is created but when accessing consumers the entry seems to be off. Do you know if there's any desync between test database or something? -
Getting values from queryset in Django
Facing troubles with getting values from foreign key models. I have one model, where included all foreign key relations. class UserAccount(models.Model): name= models.CharField(max_length=100) surname = models.CharField(max_length=100) category= models.ManyToManyField(Category) account = models.ForeignKey(Account) country = models.ForeignKey(Country) permissions = models.ForeignKey(Permissions) class Country(models.Model): iso_code = models.CharField(max_length=6) zip_code = models.CharField(max_length=10) I'm using this to get all fields related to model UserAccount: user_account_data = UserAccount.objects.all() name = user_account_data.values_list('name', flat=True))) surname = user_account_data.values_list('surname', flat=True))) But when trying this, its giving me: 'QuerySet' object has no attribute 'country' countries = user_account_data.country.values('iso_code') -
Django - uwsgi.py to run a python script
I need to run a script into my Django project. I'm using this approach, that works, but I'm looking for more valid alternatives. uwsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "MyApp.settings") application = get_wsgi_application() __import__('myapp.script') import os os.environ = {'DJANGO_SETTINGS_MODULE': 'MyApp.settings'} import django django.setup() def main(): # some script using django db pass main() I don't like to use this approach because every time I need to set DJANGO_SETTINGS_MODULE, because I also want to run it locally. I prefere using the runscript. So, there is a way to call the manage.py from the wsgi module in order to use the runscript to run the script.py? Or, do you know another approach like the uwsgi.ini or something else? -
Django channels send message stuck in for loop
I am calculating the task progress using for loop and trying to send the calculated value via sockets using async_to_sync but the process gets stuck and nothing happens. I am facing this issue only in loop but outside of loop I am able to send the message. consumers.py file import asyncio from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync import json import time class ProgressConsumer(WebsocketConsumer): def connect(self): self.room_name = "test_consumer" self.room_group_name = "test_consumer_group" async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() self.send(text_data=json.dumps({'status' : 'connected'})) def receive(self, text_data): print(text_data) for i in range(10): time.sleep(1) msg_dict = { "msg" : "msg "+str(i)+" sent from loop" } self.send(text_data=json.dumps(msg_dict)) def disconnect(self, *args, **kwargs): self.room_name = "test_consumer" self.room_group_name = "test_consumer_group" async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) print("disconnected") def send_progress(self, event): print("send progress") data = json.loads(event.get('value')) print("data :", data) self.send(text_data=json.dumps({"payload" : data})) print('send progress') Loop in which I am calling send progress function for line in loglines: cur_frame = int(line) prog = calulate_progress(int(n_frames),cur_frame) print("Progress is : "+str(prog)+"%") data = {"progress from loop" : prog} channel_layer = get_channel_layer() prog = prog async_to_sync(channel_layer.group_send)( "test_consumer_group", { "type": "send_progress", "value": json.dumps(data) } ) if prog == 100.0: break -
How do I link two views to one template file in Django
I'm trying to build a very basic messaging app where someone types into a text input, presses send then see's the message on the screen. And I want to do all of this on the same URL. Here is what I have right now: views.py: from django.shortcuts import render from django.views.generic import ListView, CreateView from message import models # Create your views here. class ViewMessages(ListView): model = models.Messages context_object_name = 'messages' class WriteMessages(CreateView): fields = ('message',) model = models.Messages models.py: from django.db import models from django import forms from django.core.urlresolvers import reverse # Create your models here. class Messages(models.Model): message = models.CharField(max_length=300) def __str__(self): return self.message def get_absolute_url(self): return reverse("view") project urls.py: from django.conf.urls import url from django.contrib import admin from message import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^view/', views.ViewMessages.as_view(), name="view"), url(r'^create/', views.WriteMessages.as_view(), name="create"), ] messages_form.html {% extends "message/base.html" %} {% block head_block %} <title>Create Message</title> {% endblock %} {% block body_block %} {% for message in messages %} <h3><div class="text-center"><span class="label label-default">{{ message.message }}</span></div></h3> {% endfor %} <form method="POST" class="form-horizontal"> {% csrf_token %} <div class="text-center" style="position: fixed; top: 500px;"> <span style="margin: 10px;">{{ form }}</span> <br> <input type="submit" value="Send" class="btn btn-primary btn-group btn-group-lg" > </div> </form> {% endblock %} … -
(IntegrityError at /Hod/Student/Add/ NOT NULL constraint failed: apps_customuser.username)
My data are not posted to the database (each fields are going but not the username) #my models class CustomUser(AbstractUser): USER = ( (1,'HOD'), (2, 'STAFF'), (3, 'STUDENT'), ) user_type = models.CharField(choices=USER,max_length=50,default=1) profile_pic = models.ImageField(upload_to='media/profile_pic') class Course(models.Model): name = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Session_Year(models.Model): session_start = models.CharField(max_length=100) session_end = models.CharField(max_length=100) def __str__(self) : return self.session_start + " To " + self.session_end class Student(models.Model): admin = models.OneToOneField(CustomUser,on_delete=models.CASCADE) address = models.TextField() gender = models.CharField(max_length=100) roll = models.IntegerField() course_id = models.ForeignKey(Course,on_delete=models.DO_NOTHING) session_year_id = models.ForeignKey(Session_Year,on_delete=models.DO_NOTHING) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) #my views @login_required(login_url='/') def Add_Student(request): course = Course.objects.all() session_year = Session_Year.objects.all() if request.method == 'POST': profile_pic = request.FILES.get('profile_pic') first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') email = request.POST.get('email') username = request.POST.get('username') password = request.POST.get('password') address = request.POST.get('password') roll = request.POST.get('roll') gender = request.POST.get('gender') course_id = request.POST.get('course_id') session_year_id = request.POST.get('session_year_id') if CustomUser.objects.filter(email=email).exists(): messages.warning(request,'Email is Already Taken') return redirect('add_student') if CustomUser.objects.filter(username=username).exists(): messages.warning(request, 'UserName is Already Taken') return redirect('add_student') else: user = CustomUser( first_name = first_name, last_name = last_name, username = username, email = email, profile_pic = profile_pic, user_type = 3 ) user.set_password(password) user.save() course = Course.objects.get(id=course_id) session_year = Session_Year.objects.get(id=session_year_id) student = Student( admin = user, address = address, … -
django disable button until file is uploaded
I would like to disable my button until a file is uploaded, how can I do this? my html code {% extends 'base.html' %} {% block content %} <center> <h1>Upload your file</h1> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <label class="custom-file-upload"> <input type="file" name="document"><br/> </label> <button class="button button1" type="submit">Upload file</button> </form> {% if url %} <p>Uploaded file: <a href="{{ url }}">{{ url }}</a></p> {% endif %} {{ return_value }} </center> {% endblock %}