Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Allauth Custom User Model - Add Bootstrap Styled Checkbox To Signup Form That Submits To Database
What I want to do sounds simple - basically add a boostrap 4 styled checkbox to the allauth signup form that submits the user's response to that checkbox to the database along with their default allauth signup form data such as their username, email, etc. I cannot find a good tutorial anywhere online how to do this especially since it could have many different uses - such as asking a user on signup to accept the terms of service / privacy policy, sign up for marketing emails, or asking the user if they are above a certain age which is what I am trying to do. Here is what I tried so far (I added a checkbox to the allauth form in one of my forms.py located in one of my main app folders and also tried adding a model in that app for my project). But it is not submitting to the database and I am not sure how to style the checkbox using bootstrap. Courses forms.py: class CaptchaSignupForm(SignupForm, CaptchaRequirement): captcha = CaptchaField() is_age_compliant = forms.BooleanField(required=True,initial=False,label='Are you at least 13 years old?') field_order = ['username', 'email', 'password1', 'password2', 'is_age_compliant', 'captcha',] def __init__(self, *args, **kwargs): super(CaptchaSignupForm, self).__init__(*args, **kwargs) self.fields['captcha'].widget.attrs['class'] = … -
Django : How to check if element in the queryset?
I'd liket to make is current_user exist in queryset, so i try: {% if obj.payer.name == current_user.username %} {{ obj.price|intcomma }} / {{obj.dutch_payer.all.count}}</p> <p>={{ obj.price|div_payer_me:obj.dutch_payer.all.count|intcomma }}</p> {% else %} {% if current_user.username in obj.dutch_payer.filter(name=current_user.username) %} {{ obj.price|intcomma }} / {{obj.dutch_payer.all.count|add1}}</p> <p>={{ obj.price|div_payer_notme:obj.dutch_payer.all.count|intcomma }}</p> {% else %} 0 {% endif %} {% endif %} but error occur : Could not parse the remainder: '(name=current_user.username)' from 'obj.dutch_payer.filter(name=current_user.username)' Tempfriend model: class Tempfriend(core_models.TimeStampedModel): name = models.CharField(max_length=30) belongs_to = models.ForeignKey( user_models.User, on_delete=models.CASCADE, related_name="belongs_to") def __str__(self): return self.name moneylog model: class Moneylog(core_models.TimeStampedModel): moneybook = models.ForeignKey( moneybook_models.Moneybook, on_delete=models.CASCADE) pay_day = models.DateTimeField(default=NOW) payer = models.ForeignKey( tempfriend_models.Tempfriend, on_delete=models.CASCADE, related_name="payer") dutch_payer = models.ManyToManyField( tempfriend_models.Tempfriend, related_name="dutch_payer", blank=True) price = models.IntegerField() category = models.CharField(max_length=10) memo = models.TextField() objects = models.Manager() as you see, dutch_payer and current_user is different model. How can I check the is there current_user in dutch_payer? -
Inheritance in Django
class OldComputer: transistors = models.IntegerField(null=False) class SuperComputer(OldComputer): objects = models.Manager() transistorCount = models.IntegerField(default=500) in create obj = self.model(**kwargs) TypeError: 'NoneType' object is not callable I get the above error when calling SuperComputer.objects.create() Why is this? When inheriting from a Parent class, do i have to provide values for the inherited fields? -
Django, create a form with additional fields
I have a model : class Post(models.Model): name = models.CharField(max_length=100) desc = models.TextField() Now i want to make a form that will containt extra fields. So my form can be look like this: name, desc,can_see, can_comment Here is my view: class CreatePostView(LoginRequiredMixin, CreateView): model = Post fields = ['name','desc','upload_file'] serializer = UserPermissionSerialize() def form_valid(self, form): return super().form_valid(form) -
How to run multiple django services in on Docker container?
I have a Django project with a few microservices which heavily rely on django infrastructure itself and have to be started with: python manage.py sevicename1 python manage.py sevicename2 python manage.py sevicename3 python manage.py sevicename4 python manage.py sevicename... They all communicate with each other. What is the proper way to run them in one Dockerfile all together? -
i was going to render the saved data into html table but found this error
<tbody> {% for publication in publication_list %} <tr> <td>{{%publication.addpublication%}}</td> </tr> {% endfor %} </tbody> views.py def publicationlist(request): context = {'publication_list' : AddPublication.objects.all()} return render(request,"publication_list.html", context) TemplateSyntaxError at /addpublication/publicationlist/ Could not parse the remainder: '%publication.addpublication%' from '%publication.addpublication%' -
Changing ModelChoiceField to ModelMultipleChoiceField
I have a CreateView CBV where I override get_form to set a field type: def get_form(self, form_class=None): form = super(EventMembershipCreate, self).get_form(form_class) form.fields['person'] = forms.ModelChoiceField( queryset=Person.objects.all(), to_field_name='email' ) return form This works fine when the field is ModelChoiceField, however I want to allow the users to create multiple objects which I will capture and get_or_create in def post():. To do this, I change the field type to a multiple choice field set as form.fields['person'] = forms.ModelMultipleChoiceField. However, even when submitting just one value on the form, I get the following error: ValueError at /lists/event/1/add/ Cannot assign "QuerySet Person: email@domain.com": "EventMembership.person" must be a "Person" instance. The email input definitely is a Person instance, so I am not sure what is throwing this error. Why does this get_form override work with ModelChoiceField and not ModelMultipleChoiceField? -
Unable to run Django server after executing custom python code
I reconstructed a Django boilerplate where I divided the settings as different files for production and development separately inside production.py and development.py respectively. Here, src was renamed from main. They both import everything from base.py. The folder structure of my project looks like this: -Django_boilerplate -src -core -migrations -management -commands -rename.py -main -settings -base.py -development.py -production.py -templates -db.sqlite3 -manage.py I wrote the rename.py so that whenever I work on a new project, I can just start the project by running this file to rename the project accordingly. My rename.py file looks like this: from django.core.management.base import BaseCommand import os class Command(BaseCommand): help = 'Renames a Django project' def add_arguments(self, parser): parser.add_argument('new', type=str, help='The new Django project name') def handle(self, *args, **kwargs): new_project_name = kwargs['new'][0] files_to_rename = ['main/settings/base.py', 'main/asgi.py', 'main/wsgi.py', 'manage.py'] folder_to_rename = 'main' for f in files_to_rename: with open(f, 'r') as file: filedata = file.read() filedata = filedata.replace(folder_to_rename, new_project_name) with open(f, 'w') as file: file.write(filedata) os.rename(folder_to_rename, new_project_name) self.stdout.write(self.style.SUCCESS(f'Project has been renamed to {new_project_name}')) Then I executed the rename.py file by running python rename.py ecommerce The first time, it executed and changed the settings as os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ecommerce.settings.development') in manage.py and os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ecommerce.settings') in the asgi.py & wsgi.py files but not in … -
Can't seem to trigger error_message to display with django3?
I was working through the Django3 tutorial and doing some of my own stuff with it. I have this template sales_orders/details.html <h1>{{ sales_order.number }}</h1> {% if error_messsage %} <p><strong> {{ error_message }} </strong></p> {% endif %} <h2>Date: {{sales_order.date}}</h2> <form action="{% url 'sales_orders:update' sales_order.id %}" method="POST"> {% csrf_token %} <input type="text" name="totalAmount" id="totalAmount" value="{{ sales_order.totalAmount }}"> <label for="totalAmount">Total Amount: $</label> <input type="submit" value="Update"> </form> and these two views def detail(request, salesOrder_id): # try: # sales_order =salesOrder.objects.get(pk=salesOrder_id) # except salesOrder.DoesNotExist: # raise Http404('Question does not exist.') # return render(request, 'sales_orders/detail.html', {'sales_order':sales_order}) sales_order = get_object_or_404(salesOrder, pk=salesOrder_id) return render(request, 'sales_orders/detail.html', {'sales_order':sales_order}) def update(request, salesOrder_id): sales_order = get_object_or_404(salesOrder, pk=salesOrder_id) print("got sales order") try: totalAmount = float(request.POST['totalAmount']) except ValueError: print("totalAmountError") return render(request, 'sales_orders/detail.html', { 'sales_order': sales_order, 'error_message': "Amount must be a number.", }) print(f"got total Amount {totalAmount}") if totalAmount < 0: print("returning error message") # return error_messsage return render(request, 'sales_orders/detail.html', {'sales_order':sales_order, 'error_message':"Amount must be postiive",}) else: print("redirect") sales_order.totalAmount = totalAmount sales_order.save() # Return with httpresponserequest aftersuccessful # Dealing with post data, toprevent dobule posting return HttpResponseRedirect(reverse('sales_orders:results', args=(sales_order.id,))) I started purposefully trying to raise errors with this to just get the {% if error_message %} {{error_message}} to show, but I can't seem to do it despite confirming … -
Install mysqlclient for Django database via pip
I have installed MySQL-server, python3-dev, libmysqlclient-dev. But whem I try to install mysqlclient via pip, I get some errors that I don't understand. Like this: (Env) randomparatololer@randomparatololer:~/Documents/DJANGO/tigabelas$ pip install mysqlclient Collecting mysqlclient Using cached mysqlclient-1.4.6.tar.gz (85 kB) ERROR: Command errored out with exit status 1: command: /home/randomparatololer/Documents/DJANGO/Env/bin/python3.8 -C 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-r_ybnapl/mysqlclient/setup.py'"'"'; __file__='"'"'/tmp/pip-install-r_ybnapl/mysqlclient/setup.py'"'"';f=getattr (tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace ('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec (compile (code, __file__, '"'"'exec'"'"')' egg_info &ndash; egg-base /tmp/pip-install-r_ybnapl/mysqlclient/pip-egg-info cwd: /tmp/pip-install-r_ybnapl/mysqlclient/ Complete output (11 lines): Traceback (most recent call last): File "<string>", line 1, in <module> File "/home/randomparatololer/Documents/DJANGO/Env/lib/python3.8/site-packages/setuptools/__init__.py", line 20, in <module> from setuptools.dist import Distribution, Feature File "/home/randomparatololer/Documents/DJANGO/Env/lib/python3.8/site-packages/setuptools/dist.py", line 35, in <module> from setuptools import windows_support File "/home/randomparatololer/Documents/DJANGO/Env/lib/python3.8/site-packages/setuptools/windows_support.py", line 2, in <module> import ctypes File "/usr/local/lib/python3.8/ctypes/__init__.py", line 7, in <module> from _ctypes import Union, Structure, Array ModuleNotFoundError: No module named '_ctypes' ---------------------------------------- ERROR: Command errored out with exit status 1: Python setup.py egg_info Check the logs for full command output. -
How to make Static files working with javascript?
I am trying to use static files in my Django project but it just not displays them. I have looked thru the code and tried to provide the whole home.html Most part is copy paste Bootstrap that should be perfect I have tried to do the Java Script parts. <!doctype html> { load staticfiles } <html lang="en"> <head> <meta charset="utf-8"> </head> <body> <header> <!-- DELETED HEADER --> <!-- <div class="collapse bg-dark" id="navbarHeader"> <div class="container"> <div class="row"> <div class="col-sm-8 col-md-7 py-4"> <h4 class="text-white">About</h4> <p class="text-muted">Add some information about the album below, the author, or any other background context. Make it a few sentences long so folks can pick up some informative tidbits. Then, link them off to some social networking sites or contact information.</p> </div> <div class="col-sm-4 offset-md-1 py-4"> <h4 class="text-white">Contact</h4> <ul class="list-unstyled"> <li><a href="#" class="text-white">Follow on Twitter</a></li> <li><a href="#" class="text-white">Like on Facebook</a></li> <li><a href="#" class="text-white">Email me</a></li> </ul> </div> </div> </div> </div> <div class="navbar navbar-dark bg-dark shadow-sm"> <div class="container d-flex justify-content-between"> <a href="#" class="navbar-brand d-flex align-items-center"> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" aria-hidden="true" class="mr-2" viewBox="0 0 24 24" focusable="false"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 … -
How can I write database Django database model instances during startup of the Django project?
Is there a way to write the values of database model instances with initialization values during the startup phase of the Django project? BTW: I'm not interested in migrations which require to invoke the command line prior to starting the Django project. The changes to the database shall be persistent w.r.t. the database change history. -
How to get and update an Django object in one query?
To optimize a lot my database I would like to make as less as possible any query. I'm trying to get an object, increment the field "count_limit" and make an If statement after on the Customer instance. To achieve it I've made this query who worked well. Customer.objects.filter(user=user).update(count_limit=F('count_limit') + 1) So after this query, count_limit has been incremented by 1 as I wanted. When I'm trying to get the Customer instance as a result of this query, it returns "1". Is it possible to make both, update the instance and get it as a return object ? Thanks a lot -
overriding restauth password reset email issues
Good day, I am trying to override the password_reset_email of Django allauth. the issue is that it successfully overrides but I get the html code just sent to the user instead of the html representation. I was expecting a styled email just like I got for my confirmation email, but this does not seem to be the case. In my templates/registration/password_reset_email.html {% load i18n %} {% autoescape off %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Confirm Your E-mail</title> <style> .body { background-color: #f6f6f6; padding: 30px; display: flex; flex-direction: row; justify-content: center; align-items: center; } .content { background-color: #FFFFFF; color: #4d4d4d; max-width: 400px; padding: 20px; margin: auto; } .title { font-size: 20px; font-weight: 600; margin: 10px 0; text-align: center } .intro { font-size: 15px; align-self: flex-start; color: #4d4d4d; margin-bottom: 15px; } .main-body { font-size: 15px; color: #4d4d4d; margin-bottom: 15px; } .alt-body { width: 100%; display: flex; flex-direction: row !important; justify-content: center !important; } .alt-body>a { font-size: 17px; font-weight: 500; text-decoration: none; color: #FFFFFF; margin: auto; margin-bottom: 15px; } .cta-button { background-color: #525659; padding: 9px 100px; border: 2px solid #525659; border-radius: 35px; align-self: center; } .cta-button:hover { background-color: #000000; border: 2px solid #000000; } … -
Django group by and count(*), includes zero counts
class Author(models.Model): name = models.CharField(max_length=50) class Book(models.Model): name = models.CharField(max_length=50) author = models.ForeignKey(Author,related_name='book' on_delete=models.CASCADE) is_deleted = models.BooleanField(default=False) I want to display the number of books in each author (include zero counts). My code: Book.objects.filter(is_deleted =False).values('author').annotate(num=Count('id')) but it only returns values greater than zero and lost many authors. How can I get result like this: author1:0, author2:1, author3:2, Please help me and thanks in advance ^^. -
Django : changing browser zoom in production
The zoom level of my website is not the same in production as it is in development. I would like the zoom level to be the same as it is in development. That corresponds to a 75% zoom in production. Is there a way to do this with Django ? Maybe in the settings or in the templates ? Thanks in advance ! -
Site matching query does not exist on login page after enabling django-registration-redux
Getting the error message DoesNotExist at /accounts/login/ Site matching query does not exist. when trying to redirect users to my login page. Users should be able to view login, enter details and be redirected to their profile pages depending on their profile type (teacher, student). This is what I have in classroom.py(views.py): #login process class LoginView(TemplateView): template_name = 'registration/login.html' and urls.py: urlpatterns = [ path('', include('classroom.urls')), path('accounts/', include('django.contrib.auth.urls')), path('accounts/signup/', classroom.SignUpView.as_view(), name='signup'), path('accounts/signup/student/', students.StudentSignUpView.as_view(), name='student_signup'), path('accounts/signup/teacher/', teachers.TeacherSignUpView.as_view(), name='teacher_signup'), path('accounts/login/', classroom.LoginView.as_view(), name='login') ] This error started occurring after I enabled django-registration-redux and added django.contrib.sites to my installed apps in my settings -
Get the email of the current recipient, Django
I am building a blog app using django. It's a simple blog so it doesn't have a sign-in/sign-up function, but people can leave comments on posts using emails. And things go something like this: 1- Person leaves a comment on a post. 2- Once the comment is saved Person gets added to the subscription list of that post(only if they're not already on that list) so I could notify them when new comments are added to the post. 3- Send emails to people on the subscription list notifying them of the new comment, and with the email, there's a link to let people unsubscribe from receiving further emails. The problem I am facing right now is that I can't figure out how to fetch the recipient's email to pass it to the unsubscribe view instead of asking them to write it in an input field. def unsubscribe_from_post(request, slug, email): #I don't how to know the email of the recipient to pass it post = Post.objects.get(slug=slug) #to this function without asking them to write it down post.recipients.filter(recipient_email=email).delete() in models.py class Post(models.Model): title = models.CharField(max_length=120) body = models.TextField() pub_date = models.DateTimeField(auto_now_add=True) categories = models.ManyToManyField('Category', related_name= 'posts') slug = models.SlugField(null=True) recipients = models.ManyToManyField('Recipient') … -
Django - saving one model during saving another model
I need to creaet records in model Tabel after creation moden Vacation. I have Employee who creates a vacation and each date from the duration of vacation has to go to model Tabel. name = models.CharField('Name', max_length = 20) last_name = models.CharField('Last name', max_length = 20) def __str__(self): return self.last_name class Vacation(models.Model): employee = models.ForeignKey(Employee, on_delete = models.SET_NULL, blank = True, null = True) vacation_type = models.ForeignKey(VacationType, on_delete = models.SET_NULL, blank = True, null = True) date_creation = models.DateTimeField(auto_now = True) start_date = models.DateField() end_date = models.DateField() duration = models.DurationField(default=timedelta) class Tabel(models.Model): employee = models.ForeignKey(Employee, on_delete = models.SET_NULL, blank = True, null = True) date = models.DateField() day_type = models.ForeignKey(TabelType, on_delete = models.SET_NULL, blank = True, null = True) late_changes = models.BooleanField(default = False) I just start with Django. What shoud I use to update model Tabel after Vacation creation? Thank you in advance for any advice! -
Django and virtual machine management
I have several virtual machines. Can I make sure that data from virtual machine consoles is sent to my Django server located on the host (my computer)? Can I use the Django server to manage these virtual machines using console commands? If so, how can I search for this information and how can I do it better? -
How to copy all the items in one parent django-model to child django-model in a simple way
In my project, I code it like this: def add_delete_comment(obj): DeletedComments.objects.all().delete() deleted_obj = DeleteCommentView( movie = obj.movie, user = obj.user, comment = obj.comment date = obj.date, likes = obj.likes, dislikes = obj.dislikes, reports = obj.reports ) deleted_obj.save() But I need a simple way to do this. Just Copying the model items from parent class to subclass. Is this is the only way to do this? -
Accessing a json element within Django
I am creating a RESTFUL API with Django, and I want to access a json property from the request. How do I do this within Django? Here is my json request object(in postman): { "username": "sam" } I want to access the username value within Django. Here is what I have tried so far: def signupAPI(request): data = json.loads(request.GET) if request.method == "POST": print(data.get("username")) Does anybody know how to accomplish this functionality? Thank you. -
Fabric2 issue running Django management commands
I'm porting fabric scripts to python 3 and I'm using latest version of fabric. Working with regular bash commands is okay but when I want to do some Django stuff it breaks with error below: from fabric.tasks import task python = '/data/worker/ve/bin/python' hosts = ['worker@ip-adress'] @task(hosts=hosts) def do_that(c): with c.prefix('source /data/worker/ve/bin/activate'): with c.cd('/home/worker/ve/app'): # c.run(f"{python} manage.py showmigrations") this breaks c.run('python -V') works c.run('ls -la') works c.run('which python') works Error: Traceback (most recent call last): File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line File "/data/worker/ve/lib/python2.7/site-packages/django/core/management/__init__.py", line 10, in <module> from django.apps import apps File "/data/worker/ve/lib/python2.7/site-packages/django/apps/__init__.py", line 1, in <module> from .config import AppConfig File "/data/worker/ve/lib/python2.7/site-packages/django/apps/config.py", line 5, in <module> from django.utils._os import upath File "/data/worker/ve/lib/python2.7/site-packages/django/utils/_os.py", line 5, in <module> import tempfile File "/opt/rh/python27/root/usr/lib64/python2.7/tempfile.py", line 32, in <module> import io as _io File "/opt/rh/python27/root/usr/lib64/python2.7/io.py", line 51, in <module> import _io ImportError: /data/worker/ve/lib64/python2.7/lib-dynload/_io.so: undefined symbol: _PyErr_ReplaceException -
How to get the id of the object in the view from the context?
I have 2 models: 'Portfolio' and 'Screenshots'. 'Screenshots' has field 'project' - it's foreign key to 'Portfolio'. And I have view 'ProjectDetailView'. I added 'Screenshots' model via get_context_data(). How to get by filter only objects 'Screenshots' model where context['screenshots'] = Screenshot.objects.filter(project=???) # id from Project object My code is below. This my model Portfolio: class Project(BaseModel): slug = models.SlugField(verbose_name='URL', unique=True, blank=False) category = models.ManyToManyField(Category, verbose_name='Category') title = models.CharField(max_length=200, verbose_name='Title', blank=False) publication = models.BooleanField(verbose_name='Publication', default=True) And my model Screenshots: class Screenshot(BaseModel): image = models.ImageField(upload_to='uploads/projects/%Y/%m/', verbose_name='Image', blank=False) project = models.ForeignKey(Project, on_delete=models.CASCADE) This is view.py: class ProjectDetailView(DetailView): model = Project template_name = 'portfolio/project_detail.html' context_object_name = 'project' queryset = Project.objects.filter(publication=True) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['screenshots'] = Screenshot.objects.filter(project=???) # id from Project object return context -
(530, '5.7.0 Must issue a STARTTLS command first. 135sm7372342lfb.28 - gsmtp',u'mail id)
I am trying to send mail using django, getting this error, (530, '5.7.0 Must issue a STARTTLS command first. 135sm7372342lfb.28 - gsmtp',u'mail id)****** Please help. TIA