Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Custom Django Admin Permissions for article Authors
I'm building a website that will include articles. Article content will be stored in a database model. Example: class article(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) date_posted = models.DateTimeField(default=timezone.now) content = models.TextField() ... I'm wanting to use the built-in admin app for adding new articles to the website. And I'm going to have a group called 'author' which will allow other people to log in to the admin section and add new content. My issue is with the permissions. I want to give the 'author' group the permission to add, change, view and delete Articles. But I want to restrict this to only articles that they have created. Basically I don't want them to be able to update other author's posts. Is there a way that I can give them custom permissions so that they only have the ability to change, view, and delete only their own posts? -
Calculated django model field that depends on all the table
I have a model like this: class MyModel(): total_time = IntegerField total_score = IntegerField and I want to add a property or a field to this model which will be called rate and will be calculated according to those fields but on all the table, So if with have this models total time - 1, total score - 3 Total time - 2, total score - 2 Total time - 3, total score - 1 I want that if the rate is calculated by time number 3 is rated 1 but if it is calculated by score number one will be rated 1. What is the best practice for such case? Thank in advance !! -
Move Django Form init field from bottom of form?
How can I move the field that is created by __init__ from the bottom to a specified location on the form? class form(forms.Form): somefield = forms.ChoiceField() def __init__(self, *args, **kwargs): super(form, self).__init__(*args, **kwargs) self.fields['etc'] = forms.ChoiceField I have tried using form ordering but that didn't have an effect? -
Django get_context_data
Is it possible to ‘skip’ a code in get_context_data? I have this parent class and wrote a child class everytime I context.update({}) I want to skip or not run certain key in the parent class, cause it is affecting the performance, especially when parent class has multiple queries inside them, and I don’t want them in the child but certain key, val in the parent? -
Custom django signal not updating my models
I am trying to implement a custom signal but I have never done this before, so I seem to have messed this up. Here is my code from models.py: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save, post_delete from django.dispatch import Signal from django.db.models import Max,Count from django.apps import apps # Create your models here. class Player(models.Model): player_name = models.CharField(max_length=150) current_level_no = models.IntegerField(null=True) no_of_moves = models.IntegerField(null=True) class Meta: verbose_name_plural = 'Players' def __str__(self): return self.player_name class PlayerStats(models.Model): player_name = models.ForeignKey(to=Player, on_delete=models.CASCADE) level_no = models.IntegerField(null=True) moves = models.IntegerField(null=True) class Meta: verbose_name_plural = 'Players Stats' # It works! TotalLevels = 25 MaxCurrentLevel = PlayerStats.objects.aggregate(max_levels=Max('level_no'))['max_levels'] PlayerCount = Player.objects.aggregate(count_players=Count('player_name', distinct=True))['count_players'] def create_player(sender, instance, created, **kwargs): if created: new_username=instance.username Player.objects.create(player_name=new_username, current_level_no=None, no_of_moves=None) def delete_player(sender, instance, **kwargs): deleted_username=instance.username Player.objects.filter(player_name=deleted_username).delete() def create_player_stat(sender, instance, **kwargs): for x in range(1, TotalLevels+1): PlayerStats.objects.create(player_name=instance, level_no=x, moves=None) UpdateLevelsSignal = Signal(providing_args=['Update']) if MaxCurrentLevel != TotalLevels and PlayerCount != 0: UpdateLevelsSignal.send(UpdateLevelsSignal,Update=True) def UpdateLevels(sender, Update,**kwargs): if Update: if MaxCurrentLevel < TotalLevels: for x in Player.objects.all().values_list('player_name', flat=True): instance = Player.object.get(player_name=x) for y in range(TotalLevels-MaxCurrentLevel, TotalLevels+1): PlayerStats.objects.create(player_name=instance, level_no=y, moves=None) else: for x in Player.objects.all().values_list('player_name', flat=True): instance = Player.object.get(player_name=x) for y in range(MaxCurrentLevel-TotalLevels, MaxCurrentLevel+1): PlayerStats.objects.filter(player_name=instance, level_no=y, moves=None).delete() post_save.connect(create_player, sender=User) post_delete.connect(delete_player, sender=User) post_save.connect(create_player_stat, sender=Player) UpdateLevelsSignal.connect(UpdateLevels, … -
How to display image from Postgres Database using python views.py
I have a table is postgres database and the table has a column name castimage with the data type bytea. I inserted image into the column with a query (it shows [binary data]). When i tried to show the image in my HTML page it doesn't show. Is there a way to display image in my page? OR should I change the field data type which I used to store Image? views.py def search(request): FormSearchMovies1=FormSearchMovies() image=Tblcast.objects.get() return render(request,"search.html",{'FormSearchMovies1':FormSearchMovies1,'image': image}) models.py class Tblcast(models.Model): castid = models.AutoField(primary_key=True) castname = models.CharField(max_length=100) castimage = models.BinaryField() HTML <img src="{{image.castimage.url}}" alt="CastImage" class="img-fluid"> -
Hot to modify JS/AJAX so that dependent drop-down loads with options when the page first loads?
I have a form with a dependent drop-down. This secondary drop-down is hidden whenever the primary option selected does not have any secondary options, and when the page first loads. Whenever the form is submitted, only the first field gets cleared out, since most of the time the drop-downs remain the same, however, since the script works whenever there is a change in the primary drop-down, since the load upon does not constitute a change, it just keeps the selected/submitted option on the primary drop-down, and will just display an empty secondary drop-down, even when the primary option selected does have secondary options. I got most of the JS from the drop-down from a tutorial, as I am not very familiar with it. For a more visual understanding: This is the form when the page first loads When you select an option that has secondary options, the other dropdown appears After you select a Station and submit, the Employee # clears, but the other two are supposed to remain, however, when the page reloads upon submission, it looks like this, and the station has been cleared according to the debugger since there are none technically. I don't care so much … -
django-channels does not work with daphne on linux server
I'm using Django-eventstream over Django channels to send an event to my client app (react using eventstream), on my local machine the events are sent correctly to the client. but when I upload the app to my Linux server the webhook just getting open and 'keep-alive' but the events won't get to the client at all. I use daphne to deploy my Asgi app and use Nginx as my getaway. when I use "python manage.py runserver" (on the Linux server) the client is getting all the messages. because of that my clients do get the messages when I use runserver command I assume that my Nginx configuration is right (correct me if I'm wrong) and the problem is in Daphne somehow. I don't see the events trying to be sent in the daphne logs at all. does anyone have a clue why this is happening? Thanks! the command I used to run Daphne: daphne --verbosity 3 -p 8001 my_project.asgi:application here is my Daphne log: [06/12/2019 14:52:34] INFO [daphne.cli:287] Starting server at tcp:port=8001:interface=127.0.0.1 2019-12-06 14:52:34,376 INFO Starting server at tcp:port=8001:interface=127.0.0.1 [06/12/2019 14:52:34] INFO [daphne.server:311] HTTP/2 support enabled 2019-12-06 14:52:34,377 INFO HTTP/2 support enabled [06/12/2019 14:52:34] INFO [daphne.server:311] Configuring endpoint tcp:port=8001:interface=127.0.0.1 2019-12-06 … -
Get Previous Months in python-Django
I want to generate a code in python to get the previous 10 months from the month we are in and the next month (to get some stats for it and labels in Line chartJs) e.g(we are currently in December 2019 , I want it to show from Feb 2019 - Jan2020) I have tried the old way but it is fixed range: months =[] for j in range(12): curr_month = calendar.month_name[j] my = [curr_month,y] months.append(my) # print(months) lnqs_rfq =[] lnqs_local =[] allrq = [] for i in range(12): lnqs_rfq.append(Request.objects.filter(req_date__month=(i),req_type='stock').count()) lnqs_local.append(Request.objects.filter(req_date__month(i),req_type='Local').count()) allrq.append(Request.objects.filter(req_date__month=(i)).count()) I tried also panda but I don't get the previous months : td = datetime.today() mon = pd.date_range(start=td ,periods = 12, freq='MS').strftime("%b,%Y").tolist() print(mon) I hope you help me if there is a better way. Thanks -
uwsgi falied , vultr server, django+ngin+uwsgi
please help, i dont know the reason why uwsgi failed uwsgi.service - uWSGI Emperor service Loaded: loaded (/etc/systemd/system/uwsgi.service; disabled; vendor preset: disabled) Active: failed (Result: start-limit) since Wed 2019-11-20 09:41:15 EST; 2 weeks 2 days ago Process: 31588 ExecStart=/usr/bin/uwsgi --emperor /etc/uwsgi/sites (code=exited, status=203/EXEC) Process: 31585 ExecStartPre=/usr/bin/bash -c mkdir -p /run/uwsgi; chown user025:nginx /run/uwsgi (code=exited, status=0/SUCCESS) Main PID: 31588 (code=exited, status=203/EXEC) Warning: Journal has been rotated since unit was started. Log output is incomplete or unavailable. uwsgi.service file content: [Unit] Description=uWSGI Emperor service [Service] ExecStartPre=/usr/bin/bash -c 'mkdir -p /run/uwsgi; chown user025:nginx /run/uwsgi' ExecStart=/usr/bin/uwsgi --emperor /etc/uwsgi/sites Restart=always KillSignal=SIGQUIT Type=notify NotifyAccess=all [Install] WantedBy=multi-user.target firstsite.ini content: [uwsgi] project = firstsite username = user025 base = /home/%(username)/myproject chdir = %(base)/%(project) home = %(base)/myprojectenv module = %(project).wsgi:application master = true processes = 5 uid = %(username) socket = /run/uwsgi/%(project).sock chown-socket = %(username):nginx chmod-socket = 660 vacuum = true -
loading admin page after upgrading to django 3.0 crashes dev. server
I upgraded Django from 2.2 to 3.0, Now I can't access admin page. Every time I access http://127.0.0.1:8000/admin the dev. server quits without any message or error. I wen to upgrade by following this link: https://docs.djangoproject.com/en/3.0/howto/upgrade-version/ Is this a common issue or do I have any error. -
Django/ReportLab: pdf print do not works on alwaysdata
I just have deployed an update of my project on alwaysdata.net All works except pdf print I do not have any error and looking browser debug network request status is 200 but I can not find my pdf anywhere in local, pdf is save in download folder -
Activated Virtualenv in commands but the bracket is not showing in the directory [Python]
I am trying to learn django. In VS code, I have installed pip and virtualenv. I created a env folder by using virtualenv command. $ virtualenv env To activate virtual environment, I ran the command below. $ source env/bin/activate The result I was expecting to see was I see the little brackets in front of directory address in bold below. However, I do not see any brackets to indicate that the virtual environment is being activated. dhkang@dhkang-Lenovo-IdeaPad-S145-15API ~/fastcampus/django % source env/bin/activate **dhkang@dhkang-Lenovo-IdeaPad-S145-15API ~/fastcampus/django % (env) ** However, I do not see (env) here. I don't know if the virtual environment is activated or not. Does anyone know how to resolve to show the brackets when virtual environment is activated? -
Django how to make a form
I try to make an user registration form, how do make a form to this code: from django.contrib.auth.models import User from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): STUDENT = 1 TEACHER = 2 SUPERVISOR = 3 ROLE_CHOICES = ( (STUDENT, 'Student'), (TEACHER, 'Teacher'), (SUPERVISOR, 'Supervisor'), ) user = models.OneToOneField(User, on_delete=models.CASCADE) location = models.CharField(max_length=30, blank=True) birthdate = models.DateField(null=True, blank=True) role = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, null=True, blank=True) def __str__(self): # __unicode__ for Python 2 return self.user.username @receiver(post_save, sender=User) def create_or_update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() Create this form I don't know how to made this -
Problems understanding Django app dependencies
I'm relatively new to Django working on my first project. Im getting kinda confused when it comes to app dependencies in Django. Comming from Odoo (Python based ERP-System) Apps/Modules all have their own manifest.py which handles dependencies amongst other things. So you can say App1 depends on App2 and cannot be installed without its dependency being installed. How would I handle something like that in Django? Say I have an app called "account" for user accounts and I wanna make a new app "account_profile" where I put everything related to user profiles. Classes in "account_profile" may inherit from "account". What are best practises to achieve something similiar in Django? Or is it even needed here? -
How to get MIMEText to render HTML?
I'm not quite sure what I'm doing wrong with MIMEText. The emails are still sending as plain text. The email body that the user receives looks like this: Content-Type: text/html; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit <html>Thanks for signing up. Go to <a href=localhost:8000/confirm>confirm</a> to complete your registration.</html> (In this example it links to localhost, but in production it will be to my site) Here is the relevant code from my views.py file: from email.mime.text import MIMEText import mailer def signup(request): current_site = get_current_site(request) email_address = request.user.email mail_subject = 'Welcome!' msg = u'<html>Thanks for signing up. Go to <a href=localhost:8000/confirm>confirm</a> to complete your registration.</html>' print(msg) html_msg = MIMEText(msg, 'html') send('myemail@gmail.com', 'myemailpassword', email_address, mail_subject, html_msg) And here is the email sender module, mailer.py: import smtplib def send(user, pwd, recipient, subject, body): FROM = user TO = recipient if type(recipient) is list else [recipient] SUBJECT = subject TEXT = body # Prepare actual message message = """From: %s\nTo: %s\nSubject: %s\n\n%s """ % (FROM, ", ".join(TO), SUBJECT, TEXT) try: server = smtplib.SMTP("smtp.gmail.com", 587) server.ehlo() server.starttls() server.login(user, pwd) server.sendmail(FROM, TO, message) server.close() print('successfully sent the mail') except Exception as e: print("\n\nfailed to send mail, here's why:\n") print(e) Thank you for any help at all here. -
request.method and request.GET in Django
I am following a tutorial and I am unable to understand some lines in it from django.shortcuts import render, get_object_or_404 from django.http import HttpResponseRedirect from . models import Page from .forms import ContactForm def index(request, pagename): pagename = '/' + pagename pg = get_object_or_404(Page, permalink=pagename) context = { 'title': pg.title, 'content': pg.bodytext, 'last_updated': pg.update_date, 'page_list': Page.objects.all(), } # assert False return render(request, 'pages/page.htm', context) def contact(request): submitted = False if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): cd = form.cleaned_data #assert False return HttpResponseRedirect('/contact?submitted=True') else: form = ContactForm() if 'submitted' in request.GET: submitted = True return render(request,'pages/contact.htm',{'form': form, 'page_list': Page.objects.all(), 'sbmitted': submitted}) The above is pages/view.py file {% extends "pages/page.htm" %} {% block title %} Contact us {% endblock title %} {% block content %} <h1>Contact us</h1> {% if submitted %} <p class="success"> Your message was submitted successfully. Thankm you. </p> {% else %} <form action="" method="post" novalidate> <table> {{ form.as_table }} <tr> <td>&NonBreakingSpace;</td> <td><input type="submit" value="Submit"></td> </tr> </table> {% csrf_token %} </form> {% endif %} {% endblock content %} The above is pages/contact.htm file so, what is meaning of "if request.method == 'POST':" and why is there "if submitted in request.GET: submitted=True"? I have googled a lot but … -
Django iis deployment postgres
I have deployed a django app on an iis server. I'm using postgres as the database. However while connecting with the application remotely, I'm getting they following error - Operational error.. An error has occurred: could not connect to server: No buffer space available (0x00002747/10055) is the server running on "localhost" (::1) and accepting TCP/IP connections on port 5432? could not connect to server : no buffer space avalaible (0x00002747/10055) is the server running on "localhost" (::1) and accepting TCP/IP connections on port 5432? What could be the possible scenario: 1. Should i ask the server team to unblock port 5432 for remote access? 2. Is any other configurations required at server end? -
i need to know how i user OPT pin instead of password [closed]
i would like know how can a user use OTP pin instead of a user inserting password. The code for generating OTP in using email address. -
NoReverseMatch at /tinku/update
Reverse for 'update_student' with no arguments not found. 1 pattern(s) tried: ['(?P[-a-zA-Z0-9_]+)/update$'] it is showing error above please tell if anyone know about this how to resolve this urls.py path('',views.index,name="home"), path('<slug:name>/update',views.student_update,name="update_student"), path('delete/<slug:name>',views.student_delete,name="delete_student") student_update.html <div class=" row d-flex justify-content-center"> <div class="col-md-6 box-shadow"> <form action="{% url 'update_student' %}" method="POST" class="form"> {% csrf_token %} {{updateform|crispy}} <button class="btn btn-primary form-control">update</button> </form> </div> views.py:- def student_update(request,name): instance=get_object_or_404(Student,name=name) print(instance) form=StudentForm(request.POST,instance=instance) print(form) if form.is_valid(): form.save() return redirect('home') return render(request,'webapp/student_update.html',{'updateform':form}) models.py from django.db import models from django.core.validators import MaxValueValidator,MinValueValidator from django.contrib.auth.models import User class Student(models.Model): gender=( ('M','male'), ('F','female') ) name=models.CharField(max_length=50) age=models.PositiveIntegerField(validators=[MinValueValidator(18),MaxValueValidator(50)]) sex=models.CharField(max_length=1,choices=gender) def __str__(self): return self.name forms.py from django import forms from django.core.validators import MaxValueValidator,MinValueValidator from webapp.models import Student class StudentForm(forms.ModelForm): class Meta: model = Student fields=['name','age','sex'] -
migration images to another table and save them
I was using images in one table of Product like that class Product(models.Model): category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.CASCADE) brand = models.ForeignKey(Brand, on_delete=models.DO_NOTHING, null=True, blank=True) name = models.CharField(max_length=200) image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True, null=True) image1 = models.ImageField(upload_to='products/%Y/%m/%d', blank=True, null=True) image2 = models.ImageField(upload_to='products/%Y/%m/%d', blank=True, null=True) image3 = models.ImageField(upload_to='products/%Y/%m/%d', blank=True, null=True) image4 = models.ImageField(upload_to='products/%Y/%m/%d', blank=True, null=True) But I am going to move this images to another table which includes only images class ProductImage(models.Model): image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True, null=True) image1 = models.ImageField(upload_to='products/%Y/%m/%d', blank=True, null=True) image2 = models.ImageField(upload_to='products/%Y/%m/%d', blank=True, null=True) image3 = models.ImageField(upload_to='products/%Y/%m/%d', blank=True, null=True) image4 = models.ImageField(upload_to='products/%Y/%m/%d', blank=True, null=True) one problem is that I added many images in Product table now If I do this without deleting products. Can I add those images to product? But how can I do? any help please -
ImproperlyConfigured Django error when runing an external script
hi all I've coded a script that generates some Django files with the following structure _Django-project | |_main-app | | | |_ urls.py | views.py | . | . | |_Django-project | | | |_settings.py | urls.py | . | . | |_manage.py myscript.py the problem is when I try to run myscript.py Django raises this error ImproperlyConfigured: You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings myscript.py import ast from main-app.models import * with open('main-app/models.py', 'r') as myfile: source = myfile.read() p = ast.parse(source) classes = [node.name for node in ast.walk(p) if isinstance(node, ast.ClassDef) and node.name != "Meta"] #fields are Classname+fields returns a list for i in range(len(classes)): exec("a="+classes[i]+"()") exec(classes[i]+"fields = [key for key in a.__dict__ if key != '_state']") the code works well when I run it in the shell but when I try to run the file it fails! i think that the problem is because of from main-app.models import * -
Django - QuerySet is not iterable in permissions.py
New to Django and Django Rest here. I have the following structure : class MyUsers(AbstractUser): email = models.EmailField(unique=True) USERNAME_FIELD = 'email' class roles(models.Model): id = models.AutoField(primary_key=True) label = models.CharField(max_length=80) class user_roles(models.Model): id_user = models.ForeignKey(MyUsers,on_delete=models.CASCADE) id_role = models.ForeignKey(roles,on_delete=models.CASCADE) I'm trying to create a custom permission, to allow users with a specific role to access some endpoints. class IsAuthenticatedAndLeader(BasePermission): def has_permission(self, request, view): id_role=models.roles_users.objects.filter(id_user=request.user.id).values_list('id_role',flat=True) if "Leader" in models.roles.objects.filter(id=id_role).values_list('label',flat=True): return request.user and request.user.is_authenticated def has_object_permission(self, request, view, obj): return True When I try to access to the endpoint, I have the following error: TypeError: argument of type 'QuerySet' is not iterable However if I try in views.py something simple like the following it works : if "Leader" in models.roles.objects.filter(id=3).values_list('label',flat=True): print("Yes") So I'm not sure why I'm getting this error when trying to apply it to permissions.py -
django-rest-auth unable to access user details page
I am using django-rest-auth to authenticate and register my user I can do everyhting. Login is working Registration is working but I am unable to access get User details: /rest-auth/user/ (GET, PUT, PATCH) I am trying to access this endpoint I am using JWT I am getting correct token. But when I am using this command in curl: curl -X GET http://localhost:8000/rest-auth/user/ -H 'Authorization: Bearer <jwt-toke>' I am getting this error: {"detail":"Authentication credentials were not provided."} What do I need to do to access details of user -
Django-Alwaysdata->TypeError: 'client_encoding' is an invalid keyword argument for this function
I try to deploy ma django project on Alwaysdata but get an error I am not very confortable with deployment I follow steps mentionned in alwaysdata doc what I have done via Shell in box on alwaysdata: - clone my project - setup settings.py (with parameters that use to works) - activate my env - install requirements.txt My database seems to be OK (with data inside) I contact alwaysdata supports that say me it is a python problem TypeError: 'client_encoding' is an invalid keyword argument for this function