Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Validating complex relationships in Django
I am developing a Django application that helps teachers' observation of students during lessons. I have defined models for Lesson and Student, and a FocusGroup model for the students to be observed during a given Lesson, The FocusGroup object has fields for observing Student behavior during a Lesson. A sample of Students are observed during the said Lesson, and the observations are to be registered in FocusGroupfields. As part of the teacher’s preparation for the givenLesson, he assigns that Lessonto a number of FocusGroupinstances (representingStudents) Now, the application needs to ensure, that the same Studentis assigned at most once to a givenLesson`. I do this in my template already, but I want to assure uniqueness on the server side as well. The diagram should illustrate this: My question is how I should assure the Lesson is assigned the same Student at most once. Should I do that in the FocusGroup model or in the receiving View? And how should I get this relationship assured safely in Django? My present implementation checks for FocusGroup-Lesson uniqueness, but with new FocusGroup instances generated, there is a chance that the same Student is represented by more than one of the FocusGroup instances assigned to … -
How to charge user for overdue books
1st Issue) I want to charge user for overdue books and I tried in model when bookissue instance created by overriding save() method but it is not that successful... In this case, is it a good practice to overriding save() method in BookIssue model to make charge user or in BookReturn model (I have bookreturn model) - do I need to create a separate table to do it? 2dn Issue) I tried to decrease a quantity by 1 once book issued by overriding save() method and worked well but once tried to increase quantity by 1 when issue book returned it did not work how can also implement it Models.py def get_expiry_date(): return date.today() + timedelta(days=10) class BookIssue(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) book = models.ForeignKey(Book, on_delete=models.CASCADE) issue_date = models.DateField(auto_now_add=True) return_date = models.DateField(default=get_expiry_date) quantity = models.IntegerField(default=0) charge_amount = models.IntegerField(default=0) def __str__(self): return str(self.book) def save(self, *args, **kwargs): if not self.pk: self.book.quantity = self.book.quantity - 1 self.book.save() overdue_rate = 1.50 ####($1.50 per day) overdue_days = self.book.return_date > self.book.issue_date - timedelta(days=10) if overdue_days: self.book.charge_amount = overdue_days * 10 overdue_rate * ((date.today() - self.book.return_date) / 1).days self.book.save() super().save(*args, **kwargs) -
launch_map: "Dict[asyncio.Task[object], threading.Thread]" = {}
^ SyntaxError: invalid syntax launch_map: "Dict[asyncio.Task[object], threading.Thread]" = {} ^ SyntaxError: invalid syntax launch_map: "Dict[asyncio.Task[object], threading.Thread]" = {} ^ SyntaxError: invalid syntax django-admin wont run cause of the ABOVE ERROR -
DRF: Set language while testing
I have a serializer with a DateField that is localized according to the user's language settings. I would like to write a test and verify that the formatting is working correctly but I couldn't figure out how to set the reuqest language when using APIClient. That's how my test looks like: self.api_client = APIClient() # .... url = reverse("view_name", kwargs={...}) self.api_client.force_authenticate(user=self.user) response = self.api_client.get(url, format="json", follow=True) self.assertEqual(response.status_code, status.HTTP_200_OK) # asserts This way the test successfully works for my default language setting. How can I explicitly set the language code for this request. -
In Django how to disallow users to view other users page/results
I am working on a questionnaire and reporting site. The users fill out some questionnaire forms and they get a button on the results site that shows the user his own results. My problem is that I'm using the user_name_id in the url to show the right page (for example localhost:8000/mpa/7) to the user and I don't know how to limit the request.user to allow to see just his results. Now if a logged in user wants he can change the id in the url and can view other users results. views.py @login_required def main(request): gdpr_new = Gdpr_new.objects.filter(user_name=request.user) ... context = { 'gdpr_new': gdpr_new, ... } return render(request, 'stressz/main.html', context) urls.py app_name = 'stressz' urlpatterns = [ path('<int:user_name_id>/', views.results, name='results'), path('project_details/<int:projekt_id>/', views.project_details, name='project_details'), path('sum/<int:user_name_id>/', views.individual_sum, name='individual_sum'), path('main', views.main, name='main'), -
Marking only one answer as accepted
I am building simple Q & A site like Stack Overflow, and I am building marking a answer as accepted but when I implement than it is marking every answer as accepted. I mean User can accept every answer but I don't want this. I am trying to make - user can mark only one accepted answer. models.py class Answer(models.Model): answer_user = models.ForeignKey(User,on_delete=models.CASCADE) body = models.CharField(max_length=30,null=True) accepted = models.BooleanField(default=False) views.py def mark_accepted(request, question_id): post = get_object_or_404(Answer, pk=question_id) if request.GET.get('submit') == 'accept': if post.accepted == True: post.accepted = False else: post.accepted = True return JsonResponse({'action':'accept'}) template.html {% if data.accepted %} <button name='submit' type='submit' value="like"><i class=" fas fa-correct fa-6x " ></i></button> {% else %} <button name='submit' type='submit' value="like"><i class=" fal fa-correct fa-6x "></i></button> {% endif %} <script> $('.likeForm').submit(function (e) { e.preventDefault(); let thisElement = $(this) $.ajax({ url: thisElement.attr('action'), data: { 'submit': 'accept', }, dataType: 'json', method: 'get', if (response.action == 'accept') { accept ++ $(`#id_likes${thisElement.attr('data-pk')}`).html(`<button name='submit' type='submit' value="like"><i class=" fas fa-correct fa-6x "></i></button>`) // Followed $(`#followed_likes${thisElement.attr('data-pk')}`).html(`<button name='submit' type='submit' value="like"><i class=" fas fa-correct fa-6x "></i></button>`) } </script> -
Doesn't see my path in urls.py, page not found
I go to "http://127.0.0.1:8000/api/v1/personalities/?fio=ti" and see "Page not found". And the same page shows this path: api/v1/ personalities/ (?P<fio>.+)/$ Why doesn't it work? my main urls.py: path('personalities/', include('api.v1.personalities.urls')) personalities.urls.py: re_path('(?P<fio>.+)/$', PersonalitiesFilterView.as_view()) I followed the documentation from the django_filters website https://www.django-rest-framework.org/api-guide/filtering/ -
Django: multiple user types with abstract base class
I want to create multiple user types and roles depending on the user type while making the base user model abstract I tried something like this:- class CustomAccountManager(BaseUserManager): ..... class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=150, unique=True) email = models.EmailField(_('email address'), unique=True) firstname = models.CharField(max_length=150, blank=True, null=True) .... class Meta: abstract = true class Client(User): location = models.BooleanField(_(""), default=True) history = models.BooleanField( _(""), default=True) ip = models.BooleanField(_(""), default=True) def __str__(self): return self.username class Vendor(User): Storesmtn = models.ImageField( upload_to="Images", max_length=100000, default="default/default.png") Storesmtn = models.ImageField( upload_to="Images", max_length=100000, default="default/default.png") Storesmtn = models.CharField(max_length=220, blank=False, unique=True) when I migrate the following error appears:- users.Client.groups: (fields.E304) Reverse accessor for 'users.Client.groups' clashes with reverse accessor for 'users.Vendor.groups'. HINT: Add or change a related_name argument to the definition for 'users.Client.groups' or 'users.Vendor.groups'. users.Client.user_permissions: (fields.E304) Reverse accessor for 'users.Client.user_permissions' clashes with reverse accessor for 'users.Vendor.user_permissions'. HINT: Add or change a related_name argument to the definition for 'users.Client.user_permissions' or 'users.Vendor.user_permissions'. users.Vendor.groups: (fields.E304) Reverse accessor for 'users.Vendor.groups' clashes with reverse accessor for 'users.Client.groups'. HINT: Add or change a related_name argument to the definition for 'users.Vendor.groups' or 'users.Client.groups'. users.Vendor.user_permissions: (fields.E304) Reverse accessor for 'users.Vendor.user_permissions' clashes with reverse accessor for 'users.Client.user_permissions'. HINT: Add or change a related_name argument to the definition for 'users.Vendor.user_permissions' or … -
is_superuser flag is not working correctly once loggin and not redirecting to a custom admin dashboard
Once trying to login to the system with a superuser's credentials it is not working properly and redirecting home page instead of custom admin page. The system is treating both superuser and a normal user equally in views but is_superuser flag is working when I use in templates for ex, showing different links in navbar and I am using signals to create user instance. Views.py def custom_user_login(request): if request.method == "POST": username = request.POST.get("username", "") password = request.POST.get("password", "") user = authenticate(request, username=username, password=password) if request.user.is_superuser: login(request, user) return redirect("admin_page") else: login(request, user) return redirect("home") else: form = LoginForm() return render(request, "registration/login.html", {"form": form}) Models.py class User(AbstractUser): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(max_length=250) id_number = models.CharField(max_length=50) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def post_user_created_signal(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) post_save.connect(post_user_created_signal, sender=User) -
Django annotate Multiple Sum with one Many to Many field
Lets take this models: class Computer(models.Model): name = models.CharField(max_length=100, null=False, blank=False) cpu = models.PositiveIntegerField(null=False, blank=False) ram = models.PositiveBigIntegerField(null=False, blank=False) customer = models.ForeignKey( Customer, related_name='Computers', on_delete=models.SET_NULL, null=True, blank=True ) class Disk(models.Model): computer = models.ForeignKey( Computer, related_name='Disks', on_delete=models.CASCADE, null=False, blank=False ) size = models.PositiveBigIntegerField(null=False, blank=False) class Customer(models.Model): name = models.CharField(max_length=255, blank=True, null=True) creation_date = models.DateTimeField(auto_now_add=True) enabled = models.BooleanField( blank=False, null=False, default=False) I want list, by customer, the total number of CPU, RAM, and disk size (with the number of computer for each customer). something like this: {'customer': ACME_Corp., 'cpu__sum': 72, 'ram__sum': 10737418240, 'computer__sum': 10, 'disks__sum': 10000000000000} I tried something like that: Computer.values('customer').annotate(Sum('cpu'), Sum('ram'), Sum('Disks__size'),computer__sum=Count('computer_id')) The problem is: If a computer has multiple Disk, I am going to add his cpu (RAM and count) as many time as his number of disk for example if we have 2 computers with 1 cpu each, but one of them has two disks attached, the cpu total will not be 2, but 3... Any help will be appreciated, thank you !! -
hls.js audio track selection controls missing
I'm using hls.js to playback a m4s encoded http-live-stream. The master.m3u8 file references multiple audio tracks and also references multiple subtitles for my video. I noticed that subtitle track selection is working fine but audio track selection is simply not available at the player controls at all, why that?. I'm using hls.js like so: <script src="{% static 'js/hls.js' %}"></script> <video id="video"></video> <script> if(Hls.isSupported()) { var video = document.getElementById('video'); var hls = new Hls(); hls.loadSource('https://example.com/master.m3u8'); hls.attachMedia(video); hls.on(Hls.Events.MANIFEST_PARSED,function() { video.play(); video.controls = true }); } </script> Is there a way to have these controls added? To me it seems that the player at least supports it. If I take a closer look at the hls.js demo resources right here: https://hls-js.netlify.app/demo/ At the very bottom of the page it shows "Audio-tracks". Using my m3u8 file at the demo page also allows me the change the audio track on-the-fly but its basically outside the player. Thanks in advance -
Why mongoDB is being used in django project
As we know we can build great application with django using postgresql database or additional scalability and feature, sometime we use redis I have notice some people using mongodb in their django project. My question is, what is the case and what specific purpose they are using mongoDB in their django project. Why can't those feature can't be achieved by postgresql or redis? -
Python SMTP - 'linesep' is an invalid keyword argument for encode()
I'm getting the following error in my Django project: 'linesep' is an invalid keyword argument for encode() Python version 3.8.2 and Django version 3.2.4. Here is my code. I'm getting the error when sendmail is being executed. try: sender = settings.SMTP_HOST_USER message = html_message msg = MIMEText(message, 'html') msg['Subject'] = subject msg['From'] = sender msg['To'] = recipient server = smtplib.SMTP(settings.SMTP_HOST, settings.SMTP_PORT) server.login(settings.SMTP_HOST_USER, settings.SMTP_HOST_PASSWORD) server.sendmail(sender, recipient, msg.as_string()) server.quit() return True except Exception as exp: print(str(exp)) return False -
How to pull random images from database(admin) in Django?
I want to pull random images from database with there id number This is my models.py code and Here i am making id field , name and image field from django.db import models from django.db import models from os import listdir import os.path from django.conf import settings from os.path import isfile from os.path import join as path_join from random import choice import internship.settings def random_img(): dir_path = os.path.join(internship.settings.BASE_DIR, 'media') files = [ content for content in listdir(dir_path) if isfile(path_join(dir_path, content)) ] return choice(files) # Create your models here. class images(models.Model): id_no = models.IntegerField() name = models.CharField(max_length=20) image = models.ImageField(upload_to='images') so i want to pull out and show it in a template but everytime i reload the page i need to show a new images .. So How can i do that? i cant able to get the logic -
Taking input, processing it in python code and display output in tables on html page
I am quite new to Django and struggling to do something very simple. I want to convert Boolean expressions into truth table using Django framework. I have python code I wanna know how I can connect it in a way that input from html goes to that python code, gets processed and output is displayed in tables on html page. -
How to write a SQL equivalent right join and insert in Django
I'm trying to convert a SQL query using Django ORM but not getting how to implement the right join and insert in a single query. Below is my SQL query insert into product_inventory ([material_stock] ,[opening_stock] ,[combined_string]) select product_inventorytemp.[material_group] ,product_inventorytemp.[opening_stock] ,product_inventorytemp.[combined_string] from product_inventory right outer join product_inventorytemp on product_inventorytemp.combined_string = product_inventory.combined_string where product_inventory.combined_string IS NULL Below is the Django ORM query that I have tried so far ProductInventory.objects.filter( combined_string__isnull=True ).select_related() Can someone please help me highlight what exactly wrong is with my ORM query, or it would be good to provide an example? Thanks in advance. -
Django: "Login with Facebook" button not working after deployed to pythonanywhere
When I run the app in localhost, it works fine. but after deployed to pythonanywhere, Login with Facebook button doesn't work. when I refresh Login page, in console, it shows => Failed to load resource: https://username.pythonanywhere.com/static/facebook/js/fbconnect.js the server responded with a status of 404 (Not Found) Refused to execute https://username.pythonanywhere.com/static/facebook/js/fbconnect.js as script because "X-Content-Type: nosniff" was given and its Content-Type is not a script MIME type. in template: <a href="{% provider_login_url 'facebook' method='js_sdk' %}"><button class="effect" style="width: 100%; background-color: rgb(58, 110, 255); height: 36px; border: none; color: white; border-radius: 3px; display: flex; justify-content: center;align-items: center;"><img style="height: 24px; width: 24px; background-color: white; padding: 1px; border-radius: 50%;" src="{% static 'images/fblogo.png' %}" alt=""><span style="margin-top: 2px; display: block; margin-left: 8px; font-size: 16px;"> Login with Facebook</span></button></a> <br> Another problem is: CSS doesn't load in admin page how to fix this? -
Caps between card elements
I have Bootstrap card elements in django project. How i can remove caps from card elements? Image <div class="container"> {% for post in posts %} {% if forloop.counter0|divisibleby:3 %} <div class="row text-center"> {% endif %} <div class="col-md-4" onclick="window.location.href=''" style="cursor: pointer"> <div class="card bg-light mb-3" style="max-width: 18rem;"> <div class="card-content"> <div class="card-header"><h4>{{ post.Otsikko| safe }}</h4></div> <p>{{ post.Lisätietoja| safe }}</p> <div class="card-footer"<small>{{ post.Lisätty| safe }}</small></div> </div> </div> </div> {% if forloop.counter|divisibleby:3 or forloop.last %}</div>{% endif %} {% endfor %} </div> -
How to get request.GET.get('variable') in multiple value
How to get the multiple value in input form html to django. I only get the first input value Enroll but when I click the second button which is Payment I cannot get the value also in third input I don't know if the JavaScript is the problem or in my views.py - Beginner programmer :( html and javascript <html> .... <script> function newAppend(name, img, side){ const msgCHAT = ` <div class="msg ${side}-msg"> <div class="msg-img" style="background-image: url(${img})"></div> <div class="msg-bubble"> <div class="msg-info"> <div class="msg-info-name">${name}</div> <div class="msg-info-time">${formatDate(new Date())}</div> </div> <div class="msg-text"><p>How can I help you?</p></div> <br> <div class="butnew"> <button type="submit" class="input-bot" name="input_text" id="inputBot" value="Enroll">Enrollment</button> <button type="submit" class="input-bot" name="input_text" id="inputBot" value="Pay">Payment</button> <button type="submit" class="input-bot" name="input_text" id="inputBot" value="Hi">Hi Username</button> </div> </div> </div> `; msgerChat.insertAdjacentHTML("beforeend", msgCHAT); msgerChat.scrollTop += 500; // =================================================================== const msgerInputTwo = get(".input-bot"); document.getElementById("inputBot").addEventListener("click", event => { event.preventDefault(); const msgTextTwo = msgerInputTwo.value; appendMessage(PERSON_NAME, PERSON_IMG, "right", msgTextTwo); botResponse(msgTextTwo); }); } function botResponse(rawText) { // Bot Response $.get("/chatbot/post", {input_text: rawText }).done(function (data) { console.log(rawText); console.log(data); const msgText = data; appendMessage(BOT_NAME, BOT_IMG, "left", msgText); }); } </script> </html> views.py def chatbot_process(request): ..... message = request.GET.get('input_text') message = message.lower() ints = predict_class(str(message)) response = get_response(ints, intents) response = str(response) return HttpResponse(response) def chatbot(request): return render(request, "chatbot/chatbot.html") URLS.py … -
why i am unable to send email to user to verifiy for completing registeration in django webapp
i want to send user a confomation eamil for sucessfull registeration instead of sending the mail template is showing in my terminal and not sending to user email id here is my code for user registeration my views.py class SignUpView(View): form_class = SignUpForm template_name = 'register.html' def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False # Deactivate account till it is confirmed user.save() current_site = get_current_site(request) subject = 'Activate Your MySite Account' message = render_to_string('account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) messages.success(request, ('Please Confirm your email to complete registration.')) return render( request, 'activation_sent_success.html') return render(request, self.template_name, {'form': form}) class ActivateAccount(View): def get(self, request, uidb64, token, *args, **kwargs): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.profile.email_confirmed = True user.save() login(request, user) messages.success(request, ('Your account have been confirmed.')) return redirect('accounts:home') else: messages.warning(request, ('The confirmation link was invalid, possibly because it has already been used.')) return redirect('accounts:home') my tokens.py file for genrating random token from django.contrib.auth.tokens import PasswordResetTokenGenerator … -
Django: prevent making migrations for some models
Django 3.2.6 I'd like some models not to made migrations at all. Is it possible? I tried: 1. https://docs.djangoproject.com/en/3.2/ref/models/options/#managed class Meta: managed = False 2. class PrimaryReplicaRouter: special_model_names = {'generalsettings', 'generalsettings', } def allow_migrate(self, db, app_label, model_name=None, **hints): if model_name in self.special_model_names: return False return True It doesn't help: migrations are created.It doesn't migrate. But migrations become unnecessarily noisy. I quote from here: https://docs.djangoproject.com/en/3.2/topics/db/multi-db/#allow_migrate makemigrations always creates migrations for model changes, but if allow_migrate() returns False, any migration operations for the model_name will be silently skipped when running migrate on the db. Well, I don't want to make migrations for some models. Is it possible? -
How to resolve Django server startup error
I am facing below error sporadically when i start my Django server. Please help me to resolve this issue. ERROR: File "/usr/lib/python3.8/asyncio/locks.py", line 164, in __init__ self._loop = events.get_event_loop() File "/usr/lib/python3.8/asyncio/events.py", line 639, in get_event_loop raise RuntimeError('There is no current event loop in thread %r.' **RuntimeError: There is no current event loop in thread 'django-main-thread'.** -
React + Django send raw password in HTTP request, security discussion
I am new to Django and I am working on the user authentication part. I used the Django provided User model, and use auth() and login() method when the user login. I have a question about the password security and hope have some discussion here. When the auth() function hashed the raw password and then compares the username and the hashed password. That means the front end needs to send the password in raw data. (Otherwise, it will be hashed twice). Is it not safe to send the password in raw data? If I want to hash the password in the frontend then send the request to Django, what can I do in this case? -
React CkEDITOR Image upload to django backend
I have used React as fronted and DRF for API and Django as backend. I have a ckeditor in React and want to upload a image from ckeditor. How can I acheive that -
DJANGO many to one
I need your help, is really basic. I have two models, Autor and Post with a many to one relationship. I'm having problems retrieving the data in the html page. What I want to do is list all the posts for a specific Autor within a FOR and besides that I need to show the first name and last name of the autor out of the FOR. I really appreciate your help. class Autor(models.Model): first_name = models.CharField(max_length=30, null=False, verbose_name='First Name') last_name = models.CharField(max_length=30, null=False, verbose_name='Last Name') def __str__(self): return self.first_name class Meta: db_table = 'autor' verbose_name = 'Autor' verbose_name_plural = 'Autors' ordering = ['id'] class Post(models.Model): autor = models.ForeignKey(Autor, on_delete=models.CASCADE) post = models.CharField(max_length=200, null=False, verbose_name='Post') def __str__(self): return self.post class Meta: db_table = 'post' verbose_name = 'Post' verbose_name_plural = 'Posts' ordering = ['id'] ```