Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Perform action on background django
If a new data is entered in by a user or someone else, what I want my app to do is to get that data from the queue, perform a background action on its own, then remove and/or leave that data alone and move onto the next. I shouldn't be touching anything. I want to set a task, then want django to do its own work without any intervention. In this case, would django-background-tasks be the best job for this? What are some other similar packages that I should be looking at? -
django how to set background colour in html based on context
I am trying to change the background colour in a django project based on some information sent via the context body base { padding:$base-spacing-unit; font-family:'Source Sans Pro', sans-serif; margin:0; ext-align:center; } body alert { background-color: #FCFF33; padding:$base-spacing-unit; font-family:'Source Sans Pro', sans-serif; margin:0; ext-align:center; } def check_alert() -> bool: return ... def index(request): template = 'proj/index.html' ... context['alert'] = check_alert() return render(request, template, context) How can I select the body class in the proj.html based on the field alert in html looks like {% load static %} <html> <link rel="stylesheet" href="{% static 'css/proj.css' %}" /> <body class="base"> <-- I tried manually switching class here, but it appears body doesnt take that. If I do this it doesnt take the base config ... </body> </html> -
Is there a way to plug a seperate instance of Django model objects into different containers without going through a for loop in the template?
I've created a simple Project model with just a title and summary field. I want to put unique instances of this model into different containers because I don't know enough about CSS to make a flexible iterable container. Is there a way to do this in the template outside of declaring unique context variables for each instance of the object? I put a for loop here to show where I would put it. Do I need to make four unique context dictionaries each with its own unique loop? <section class="box features"> <h2 class="major"><span>Project Portfolio</span></h2> <div> <div class="row"> <div class="col-3 col-6-medium col-12-small"> <!-- Feature --> <section class="box feature"> <a href="#" class="image featured"><img src="images/pic01.jpg" alt="" /></a> <h3><a href="#">A Subheading</a></h3> <p> Phasellus quam turpis, feugiat sit amet ornare in, a hendrerit in lectus dolore. Praesent semper mod quis eget sed etiam eu ante risus. </p> </section> </div> <div class="col-3 col-6-medium col-12-small"> <!-- Feature --> <section class="box feature"> <a href="#" class="image featured"><img src="images/pic02.jpg" alt="" /></a> <h3><a href="#">Another Subheading</a></h3> {% for project in projects %} <p>{{ project.summary }}</p> {% endfor %} </section> </div> <div class="col-3 col-6-medium col-12-small"> -
Celery change content_encoding
I want make apply_async task with celery, but my argument is a file with encoding in ISO-8859-1, but celery serializer data with UTF-8. I recive the file from one url using this code: import urllib data = urllib.request.urlopen(url) content = data.read() update_task.apply_async([content]) When I try call the method I have this erro: UnicodeDecodeError: 'utf-8' codec can't decode byte -
Unable to connect to containerized Django web server while running Pycharm remote debugging session
I have a Django application running in a Docker-compose configuration and I would like to be able interactively debug it from Pycharm. I first tried and failed to set up debugging using Pycharm's built-in Docker Compose configuration (result: the application runs and is accessible, but debugging is not available, I suspect because of a known bug where the debugger fails to connect if the entrypoint script takes too long to return). I am now attempting to set up debugging using remote debugging with pydevd, roughly following the instructions contained here and summarized below: Add a Python Remote Debugger run configuration in Pycharm In my Django application, copy pycharm-debug-py3k.egg to the root directory, add it to the path, import pydevd & initialize it in my app code like so: import sys sys.path.append("pycharm-debug-py3k.egg") import pydevd pydevd.settrace('ip.address.of.my.machine', port=4444) Start the debugger in Pycharm Start my application with docker-compose up Press the Play/Resume program button in the debugger The result of this is that in Pycharm, the debugger console reports that a connection is active ("Connected to pydev debugger"). The debugger tab shows the expected variables and values present in the file I added the code snippet to. No errors appear in the container … -
Django: Subclassing UserCreationForm: doesn't have get_user() method?
I created a custom user in Django by subclassing the normal User model. This user's only difference is that it doesn't have a username. Now, I'm trying to use the built in Django UserCreationForms to log users in. I subclassed UserCreationForm and created SignUpForm, which doesn't have a username field. My control flow is as follows: 1) Check to see if input form is valid 2) if it is, get the user out of the form 3) save the form (thereby saving the user) 4) log the user in However, when I try to get a user out of the SignUpForm instance, it throws me this error: AttributeError at /user/signup 'SignUpForm' object has no attribute 'get_user' I don't understand this because SignUpForm is directly subclassed from UserCreationForm, which implements the get_user() method. My code for views.py is below: from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import authenticate, login from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth import get_user_model from django.db import models User = get_user_model() # Create your views here. class SignUpForm(UserCreationForm): email = models.EmailField(max_length=254, help_text='Required. Enter a valid email address.') username = None class Meta: model = User fields = ('email', 'password1', 'password2',) def signup(request): if … -
JavaScript showChange() to dynamically change value in django template seems to have no effect. What am I doing wrong?
I have a Django template where I am displaying products from a database along with a dropdown menu containing various conditions for the product. I have a static price for the item, that I would like to change based on the condition currently selected without loading the page. The dropdown menu was generated via django forms. I expect that when I choose the condition from the menu, the price would change to the value of whichever option I choose, but nothing is happening. What am I doing wrong? Django generated form <select name="condition" id="id_condition"> <option value="NM / LP">Near Mint / Lightly Played</option> <option value="MP">Moderately Played</option> <option value="HP">Heavily Played</option> <option value="Damaged">Damaged</option> <option value="Unopened">Unopened</option> Script at the bottom of my template <script> function showChange(){ var selected_material = document.getElementById("id_condition").value; document.getElementById("price_id").innerText = selected_material; } </script> template {% for product, card_price in products %} <div style="margin-bottom: 3%;" class="col-sm-3"> <div class=col-sm-12> <form action="{% url 'add_to_cart' product.id %}" method="post" target="submit-frame">{% csrf_token %} <div style="" class="row" id=""> <img class="img-responsive center-block" src="https://someImage.jpg"> </div> <div style="" class="row" id=""> <center> {{form|crispy}} <input id='card_price' type="hidden" name="card_price" min={{card_price}} max={{card_price}} value={{card_price}}> <div class="col-sm-3"></div> <div class="col-sm-2"> <b style="">&nbsp;$<span id="price_id">{{card_price|floatformat:2}}</span></b> </div> <div class="col-sm-2"> <input style="color: black;" size="2" id='qtyBox' type="number" name="quantity" min="1" max="8"> </div> <div class="col-sm-1"> <button … -
Django: using enums for multiple language tables and choices
How can I use Enums in Django to quickly create list of choices for enable more choices than pair tuples, e.g. 4 or 5 columns a quick method to convert enums to tuples for enable multiple languages in a drop down from enums, choice list is recycled for other parts of the project when tables are needede -
How do I have a Boolean True False form in Django for a list of models?
Whats the best way to have a boolean HTML form for a list of models? Lets say this is my model: class Comparison(model): id = models.AutoField(primary_key=True) score = models.IntegerField(blank=True, null=True) is_matching = models.NullBooleanField() And my view: def display(request): comparisons = Comparison.objects.all() context = { 'comparisons': comparisons } return render(request, 'display_comparisons.html', context) And my template: <table> {% for comparison in comparisons %} <tr> <td> Here is some True / False button that should update is_matching </td> </tr> {% endfor %} </table> Now ideally, if I click the True button or the False button, my comparison model will update. Whats the best way to do this? -
How limit choices in a ManyToMany field depending on wich user is logged?
I'd like the view only show the "personajes" that were created by the current user. If I i'm not understanding wrong, what I have to do is filter the choices, depending who is the current user logged in, before the form render. I guess that what I have to edit is the queryset argument in ModelChoiceField(**kwargs) but I don't know where I have to do this. models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Autor(models.Model): nombre = models.CharField(max_length=40) apellido = models.CharField(max_length=40) usuario = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True) def __str__(self): return "%s %s" % (self.nombre, self.apellido) class Personaje(models.Model): nombre = models.CharField(max_length=40) personalidad = models.CharField(max_length=20) creador = models.ForeignKey(Autor, on_delete=models.CASCADE) def __str__(self): return "nombre: %s Creador: %s" % (self.nombre, self.creador) class Historia(models.Model): autor = models.ForeignKey(Autor, on_delete=models.CASCADE) personajes = models.ManyToManyField(Personaje) desarrollo = models.TextField() views.py I'm not catching the request.user.id yet by simplicity (I'm really stuck with the filter thing) I know how to do that, hardcoding the user id will be just fine. from django.shortcuts import render from django.views.generic import CreateView from core.models import Historia # Create your views here. class CrearHistoria(CreateView): model = Historia fields = ['personajes', 'desarrollo'] template_name = 'core/crear_historia.html' The current result: What I … -
Crispy forms and bootstrap styles
I am trying to use UserCreationForm in django in users model for registration, my forms.py : from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] and my users/views.py is : from django.shortcuts import render, redirect from django.contrib import messages from .forms import UserRegisterForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}!') return redirect('blog-home') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) and my html is : {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Join Today</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Sign Up</button> </div> </form> {% endblock content %} i added crispy in settings.py installed app and i CRISPY_TEMPLATE_PACK = 'bootstrap4' and I added the latest bootstrap 4.2 CDN in my styelsheet but my page still looks awful , any guide please and thanks in advance -
Filtering Dates :TypeError at / expected string or bytes-like object
I'm trying to make a filter based on dates for scheduled events. I want items that happened between 60 days ago and that are scheduled 60 days from now. So the start of the range is today - 60 days and the end of the range is today + 60 days. I haven't used Django in a long time and I don't know if this is a new issue with the current version and the auto_now and auto_add_now or if the issue is using DateField. I used DateField on the models because I don't care about the time and don't want this time fields added to the database. I want clean dates. Index.html <!DOCTYPE html> {% load static %} <title>Document</title> <body> <div id=form> <select name="Title" id="title_box"> {% for item in items %} <option value="{{item.name}}">{{item.name}}</option> {% endfor %} </select> </div> </body> </html> Models.py from __future__ import unicode_literals from django.db import migrations, models import datetime class Cycle(models.Model): name= models.CharField(max_length=255) start_date = models.DateField(auto_now=False, auto_now_add=False, blank=True, null=True) end_date = models.DateField(auto_now=False, auto_now_add=False, blank=True, null=True) I changed the field from DateField to DateTimeField and it made no difference, so I changed it back to DateField. Views.py from django.shortcuts import render, HttpResponse, redirect from .models import * … -
Python django html
I am with a doubt create the product class that has name, price, bar_code and the class of Sale that has product and price. In other words, by adding a new sale, she will select a product. How do I get the value of the selected product and add to the sale price? -
Cleaning date field returned to django view from ajax call
I have a date field that comes across in the data field of an ajax call. I can get the data just fine in my views.py dateJ = request.GET.get('date_joined_group') This is great, but when I try to throw it into my model it dies everytime. I need to 'clean' the data, I know my forms when I am just doing standard get post ops works and does this automagically. Is there a way I can invoke this automagic when not using form stuff but using the ajax call? I tried this: dateObj = datetime.datetime.strptime(str(dateJ), '%m-%d-%Y') Then in my model: grpProvInfo.date_joined_group = dateObj grpProvInfo.save() This worked, till I used the date picker on the form which put it in as 4/29/2009 So the slashes broke my 'slick fix', gotta be an easier way then trying to account for all the possibilities just not sure how to invoke it from a little def method I have for the ajax call in my python. -
Django models retrieve specific records daily
I have a django application that will retrieve and display 3 records (questions) to all users of the app during a 24hr window beginning at a specific time, say 11:00 daily. Preferably, I would like to randomise the list of records or just use the question id which autoincrements. There are more than 14,000 records. I can retrieve records from the db and randomly display those records. However, every http get request (refreshing browser window) retrieves different questions Models.py from django.db import models from django.contrib.auth.models import User from django.conf import settings class Questions(models.Model): question = models.CharField(max_length=254, blank=True, null=True) answer = models.CharField(max_length=254, blank=True, null=True) question_used = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now_add=True) Views.py from django.shortcuts import render from django.views.generic import CreateView, View from .models import * from wallet.models import UserWallet class DailyDrawView(View): template_name = 'daily_draw/daily_draw.html' def get(self, request, *args, **kwargs): que_attempt = DailyDraw.objects.filter(user=request.user, is_active=True).last() question_objs = Questions.objects.all().order_by('?')[:3] points = WinnerPoint.objects.last().amount return render(request, self.template_name {'question_objs':question_objs, 'que_attempt':que_attempt, 'points':points }) At a particular time daily, retrieve 3 records. Display those records to all users throughout a 24hrs period. Update those 3 rows so that those same records are not displayed again. Rinse and repeat. -
Do I need a manager when creating and saving objects in Django?
I'm using Django with Python 3.7 and PyCharm. I'm following this tutorial for learning how to create model and save them into the database -- https://docs.djangoproject.com/en/dev/topics/db/queries/#creating-objects . The tutorial refers to manager for retrieving objects, but not for setting them, so I'm confused as to why I get the below error Article.objects.create_article(main page, '/path', 'url', 10, 22) Traceback (most recent call last): File "<input>", line 1, in <module> AttributeError: 'Manager' object has no attribute 'create_article' when I'm trying to create and save an object. Below is how I define my object in my models.py file ... class Article(models.Model): mainpage = models.ForeignKey(MainPage, on_delete=models.CASCADE,) path = models.CharField(max_length=100) url = models.TextField time = models.DateTimeField(default=datetime.now) votes = models.IntegerField(default=0) comments = models.IntegerField(default=0) def __str__(self): return self.path @classmethod def create(cls, mainpage, path, url, votes, comments): article = cls(mainpage=mainpage,path=path,url=url,votes=votes,comments=comments) return article I'm sure I'm missing something really obvious, but I don't know what it is. -
I am confused about what the CheckingAccounts class returning inside my Customer class in the following code
Here is my base Class Accounts, class Accounts: def init(self,account_no,total_balance): self.account_no = account_no self.total_balance = total_balance def __str__(self): return '{:.2f}'.format(self.total_balance) def deposit(self,deposit): self.total_balance = self.total_balance + deposit return self.total_balance def withdrawl(self, withdrawl): if self.total_balance >= withdrawl: self.total_balance = self.total_balance - withdrawl else: return ("Funds Unavaliable") CheckingAccounts class is inheriting base class Accounts class CheckingAccount(Accounts): def init(self, account_no,total_balance): super().init(account_no,total_balance) def str(self): return "The account number is:\n#{0} \nThe balance is:\n{1}".format(self.account_no, Accounts.str(self)) Now a customer class, and this is where I am having confusing about the open_checking function which is using CheckingAccount class and I do not understand whats it will return and store in the accounts list. class Customer: def init(self, name, PIN): self.name = name self.PIN = PIN # Create a dictionary of accounts, with lists to hold multiple accounts self.accts = {'C':[],'S':[],'B':[]} def __str__(self): return self.name def open_checking(self,acct_nbr,opening_deposit): self.accts['C'].append(Checking(acct_nbr,opening_deposit)) -
Django count integer up_vote/down_vote's won't work
i want to increase/decrease the integer vaule of my category_request model-fields up_vote/down_down but for some reason i always get to the else block. views.py from django.db.models import F ... def category_request_up_vote (request, pk): category_request = get_object_or_404(CategoryRequests, pk=pk) if request.method == 'POST': category_request.up_vote = F('up_vote') + 1 category_request.save() messages.success(request, 'You have successfully Provided an Up-Vote for this Request') return redirect('category_request_detail', pk=category_request.pk) else: messages.error(request, 'Uuups, something went wrong, please try again.') return redirect('category_request_detail', pk=category_request.pk) def category_request_down_vote(request, pk): category_request = get_object_or_404(CategoryRequests, pk=pk) if request.method == 'POST': category_request.down_vote = F('down_vote') - 1 category_request.save() messages.success(request, 'You have successfully Provided an Down-Vote for this Request') return redirect('category_request_detail', pk=category_request.pk) else: messages.error(request, 'Uuups, something went wrong, please try again.') return redirect('category_request_detail', pk=category_request.pk) Thanks in advance -
Django JSONField dynamic contains and key lookups
I need to filter objects by key-value pair contained in JSONField with list of dicts where key and value are model fields. This question is related to Django JSONField list of dicts "contains" filter inside Subquery This one works perfectly: EntityObject.objects.filter( data__list_of_dicts__contains=[{'static_key': 'static_value'}] ) But with dynamic values: EntityObject.objects.filter( data__list_of_dicts__contains=[{F('field1'): F('field2')}] ) It causes an error: TypeError: keys must be a string And with static key and dynamic value: EntityObject.objects.filter( data__list_of_dicts__contains=[{'static_key': F('field2')}] ) Another error: TypeError: F(field2) is not JSON serializable -
How does Django deployments happen on Servers?
I'm sorry if it's offtopic but I didn't find any other better to place to ask. I started learning Django six months ago and I really really loved it. I learnt how to deploy the django projects to EC2 instances. Basically 1st time when the django project is deployed to EC2, the instance will be configured with httpd.conf, wsgi, change permissions on files and folders and other stuff and the project will be cloned to the EC2 instance and server is restarted. My question is how do they do future deployments? They in this context is anyone who deploys Django on EC2 instances. Do they login to EC2 instances and manually clone the repository from VCS site and restart the server? Do they have any other automated mechanism to pull the code, ensure permissions and restarting the apache server etc. How is it done basically every time they go for a release? Someone please help me understand this. -
Django model not finding a field, keeps saying NoneType yet database shows it
I have a django model: @python_2_unicode_compatible class GroupProviderInformation(models.Model): group = models.ForeignKey('Group', null=True, blank=True, on_delete=models.PROTECT) provider = models.ForeignKey('Provider', null=True, blank=True, on_delete=models.PROTECT) specialty = models.ForeignKey('Specialty', on_delete=models.SET_NULL, null=True, blank=True) provider_contact = models.CharField(max_length = 50, blank=True, null=True) credentialing_contact = models.CharField(max_length = 50, blank=True, null=True) hospital_affiliation = models.CharField(max_length = 50, null=True, blank=True) date_joined_group = models.DateField(auto_now=False, auto_now_add=False, null=True, blank=True) #models.DateField(auto_now_add=True) def __str__(self): return "SP PK: " + str(self.specialty.pk) + " GRP: " + str(self.group.pk) + " PROV: " + str(self.provider.pk) I import data into this model, and then do a query from a view: group = Group.objects.get(pk=gid) provider = Provider.objects.get(pk=pid) grpProvInfo = GroupProviderInformation(group=group, provider=provider) (the id's are 136 and 24). I look in my database the table is there, the record is there all the way across even has specialty_id as containing 16 looks good. Yet if i try to print print(grpProvInfo) the return "SP PK: " + str(self.specialty.pk) + " GRP: " + str(self.group.pk) + " PROV: " + str(self.provider.pk) Throws an error 'NoneType' object has no attribute 'pk', it means the self.specialty yet I know it exsists. Does this in my view when I try to use the object and get the data grpProvInfo.specialty.whateverfield I am perplexed as to why this isn't taking, it … -
Django - add a Integerfield in the template to every m2m object
I'm trying to add functionality to add a IntegerField next to every 'stockItem' in the template so that the user can type how many of that item was needed and then update the 'count' value in the 'Stock' model. As for now it only works when the user only selects one item. (I know that how I implement this now would never work but I try to show how I intend it to work) Models: class Machine_Service(models.Model): title = models.CharField(max_length = 100) stockItem = models.ManyToManyField(Stock) date = models.DateTimeField(default=timezone.now) comment = models.TextField() machine = models.ForeignKey(Machine, on_delete=models.CASCADE) def __str__(self): return self.title class Stock(models.Model): title = models.CharField(max_length=100) count = models.IntegerField(default=10) minLimit = models.IntegerField(default=1) resellerCompany = models.CharField(max_length=100) resellerPerson = models.CharField(max_length=100) resellerEmail = models.EmailField() def __str__(self): return self.title (I left the 'Machine' model out of this because it does not belong to the question) view: def CreateService(request): if request.method == 'POST': form = CreateServiceForm(request.POST) if form.is_valid(): m = Machine.objects.get(id=form['machine'].value()) service = Machine_Service(title=form['title'].value(), date=form['date'].value(), comment=form['comment'].value(), machine=m) service.save() items = form['stockItem'].value() for item in items: s = Stock.objects.get(id=item) service.stockItem.add(s) service.save() return redirect('Machines-Home') else: form = CreateServiceForm() context = { 'form': form } form: class CreateServiceForm(forms.ModelForm): count = forms.IntegerField(required=False) class Meta: model = Machine_Service fields = ['title', 'stockItem', … -
Django vs Django Rest Framework (DRF) and a Front-end Framework - What is the development time difference?
We are getting started on a project and it is up for debate whether Django should be used on it's own with the django templates and some React/Vue javascript added in for fancy things. OR We should use the django rest framework and use React/Vue for all of the front-end work. How much more work is the second option in comparison to the 1st? If option 1 is chosen, we will likely transition into option 2. How much work will that be? Any insights or comments would be much appreciated. -
Create a django password in a simple python script
I need to generate an encrypted password that can be used within Django in a simple python script. What package/module would I need to import to achieve that? I am looking for something like: from django.auth import create_password_from_string django_password = create_password_from_string('coolpassword') The background is, that I have a PHP application on server1 which should share the accounts with a Django application on server2. When an account is created in the PHP application, I want to fire up a python script that generates the encrypted password for the django application and transfers it to server2. -
Optimizing a large Django project by moving certain process to dedicated machine (microservice?)
I'm working on a large Django project that uses application server(s) to process Latex. As our site grows, the Latex processing is affecting performance when site traffic is high. One idea I had was to move the Latex processing to a separate EC2 instance optimized for: processing Latex using TexLiv, creating a PNG, saving PNG to S3, and then returning a URL for the image. I also need to communicate with my existing Django ORM to update the object's image URL with the one just created on the dedicated machine. I have several questions: 1) what kind of EC2 instance should I use (computer or memory optimized?) 2) what kind of web server should I use on this dedicated Latex processing machine (is this a microservice?) Django, Tornado, Flask? 3) How do I get my existing project to communicate with new, dedicated Latex processing machine. 4) anything else I might be missing Thanks