Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Button that will change a field in a model
I am building a scrum application where there are Sprint and User Story objects. I want the user to be able to click a button on the Sprint detail template and for a BooleanField in the model to be changed from False to True, marking the Sprint as complete. I have tried to think but not sure how I can about this? Here is my models.py: from django.db import models from django.contrib.auth.models import User, Group class Sprint(models.Model): LENGTH_CHOICES = (('1_week', '1 Week'), ('2_weeks', '2 Weeks'), ('3_weeks', '3 Weeks')) name = models.CharField(max_length=200) created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name="sprints", null=True) project = models.ForeignKey(Group, on_delete=models.CASCADE, related_name="sprints", null=True) start_date = models.DateField(auto_now = False, auto_now_add = False) end_date = models.DateField(auto_now = False, auto_now_add = False) duration = models.CharField(max_length = 10, choices = LENGTH_CHOICES) complete = models.BooleanField(null = True, default = False) retrospective = models.CharField(max_length=10000, null=True) def __str__(self): return self.name class UserStory(models.Model): STATUS_CHOICES = (('To Do', 'To Do'),('In Progress', 'In Progress'), ('In Review', 'In Review'), ('Complete', 'Complete')) STORY_POINTS = ((0, 0), (1, 1), (2, 2), (3, 3), (5, 5), (8, 8), (13, 13), (20, 20), (40, 40), (100, 100)) name = models.CharField(max_length=300) sprint = models.ForeignKey(Sprint, on_delete=models.CASCADE, related_name="userstories", null=True) description = models.CharField(max_length=300) status = models.CharField(max_length = 11, choices … -
Backend subscribe system
Hello my dear great programmers. I am new to this case, and I have one question. I wrote an online registration system for the course, and came out a few problems. like thisPlease help a beginner programmer. I have created a multi-page html website, and it has sections like my courses, available courses, available courses page has different courses, and there is a subscribe button, I want when I click on subscribe button, it will show up on my courses website. Can you please help me to solve this problem -
How do I make each individual a user from a model?
This is probably simple but for me it has proved to be a headache. I'd like to make each teacher from TeacherData model to be a user using the first_name as the username and email as the password. Here are my models. School model class School(models.Model): name = models.CharField(max_length=100,null=True,blank=True) User model class User(AbstractUser): school = models.ForeignKey(School, on_delete=models.DO_NOTHING, null=True, blank=True) is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) Teacher's model class TeacherData(models.Model): school = models.ForeignKey(School,on_delete=models.CASCADE) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) email = models.EmailField() If there's anything else required let me know and I'll add it. -
Setting fieldsets with non-model fields with Django ModelForm
I have a modelForm and modelAdmin that both inherit the same Django models. I want to add a field to the form that will not occupy a field in the model, but will be used elsewhere. That's all and well, I can simply add a new field to the form. However, my fieldsets for the modelAdmin class that I use for the add/change views do not accept any entry that is not a model field. How should I work around this? -
Italic on first 2 words of datatable table
I'm making an academic bibliography table on my django website.On the second collumn of my datatable the first two words need to be on itallic! How can i go about this? -
Unable to render images in caraousel from database in django?
I am trying to render images from my database to carousel in Django. I have a model which contains url fields to store images url but when I use them in (template.html) my carousel img src, it only renders 1st image but not others even though I have three images url stored in database. To understand it better here is my code. models.py from django.db import models # Create your models here. class CaraouselData(models.Model): title = models.CharField(max_length=100, null=False) description = models.TextField(max_length=200, null=True) image = models.URLField(null = False, default=True) def __str__(self): return self.title views.py def home(request): caraousel_data = CaraouselData.objects.all() return render(request, 'index.html', context={ 'caraousel_data': caraousel_data, }) template.js {% block content %} {# Caraousel Data Section#} <div class="container-fluid p-0"> <div id="carouselExampleCaptions" class="carousel slide" data-bs-ride="carousel"> <div class="carousel-indicators"> <button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button> <button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="1" aria-label="Slide 2"></button> <button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="2" aria-label="Slide 3"></button> </div> {# images fetching from models #} <div class="carousel-inner"> {% for item in caraousel_data %} <div class="carousel-item {% if forloop.counter0 == 0 %} active" {% endif %}> <img src="{{ item.image }}" width="600" height="670" class="d-block w-100" alt="..."> <div class="carousel-caption d-none d-md-block"> <h5>{{ item.title }}</h5> <p>{{ item.description }}</p> </div> </div> {% endfor %} {% endblock %} -
Django add product quantity through <input type="number">
I am trying to build an e-commerce website and learn more about Django. I am experiencing problem understanding how to add product quantity through and when you press add to cart button to send this amount to the cart. Could you please explain it to me? Here is the code that I have: SHOP API ADD TO CART def api_add_to_cart(request): data = json.loads(request.body) jsonresponse = {'success': True} product_id = data['product_id'] update = data['update'] quantity = data['quantity'] cart = Cart(request) product = get_object_or_404(Product, pk=product_id) if not update: cart.add(product=product, quantity=1, update_quantity=False) else: cart.add(product=product, quantity=quantity, update_quantity=True) return JsonResponse(jsonresponse) SHOP PAGE VUE.JS INLINE SCRIPT <script> var productapp = new Vue({ el:'#productapp', delimiters:['[[', ']]'], store: store, data() { return { } }, mounted() { console.log('Mounted'); }, methods: { addToCart(product_id) { console.log('Product_id:', product_id); var data = { 'product_id': product_id, 'update': false, 'quantity': 1 }; fetch('/api/add_to_cart/', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': '{{ csrf_token }}' }, credentials: 'same-origin', body: JSON.stringify(data), }) .then((response) => { console.log(response) store.commit('increment', 1) function cartMessage() { document.getElementsByClassName('cart__message').style.display = 'flex'; } cartMessage(); }) .catch(function (error) { console.log('Error 2'); }) } } }) </script> I more or less understand that it has something to do with fetching name of the input and passing … -
Prevent Websocket DoS attack with nginx
I've noticed that someone could easily crash my website using a simple javascript while loop that continuously sends stuff like so: while(true) { websocket.send(JSON.stringify({})); } I'm using nginx which passes ws-requests to daphne which in turn talks to django-channels. This is the relevant configuration part: location /ws/ { proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; limit_conn addr 10; proxy_pass http://daphne; } Is there any easy way to prevent this? An upper limit for the datastream would be super. The websocket connection is used for things that may send several messages within a few (hundred?) milliseconds (WebRTC and game related stuff). -
Django: how to keep track of order for items of a model
I have a model: class Recipe(models.Model): name=models.CharField() class Ingredients(models.Model): name=models.CharField() class RecipeIngredients(models.Model): recipe=models.ForeignField(Recipe) ingredients = models.ForeignField(Ingredients) I am creating RecipeIngredients, but i want to show them in a sequence Sometime i have to add an ingredient inbetween. So in such cases how to keep the order while getting them -
Django - Manually Deleting an App from the Database
So I'm working on a Django project, in which I've done some significant refactoring to data models. I'm currently working on a local developer build, and by far the easiest way to migrate these changes has been to delete and re-make the database. I obviously can't do that to the production database, but the original models have already been migrated there. Since I can't delete the ENTIRE database, I want to go in and manually delete all the tables and migrations related to this module then run a new initial migration. This module isn't in use yet on production, and even if it were the data is synced from another service so it's recoverable. I've dug into the way Django does migrations a bit, so I know there's some tables Django uses that aren't directly related to my models. My question is do I need to change anything to make this work besides deleting the model tables (i.e. appname_modelname) and clearing the relevant row(s) from the django_migrations table? I know it's kind of a janky way to do what I want, but actually getting the migrations to run for my refactoring would be a huge hassle and this workaround should … -
KeyError: 'torch', memory error ERROR: ServiceError - Failed to deploy application.: AWS elastic beanstalk, django
I am trying to deploy my django app on AWS elastic beanstalk but I am facing the following error. 2021-04-20 18:00:43 INFO Environment update is starting. 2021-04-20 18:00:46 INFO Deploying new version to instance(s). 2021-04-20 18:00:57 ERROR Instance deployment failed to install application dependencies. The deployment failed. 2021-04-20 18:00:57 ERROR Instance deployment failed. For details, see 'eb-engine.log'. 2021-04-20 18:01:01 ERROR [Instance: i-0eee746bc342a71cd] Command failed on instance. Return code: 1 Output: Engine execution has encountered an error.. 2021-04-20 18:01:01 INFO Command execution completed on all instances. Summary: [Successful: 0, Failed: 1]. 2021-04-20 18:01:01 ERROR Unsuccessful command execution on instance id(s) 'i-0eee746bc342a71cd'. Aborting the operation. 2021-04-20 18:01:01 ERROR Failed to deploy application. My eb-engine.log Downloading https://download.pytorch.org/whl/cpu/torchvision-0.6.1%2Bcpu-cp37-cp37m-linux_x86_64.whl (5.7 MB) Collecting torch==1.8.1+cpu 2021/04/20 18:00:57.931655 [ERROR] An error occurred during execution of command [app-deploy] - [InstallDependency]. Stop running the command. Error: fail to install dependencies with requirements.txt file with error Command /bin/sh -c /var/app/venv/staging-LQM1lest/bin/pip install -r requirements.txt failed with error exit status 2. Stderr:ERROR: Exception: Traceback (most recent call last): File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_vendor/resolvelib/resolvers.py", line 171, in _merge_into_criterion crit = self.state.criteria[name] KeyError: 'torch' . . . . File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_vendor/msgpack/fallback.py", line 671, in _unpack ret[key] = self._unpack(EX_CONSTRUCT) File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_vendor/msgpack/fallback.py", line 684, in _unpack return bytes(obj) MemoryError My requirements.txt … -
Django's Model ContentType id is different between two databases
Basically I am running into a problem with Django's ContentType table behaviour My project and tests run just fine locally, but they don't work in production because it seems a model's contenttype ID is different between the two. My local looks as follow: ContentType.objects.get(app_label='app', model='ticket').id // (prints 347) Prod: ContentType.objects.get(app_label='app', model='ticket').id // (prints 348) and my fixtures look like this [ { "model": "app.attachment", "pk": "dc81fd8d-1729", "fields": { "content_type": 347, "object_id": "04d0d75d-b249e3f", } }, ] so obviously when during my test I happen to do this: // self.ticket_content_type_id = ContentType.objects.get(app_label='app', model='ticket').id self.attachments = Attachment.objects.all() attachment = self.attachments.filter(content_type=self.ticket_content_type_id).first() // returns None Any idea why that offset? What should I do to fix it? What may have caused this in the first place? Thank you in advance! -
Django model form applying user viewing data as the user from form
I have a model form which adds fields (email, latitude etc) and then my views.py attaches the user to the form before it saves. However, when I look at the data in the admin panel, it just assigns my username to all of the entries. If I log in as a different user, I get the same form entries but all with the new username attached. Views.py form = SafezoneForm() if request.method == 'POST': form = SafezoneForm(request.POST) if form.is_valid(): instance = form.save(commit=False) Safezone.userid = request.user #### gets username here and assigns to model instance.save() return redirect('loadingsafezone') context = {'form':form} return render(request, 'V2maparonno_create_safe_zoneV2.html', context) models.py class Safezone(models.Model): userid = models.ForeignKey(User, on_delete=models.CASCADE, null=True) useremail = models.EmailField(max_length=100) name = models.CharField(max_length=100, null=True) latitudecentre = models.FloatField(null=True) longitudecentre = models.FloatField(null=True) latcorner1 = models.FloatField(null=True) latcorner2 = models.FloatField(null=True) latcorner3 = models.FloatField(null=True) latcorner4 = models.FloatField(null=True) longcorner1 = models.FloatField(null=True) longcorner2 = models.FloatField(null=True) longcorner3 = models.FloatField(null=True) longcorner4 = models.FloatField(null=True) def save(self, *args, **kwargs): self.longcorner1 = self.longitudecentre - 0.6 self.longcorner2 = self.longitudecentre + 0.6 self.longcorner3 = self.longitudecentre + 0.6 self.longcorner4 = self.longitudecentre - 0.6 self.latcorner1 = self.latitudecentre - 0.6 self.latcorner2 = self.latitudecentre - 0.6 self.latcorner3 = self.latitudecentre + 0.6 self.latcorner4 = self.latitudecentre + 0.6 super(Safezone, self).save(*args, **kwargs) def __str__(self): return self.userid or … -
Speed up offset pagination on complex calculations in database
I am using pagination with Graphql when creating a facebook-like feed with React Native. I am using Django as Backend. I am using the approach where i send offset and limit as parameters to my backend and the response is just the data from that given interval. But what i do not really understand about this type of pagination is that, will i need to run my functions and calculations in the backend on every request or is django caching it? What i mean is, suppose i would like to get all my followers posts, and then sort them by date. After i have done that i would just return an interval of this data to the frontend. But when the frontend ask the backend for a new interval after 20 seconds, it just feels really unnecessary that the backend will be needed to find and sort the posts again. Is there a way where i would be able to cache the sorted list of posts and then return intervals without the need to sort them everytime? -
Change some default words for a specific language code in django
I'm trying to change some words that are poorly translated into Persian. I've searched this issue but I couldn't find any article about it. I've only changed the LANGUAGE_CODE, and I don't want a website for both languages -
Getting "Server Error (500)" on Django Heroku website
I tried following this guide to publish my website using Heroku, and it partly works but not entirely. For some reason, I keep on getting a Server Error (500) on part of my website. Some pages work, including the homepage, but the main page does not. (Everything works on local, but for some reason I think I got a session data corrupted, but it still worked fine.) When I got the error log email, it says: "Internal Server Error: /results/NYC AttributeError at /results/NYC 'NoneType' object has no attribute 'has_header'" I tried doing many things, nothing worked. Here's my settings.py: """ Django settings for finalproject project. Generated by 'django-admin startproject' using Django 3.0.8. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os import environ # https://devcenter.heroku.com/articles/django-app-configuration # https://devcenter.heroku.com/articles/deploying-python import django_heroku # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # For environment variable (for secret key) # https://djangocentral.com/environment-variables-in-django/ env = environ.Env() # reading .env file environ.Env.read_env() # SECURITY WARNING: keep the secret key used in production secret! # PRODUCTION: # https://stackoverflow.com/questions/47949022/git-heroku-how-to-hide-my-secret-key # https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Deployment#getting_your_website_ready_to_publish … -
I am cloning a django project from git but it is showing the following error
[this is the project I need to run][1] [enter image description here][2] I tried running the command python manage.py migrate [1]: https://github.com/anuj-glitch/Disease-Prediction-using-Django-and-machine-learning [2]: https://i.stack.imgur.com/e1Bwl.png -
Sign in with Apple ID in react + django rest framework project
I'm working on the project setup with react + Django rest framework. The error I'm getting now is invalid client. In react, I used 2 packages react-social-login-buttons and react-apple-login button. I used 2 packages to succeed to get code and id_token. Then I sent code and id_token like this: {"code": code_value, "id_token": id_token_value}. But when I call this API, I'm getting the following error. It would be great if anyone could help me. Thanks -
Best practices about serving media efficiently with Nginx + Django in NAS
Having read a bunch of other topics similar to this one, I'm still not sure what would be best. Let's say I have a load balancer with 2 servers which have Nginx + Django, and then a separate database server and 3 storage servers with images and videos. How do I best serve the media files from the 3 storage servers ? What I currently plan to do is keeping my 2 entry points for all the requests. A request for a media file would be authenticated there by Django and then I would use X-accel direct to proxy pass the media request to the storage servers. However, the Nginx docs state this: When NGINX proxies a request, it sends the request to a specified proxied server, fetches the response, and sends it back to the client. Does this mean that the load would be the same for the 2 entry point servers ? This is how I would understand it, which is not very efficient. What I would like to achieve is something like this: Is this possible? I guess the most efficient way performance wise to serve media files would be to remove the app server step, like … -
How to get a count of a value in a ManyToMany field
I have a model called Recipe that is simplified to have a title and category. The category is a ManyToMany field. title = models.CharField(max_length=100) category = models.ManyToManyField(Category, help_text='Select a category') I have another model called Category name = models.CharField(max_length=200, help_text='Enter a baking category') def __str__(self): return self.name There are several categories but for simplicity, let's say we have two: Bread and Cake. How would I query the DB to figure out how many Recipes I have of each category? I've been trying something like this: But that isn't working. I also don't want to explicitly define all the categories I'm looking for since in the future I would add more categories. -
Dango3: problems with onetoone relationship and '...' object has no attribute '...'
I am getting this error, but I don't understand why. I created the Pipeline object and Config object together in the admin view. However, when I go to the list view: 'Pipeline' object has no attribute 'args' I have pretty much the same setup working with other models, so I am not sure why it is not working in this case. It complains that 'Pipeline' has no args model.py: class Pipeline(models.Model): config= models.OneToOneField('Config', on_delete=models.SET_NULL, null=True, parent_link=True) class Config(models.Model): args = models.CharField(max_length=256, null=True, default='-p -q -x -u -l -m -r') pipeline = models.OneToOneField('Pipeline', on_delete=models.CASCADE, null=True, parent_link=False) admin.py: class ConfigInline(admin.StackedInline): model = Config class PipelineAdmin(admin.ModelAdmin): inlines = [ConfigInline] I did the database migrations. -
How to pass arguments when redirecting to another view in Django 3 (Python)
I want to pass variables to my views in django but I get errors... The code is simply attempting to pass text into a view while redirecting. Basically the user will fill out a form, and the content of that form will be displayed on another page. However, if I run the following code, I come across this error: django.urls.exceptions.NoReverseMatch: Reverse for 'view2' with arguments '('hi',)' not found. 1 pattern(s) tried: ['view2$'] views.py from django.shortcuts import render, redirect def index(request): if request.method == 'POST': form = MyForm(request.POST) if form.is_valid(): submit_form(request) else: form = MyForm() return render(request, 'index.html', {'form':form}) def view2(request, text): return render(request, 'page2.html', {'my_text':text}) def submit_form(request): # Just using 'hi' for simplicity return redirect(view2, 'hi') page2.html {% extends "base.html" %} {% block body_block %} {{ my_text }} {% endblock %} urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('view2', views.view2, name='view2'), ] I suspect the error is from me doing something wrong in the views.py, but I have not been able to find anything that will work... I've also tried these two lines in the submit_form function, but got the same error return redirect(view2, pn='hi') return HttpResponseRedirect(reverse('view2', args=('hi', ))) -
django not rendering custom 403 page, displays browser default instead
I am trying to apply a custom 403 template to display instead of the browser default. I have a Middelware that looks something like this: from django.http import HttpResponseForbidden class CheckUserTypeMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if request.user.is_authenticated: allowed_types = ['a', 'b', 'c', 'd', 'e'] user_data = get_some_AD_values if user_data.get('a_key') not in allowed_types: return HttpResponseForbidden() response = self.get_response(request) return response views.py def error_403(request, exception): return render(request, 'my_app/403.html') # I have a 404.html in the same folder as the 403 and that renders fine. urls.py handler403 = 'my_app.views.error_403' settings.py DEBUG = False MIDDLEWARE = [ # Default Django middlewares untouched 'my_app.middleware.my_middleware.CheckUserTypeMiddleware', ] The same process I have above worked for 404 errors, but for some reason, I cant get it to work with 403 errors. -
Hey! actually i want to clear my database (postgres - pgadmin) because it is not working correctly so please help me out to delete the database
Hey actually i want to just delete everything from database and I want to just start the fresh database so please help me out to delete all the database and just start new one in postgres -
Update django page from firebase without page refresh
I wanted to make a django page that reads information from firebase, and print it out to my output.html page without having to reload or refresh the page. The data in firebase will be updated while the output.html loads (after a button click), and it will take a few minutes before rendering and redirect to the next page. I have read online that i will have to use AJAX requests in an interval to get the updated data from firebase and display it in the html page. Are there any other suggestions for me to get this done?