Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to upload multiple videos with title to a course in Django
I am working on an e-learning project. It focuses on the relation among Students, Teachers, and Courses. The project allows teachers to create Courses with multiple lessons and students to enrol in these courses. I want to create lessons for each course like this here But I don't know how to do it. Here is my code. models.py class Course(models.Model): instructor = models.ForeignKey(User, on_delete=models.CASCADE, default=None) title = models.CharField(max_length=100, default=None) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, default='') slug = models.SlugField(max_length=200, unique=True, blank=True, primary_key=True, auto_created=False, default='') short_description = models.TextField(blank=False, max_length=60, default='') description = models.TextField(blank=False, default='') language = models.CharField(max_length=200, default='English') thumbnail = models.ImageField(upload_to='thumbnails/', default='') def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Course, self).save(*args, **kwargs) def add_user_to_list_of_students(self, user): registration = CourseRegistration.objects.create(user = user, course = self) class Lesson(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='lessons', default='') title = models.CharField(max_length=100, default=None) video = models.FileField(upload_to='courses/') def __str__(self): return self.course.title views.py class CreateCourseView(LoginRequiredMixin, CreateView): template_name = 'courses/upload.html' What should I write in views.py which allow teachers to create courses and multiple lessons in each course? -
Django Unique on ManyToManyField
I'm trying to create a private messaging system between users. I created two models. One is "Message" which contains messages and another one is "Conversation" which contains messages just between two users. I want to head off create duplicate conversations. For example i created a conversation between user1 and user2 and this conversation's ID is "5" then i created another one conversation again between user1 and user2 and it's ID is "6". That's bad for me. There must just one conversation between same users. When i try "unique=True" i'm getting an error as "api.Conversation.participants: (fields.E330) ManyToManyFields cannot be unique." models.py class Conversation(models.Model): participants = models.ManyToManyField(User, unique=True) class Message(models.Model): sender = models.ForeignKey(User, related_name="sender", on_delete=models.CASCADE, related_query_name='s') reciepent = models.ManyToManyField(User) conversation = models.ForeignKey(Conversation, blank=False, null=False, on_delete=models.CASCADE) msg_content = models.TextField(max_length=500, blank=True) sendtime = models.DateTimeField(auto_now_add=True) ordering = ["-sendtime"] -
How to load react's staticfiles from s3 in django - react
So I have a Django - React application. All the static files are served by s3 I ran npm run build and then i coped the build folder into my django project folder. and then i setup the template dirs and staticfiles dirs in my settings.py file. when i try to load the django-admin page. everything works perfectly. the static files are served by aws s3. But when i try to load the react page. it tries to look for static files locally which obviously does not exist. so how do i tell my react app to look for the staticfiles in s3? this is how my index.html looks <!doctype html> <html lang="en"> <head> <meta charset="utf-8"/> <link rel="icon" href="/favicon.ico"/> <meta name="viewport" content="width=device-width,initial-scale=1"/> <meta name="theme-color" content="#000000"/> <meta name="description" content="jgprth."/> <link rel="apple-touch-icon" href="/logo192.png"/> <link rel="manifest" href="/manifest.json"/> <title>test</title></head> <body> <noscript>You need to enable JavaScript to run this app.</noscript> <div id="root"></div> <script>!function (e) { function t(t) { for (var n, a, l = t[0], f = t[1], i = t[2], p = 0, s = []; p < l.length; p++) a = l[p], Object.prototype.hasOwnProperty.call(o, a) && o[a] && s.push(o[a][0]), o[a] = 0; for (n in f) Object.prototype.hasOwnProperty.call(f, n) && (e[n] = f[n]); for (c … -
Django not setting the same site cookie
I am getting an error in chrome as follows Because a cookie’s SameSite attribute was not set or is invalid, it defaults to SameSite=Lax, which prevents the cookie from being sent in a cross-site request. In Django docs they have given by default it's been set to Lax but then why does the error come I am using Django 3.2.2 -
Grouping the data financial year wise and month wise
I am developing a django restframework API to show data of the salary paid to employees financial Year wise and month wise sum. Something like below: [ "2019-20":{ "Apr":120012, "May":142566, "June":122223 #So on for every month }, "2020-21":{ "Apr":130019, "May":142526, "June":152221 #So on for every month } ] My models are class Months(Model): month_name = models.Charfield(max_length=3) class FinYear(Model): finyear_name = models.Charfield(max_length=7) class Employee(Model): name=models.Carfield(max_length=50) Class Salary(Model): fin_year=models.Foreignkey(FinYear, on_delete=medels.CASCADE) month=models.Foreignkey(Months, on_delete=medels.CASCADE) salary = models.Integerfield(max_length=8) employee_id=models.Foreignkey(Employee, on_delete=models.CASCADE) Any help will be highly appreciated. -
ViewSet and additional retrieve URL
I have a django model that I expose as a ViewSet. Now I want to add an additional URL where a single instance can be retrieved and custom actions can be executed. # models.py class MyModel(models.Model): id = models.AutoField(primary_key=True) third_party_service_id = models.StringField() # views.py class MyModelViewSet(mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.ListModelMixin): def retrieve(self, request, *args, **kwargs): if kwargs['pk'].isdigit(): return super(MyModelViewSet, self).retrieve(request, *args, **kwargs) else: query_third_party_service_id = self.request.query_params.get('third_party_service_id', None) if query_third_party_service_id is not None: try: instance = MyModel.objects.get(third_party_service_id=query_third_party_service_id) catch MyModel.DoesNotExist: raise Http404 return Response(self.get_serializer(instance).data) return Response(status=status.HTTP_404_NOT_FOUND) @action(methods=['post'], detail=True) def custom_action(self, request, *args, **kwargs): pass # urls.py router = routers.DefaultRouter() router.register(r'mymodels', MyModelViewSet) router.register(r'mythirdpartyservices/(?P<third_party_service_id>[0-9]+)', MyModelViewSet) My goal is to have http://localhost:8000/mymodels point at the entire ViewSet. Also I would like to lookup an individual model, by only knowing its third_party_id like follows http://localhost:8000/mythirdpartyservices/1337/ and also executing the custom action like follows http://localhost:8000/mythirdpartyservices/1337/custom_action/. The problem I have is that the second url returns an entire queryset, not just a single instance of the model. -
Get model field values from FK related objects
I've got a structure of FK related objects that looks somewhat like that: class Object3(models.Model): ... requirement = models.ManyToManyField(Requirement, blank=True) class Object2(models.Model): ... parent = models.ForeignKey(Object3, on_delete=models.CASCADE) requirement = models.ManyToManyField(Requirement, blank=True) class Object1(models.Model): ... parent = models.ForeignKey(Object2, on_delete=models.CASCADE) requirement = models.ManyToManyField(Requirement, blank=True) class Requirement(models.Model): ... All of those object have the same non-required field, which is a ManyToManyField, it's basically a requirement that can be set on either level of the structure. What I need to do is when I set the m2m field on the highest level of the structure, Object3, I need related Object2 and Object1 to set the m2m identically, same if I set it on Object2 instance, I need it to be set on the related Object1 instances. What is the most Django-ish way to achieve that? I hope my explanation is clear enough, I'll be more than happy to provide any more information. I've been pulling my hair out with this simple task, but I can't seem to come up with a good solution, hopefully with your help I'll be able to. -
Access django admin page behind Nginx
I am able to access all of my regular endpoints in my Django project, but I'm unable to access the /admin login page. Whenever I try to enter the url/admin I get redirected to my top-url, the same happens in Postman. I have the following Nginx file: location ~ /api { rewrite ^/api(.*)$ $1 break; include uwsgi_params; uwsgi_pass unix:/run/uwsgi/backend.sock; } location /static/ { root /home/m3csadmin/backend; } location / { try_files $uri $uri/ /index.html =404; } What am I missing? -
Django Rest Framework: How to Dynamically return subset of fields
I would like to filter by fields name and get back a subset instead of having back all my fields name. For example here I am filtering by id and name. It should return me only this two dimension in json format. I have found many solution on the site and I have done exactly the same as suggested but I don't have the expected result. Could you please help me ? my view: router = routers.DefaultRouter() urlpatterns = [ path('', include(router.urls)), path('edges/', edge_list), path('edges/<int:pk>/', edge_detail), path('network/<int:pk>/edges/', edges_of_a_network), ] Here a copy past example from https://www.django-rest-framework.org/api-guide/serializers/#example class DynamicFieldsModelSerializer(serializers.ModelSerializer): """ A ModelSerializer that takes an additional `fields` argument that controls which fields should be displayed. """ def __init__(self, *args, **kwargs): # Don't pass the 'fields' arg up to the superclass fields = kwargs.pop('fields', None) # Instantiate the superclass normally super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs) if fields is not None: # Drop any fields that are not specified in the `fields` argument. allowed = set(fields) existing = set(self.fields) for field_name in existing - allowed: self.fields.pop(field_name) My serializer class which I would like to filter fields. class EdgeSerializer(DynamicFieldsModelSerializer, serializers.ModelSerializer): source = serializers.SerializerMethodField(method_name='get_node_source') target = serializers.SerializerMethodField(method_name='get_node_target') road_type = serializers.SerializerMethodField( method_name='get_road_type_id') class Meta: model = Edge fields … -
Unable to make a "Get" call to a django app residing in a docker container from a flask app in another docker container
I am referring to the tutorial, https://www.youtube.com/watch?v=0iB5IPoTDts. At from 1:18:09 in the tutorial, I am supposed to implement this code below [Api call from a flask app in a docker container to a django app residing in another docker container][1] But I keep getting maximum retry error. [Error image][2] It seems like the get request is failing. I referred to the following link How to get the IP address of the docker host from inside a docker container, and tried solutions present in answer 1 and 2, but they give an error 400. I am quite novice in flask and django. Please help. Thanks in advance. [1]: https://i.stack.imgur.com/O0tZf.png [2]: https://i.stack.imgur.com/UozYE.png -
Pass a value to an api and return a specific object
I have created an api where #urls.py router = DefaultRouter() router.register('login', GetUserViewSet, basename='get_user') urlpatterns = [ path('', include(router.urls)), ] #views.py class GetUserViewSet(viewsets.ReadOnlyModelViewSet): queryset = User.objects.all() serializer_class = GetProfileSerializer #serializers.py class GetProfileSerializer(serializers.ModelSerializer): class Meta: model = User exclude = ('password', 'groups', 'user_permissions') The above code returns the list of users when I hit 'http://localhost:8000/api/login/' and the specific user when I hit 'http://localhost:8000/api/login/1/'. Here I want to pass the 'mobile_number' to the api and return the only user with the mobile number. I have achieved it by adding get_queryset() to the views as follows. #views.py class GetUserViewSet(viewsets.ReadOnlyModelViewSet): queryset = User.objects.all() serializer_class = GetProfileSerializer def get_queryset(self): mobile_number = self.request.query_params.get('mobile_number') queryset = User.objects.filter(mobile_number=mobile_number) return queryset But the above code is returning the object in an array. I am following a common response format as given below { "status": true, "message": "Successfully registered your account.", "data": { "id": 1, "first_name": "User", "last_name": "U", "email": "user@gmail.com", "dial_code_id": "91", "mobile_number": "9876543211", } } and I am not able to achieve this with this get_queryset(). Please suggest me the best possible way to achieve this. -
Show a set of car models after the user chooses the car brand in Django forms
I am using Django 3.2 to make an uber clone and that when I want to allow the users to register with their vehicle I first want the user to be able to choose the car brand, and then afterwards choose the car model which is sorted according to the car brand. class Vehicle (models.Model): brand = models.CharField(max_length=60) model = models.CharField(max_length=60) vehicle_colour = models.CharField(choices=COLOURS, max_length=10) vehicle_number = models.CharField(max_length=8) I want to add some choices for the brand and model field, but I feel like I might need some javascript to intervene. Do you know any method that I could use to get this done? Your help is greatly appreciated. Thanks! -
Mpesa object has no attribute 'update'
I would like to update the first item in the database each time a user clicks on a button but I keep getting the error every time, any assistance would be appreciated, below is the snippet. Mpesa.objects.filter(Paid_user=self.request.user, Completed=False).first().update(Completed=True) -
how to create comment tree in django
I need a comment system so can reply a comment to any comment I know how to write models and views and my only problem is showing them in the template For example, maybe a group of comments are like this: comment comment comment comment comment comment comment comment comment comment How can I display this structure in the template? -
ValueError - The view didn't return an HttpResponse object. It returned None instead
My view currently returns an error of The view viajecenter.views.receive_payment didn't return an HttpResponse object. It returned None instead. I tried some of the solutions from other related posts here but of no luck. Here is my function in my views.py file: def receive_payment(request, account_code): template_name = 'receive-payment.html' def get_context_data(self, *args, **kwargs): user = self.request.user context = super(receive_payment, self).get_context_data(*args, **kwargs) account = get_object_or_404(Account, account_code=self.kwargs['account_code']) if user.is_assigned: puv = Puv.objects.get(assignment_id=user.assignment_id) locations = puv.route.locations.all().order_by('distance_from_base') context["account"] = account context["puv"] = puv context["locations"] = locations return render(request, self.template_name, context) else: return user and the corresponding url in urls.py file: from django.urls import path from . views import ..., receive_payment urlpatterns = [ ... path('receive-payment/<str:account_code>', receive_payment, name="receive-payment"), ] Thank you for lending me your time and answering my question :) -
How to send emails using RabbitMq and Django
I am new to RabbitMQ at the same time, if possible would someone also link me to a good tutorial for my task? -
How to update text area contents in django
Am trying to refresh a text area with data from a service that scans a bar code and logs the code. Am not sure what am doing wrong, I cant get the scanned data to appear on the text area. This is what I have done so far My camera stream for scanning the barcodes and logging to the console and to a list used_codes variable class CameraStream: used_codes = [] def __init__(self): self.camera = cv2.VideoCapture(int(0)) def get_frames(self): used_codes = self.used_codes while True: # Capture frame-by-frame success, frame = self.camera.read() if not success: break else: ret, buffer = cv2.imencode('.jpg', frame) # Add text on top of the barcode if there is a barcode in the stream using opencv # convert camera frame to numpy array color_image = np.asanyarray(frame) # decode numpy array to check if there is a barcode in color_image if decode(color_image): for code in decode(color_image): if code.data.decode('utf-8') not in used_codes: print('Approved. You can enter!') print(code.data.decode('utf-8')) used_codes.append(code.data.decode('utf-8')) elif code.data.decode('utf-8') in used_codes: print('Sorry, this code has been already used!') else: pass cv2.imshow('Testing-code-scan', frame) cv2.waitKey(1) return used_codes My Views getting the data from the used_codes variable and sending it to the view def detect(request): stream = CameraStream() success, frame = stream.camera.read() … -
How to Use Deep Learning model trained on GoogleColab in Django
I have Trained one text classification model using Jupyter notebook and saved model using Joblib which I easily use in django to predict ouput. Now I have trained one similar text classification on Google Colab but there am not able to use Joblib to save trained model. Also I have one doubt about how to use tokenizer used in google colab from server. If I want to predict I have to do some preprocessing on text x = ['this is a news'] x = tokenizer.texts_to_sequences(x) So, this tokenizer is fit on Trained dataset. Please let me know about this, how to save that model and use of it in django also how to preprocess the requested data. Thank You! -
Procfile gunicorn doesn't find module (Django)
My project structure looks like this git_root/ -django_project_root/ --core/ ---... ---settings.py ---wsgi.py ---... --app1/ --... Procfile ... So I have Procfile in git_root and wsgi in django_project/core/ My Procfile looks like that web: gunicorn --preload django_project.core.wsgi Heroku logs: ModuleNotFoundError: No module named 'core' P.S. Also tried next 2 things Tried putting Procfile in django_project folder. But it is not found when deploying. Created new repo and unwrapped django_project, so git_root is now django_project. And edited the Procfile to look like this web: gunicorn --preload core.wsgi and that worked. But i need it to work on initial repo. -
How can the data entered by a user get updated in the database in Django?
This is my html code for checkbox : <div class="col"> <div class="form-check"><input class="form-check-input" type="checkbox" id="formCheck-1"><label class="form-check-label" for="formCheck-1" style="color:rgb(255,255,255);">Melody</label></div> <div class="form-check"><input class="form-check-input" type="checkbox" id="formCheck-1"><label class="form-check-label" for="formCheck-1" style="color:rgb(255,255,255);">Rock</label></div> <div class="form-check"><input class="form-check-input" type="checkbox" id="formCheck-1"><label class="form-check-label" for="formCheck-1" style="color:rgb(255,255,255);">Classical</label></div> <div class="form-check"><input class="form-check-input" type="checkbox" id="formCheck-1"><label class="form-check-label" for="formCheck-1" style="color:rgb(255,255,255);">Jazz</label></div> <div class="form-check"><input class="form-check-input" type="checkbox" id="formCheck-1"><label class="form-check-label" for="formCheck-1" style="color:rgb(255,255,255);">Metal</label></div> </div> Views.py (I am very new to programming, so the code could be wrong) def Userregister(request): if request.method == 'POST': Name = request.POST['Name'] Melody = request.POST.getlist['Melody'] Rock = request.POST.getlist['Rock'] Jazz = request.POST.getlist['Jazz'] Classical = request.POST.getlist['Classical'] Metal = request.POST.getlist['Metal'] models.py from django.db import models class User(models.Model) : Name= models.CharField(max_length=100) Melody = models.BooleanField(default=False) Rock = models.BooleanField(default=False) Jazz = models.BooleanField(default=False) Classical = models.BooleanField(default=False) Metal = models.BooleanField(default=False) -
How do I Calculate interest on balance in days with django
How do I calculate the compound interest on balance? I want 3 percent of the amount in balance to be calculated and then automatically added to the running balance of every user that have a balance. What I meant is that the amount in running balance will be as the results of the calculation of 3 percent of the balance in user account. I want this calculation to be done consecutively every five days. Three percent interest of every amount in balance will be calculated in every 500 days. This calculation is continual and infinite from the last time it was calculated class UserAccount(models.Model): user =models.OneToOneField(User, related_name='account', on_delete=models.CASCADE,) balance =models.DecimalField(default=0 max_digits=12,decimal_places=2) running_balance =models.DecimalField(default=0 max_digits=12,decimal_places=2) interest_startdate =models.DateTimeField(auto_add=now) rate = models.IntegerChoices() days = models.IntegerField("number of days", default=0) def __str__(self): return str(self.balance) def get_interest_calculation_months(self): account = UserAccount.objects.get(balance__gt=0, pk=<something>) calc_interest = lambda value: value * useraccount.rate amount = useraccount.balance for i in xrange(12): interest = calc_interest(amount) amount += interest print 'days {}: {} ({} interest)'.format(i, amount, interest) running_balance +=interest A little confused right away. How do I get this to work The interest of all the balance in the userAccount should be calculated and then added to the user running balance This action's is … -
CouchDB user jwt authentication with python/django
Iam new to Software development and Iam implementing login page with couchdb and django, I want the authentication should be token based and I don't have any idea how to develop and I searched alot I didn't find perfect solution, I need ideas Pls help and Than you -
content is over lapping the navigation bar
I'm making the blog site with django I got a problem after adding navigation bar the problem is content of the web site is overlapping the navigation bar when I scroll down the page. Or if you know how add sticky navigation bar in another better way than this let me know.I usedw3 school web site to add this navigation bar .Anyway here is my code. {% extends "base.html" %} {% block content %} <style> body { font-family: "Roboto", sans-serif; font-size: 18px; background-color: #fdfdfd; background-image: url("images/background.png"); } .head_text{ color: white; } .card{ box-shadow: 0 16px 48px #E3E7EB; } #navbar { overflow: hidden; background-color: #333; } #navbar a { float: left; display: block; color: #f2f2f2; text-align: center; padding: 14px 16px; text-decoration: none; font-size: 17px; } #navbar a:hover { background-color: #ddd; color: black; } #navbar a.active { background-color: #04AA6D; color: white; } .content { padding: 16px; } .sticky { position: fixed; top: 0; width: 100%; } .sticky + .content { padding-top: 60px; } </style> <!-- Nav bar --> <div id="navbar"> <a class="active" href="javascript:void(0)">Home</a> <a href="javascript:void(0)">News</a> <a href="javascript:void(0)">Contact</a> </div> <script> window.onscroll = function() {myFunction()}; var navbar = document.getElementById("navbar"); var sticky = navbar.offsetTop; function myFunction() { if (window.pageYOffset >= sticky) { navbar.classList.add("sticky") } else … -
502 bad gateway error nginx/1.14.0 (Ubuntu)
Hello Can anyone help me resolve 502 bad gateway Error nginx/1.14.0 (Ubuntu). I want to run my website and I am facing an issue for the same . Please let me know the steps to resolve this error . enter image description here -
Why Django update page and log out didn't work?
This is dashboard page with django login This is analyse page after i login but the user didn#t show up I click the analyse page when i am anonumoususer, the user didn't change after i login I don't get the reason why i am logged in but the user did not show up. Besides when i click logout it doesn't work either.Below is my logout code. I really appreciate it if anyone could help me!! from django.shortcuts import render,redirect import hashlib from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth.models import AnonymousUser from django.contrib.auth import authenticate,get_user_model,login,logout,get_user from .forms import UserLoginForm,UserRegisterForm from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse from django.template import Template,Context from .decorators import unauthenticated_user,allowed_users, admin_only from django.contrib.auth.decorators import login_required @csrf_exempt @unauthenticated_user def login_view(request): next = request.GET.get('next') form =UserLoginForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username,password=password) login(request,user) if next: return redirect(next) else: return redirect('/home') context = { 'form': form, } return render(request,'users/login.html',context) def index(request): return render(request,'users/home.html') @csrf_exempt def register_view(request): next = request.GET.get('next') register_form = UserRegisterForm(request.POST or None) if register_form.is_valid(): user = register_form.save(commit=False) password = register_form.cleaned_data.get('password1') user.set_password(password) user.save() new_user = authenticate(username=user.username,password=password) login(request, new_user) if next: return redirect(next) return redirect('/userlist') context = { 'form': register_form, } return …