Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Broken migrations with Django sites framework to restrict URLs access
I want to share single code-base Django (2.2) over 2 URLs : foo.domain.ltd & bar.domain.ltd. on foo.domain.ltd: all the Django URLs are available on bar.domain.ltd: only some URLs are available, all other return 403 error I expected using the sites framework (django.contrib.sites) to reach this goal : 1 code base 2 domains configured in the sites framework 2 gunicorn instances with appropriate configuration : core.settings.foo with SITE_ID = 1 core.settings.bar with SITE_ID = 2 1 nginx server listening clients and forwarding requests to the appropriate gunicorn instance depending the xxx.domain.ltd used The issue I encountered is that sites framework looks like model oriented : You can associate models to one, two (…) sites. I try to set urls depending on the sites, but I broke the ./manage migrate tool… 1) Settings the sites framework to my project and a dualsite app to host associated code : core.settings : INSTALLED_APPS = [ # (…) "django.contrib.sites", "dualsite.apps.DualsiteConfig", ] core.settings.foo : from core.settings import * SITE_ID = 1 core.settings.bar : from core.settings import * SITE_ID = 2 dualsite.migration.0001_set_sites : from django.db import migrations def my_sites(apps, schema_editor): Site = apps.get_model("sites", "Site") initial_site = Site.objects.get(id=1) initial_site.domain = "foo.domain.ltd" initial_site.name = "foo" initial_site.save() Site.objects.create(domain="bar.domain.ltd", name="bar") class … -
Loop in template without context variables
Is possible to use a loop using just numbers and not context variables in the template something like: {% for (int i = 22; i < 65; ++i) %} <input id="name_{{i}}" type="number" value="{{i}}"> {% endfor %} If is possible to do how can I do it? thanks in advance. -
Django I'm trying to get the latest added/edited element to the top of the page. It works with editing but not when I add new element
I am getting highest integer value of model integer field and then adding +1 to it and saving it as a form. When I am adding new element I use ModelForms like that: view.py class IndexView(TemplateView): template_name = 'titracker/index.html' def get(self, request): form = addTicketForm() return render(request, self.template_name, {'form':form, 'tickets_to_load':Ticket.objects.all().order_by('-ticket_position')}) def post(self, request): form = addTicketForm(request.POST) if form.is_valid(): from django.db.models import Max result = Ticket.objects.all().aggregate(Max('ticket_position')) my_list = [] for key,value in result.items(): my_list.append(value) max_pos = my_list[0] form.ticket_position = max_pos + 1 form.save() form = addTicketForm() return HttpResponseRedirect(reverse('titracker:index')) else: return render(request, self.template_name, {'form':form, 'tickets_to_load':Ticket.objects.order_by('-ticket_position')}) And it doesn't work, but when I don't use ModelForms it does work html template <div class='container'> <form class="form-horizontal" role="form" method="post" enctype="multipart/form-data"> {% csrf_token %} <input class="u-full-width" type="text" name="t_title" value="{{ticket.ticket_title}}"/> <textarea class="form-control" rows="3" name='t_body'> {{ticket.ticket_body}}</textarea> <button type="submit" value='post' class="btn btn-info">Submit</button> <button type="submit" value='post' name='delete' class="btn btn-info">Delete</button> <select id='status' value='post' name='status'> {% if ticket.ticket_status == 0 %} <option>Open</option> <option value='1'>In progress</option> <option value='2'>Closed</option> </select> {% elif ticket.ticket_status == 1 %} <option>In progress</option> <option value='0'>Open</option> <option value='2'>Closed</option> </select> {% elif ticket.ticket_status == 2 %} <option>Closed</option> <option value='0'>Open</option> <option value='1'>In progress</option> </select> {% endif %} </form></div> </div></center> </body> </html> view def editer(request, ticket_id): tick = get_object_or_404(Ticket, pk=ticket_id) if request.method == … -
Celery - raise socket.error(last_err) OSError: [Errno 61] Connection refused
This is my project structure myproj │ ├── app1 ├── __init__.py ├── tasks.py gettingstarted ├── __init__.py ├── urls.py ├── settings.py │ ├── manage.py |-- Procfile In gettingstarted/settings: BROKER_URL = 'redis://' In Procfile: web: gunicorn gettingstarted.wsgi --log-file - worker: celery worker --app=hello.tasks.app In hello/tasks.py from __future__ import absolute_import, unicode_literals import random import celery import os app = celery.Celery('hello') @app.task def add(x, y): return x + y Please help....I've been trying to solve this for 24 hours straight now..... -
How to filter by an aggregation of the last N records of a related model
My goal is to develop a query using the Django ORM that will return all users in the system for which less than half of their last 50 posts have been liked. I've developed a query which gives me all of the users which have less than half of ALL of their posts liked, but I can't figure out how to limit the scope of the posts I'm looking to only the last 50 posts by that user. I'd prefer to keep the operation in a single query for performance reasons if at all possible. Dumbed Down versions of my models class User(models.Model): pass class Post(models.Model): author = models.ForeignKey( "user.User", related_name="posts", on_delete=models.CASCADE ) My Existing Query unpopular_users = User.objects.annotate( posts_created=Cast( Count('posts'), output_field=FloatField() ), posts_liked=Cast( Count(Case(When(posts__likes__gt=0, then=1))), output_field=FloatField() ) ).exclude(posts_created=0).annotate( liked_rate=F("posts_liked") / F("posts_created") ).filter(liked_rate__lt=Decimal('0.5')) -
Can not delete superuser in django and a resulting error django.db.utils.OperationalError: no such column: infrastructure_profile.slug
I wanted to add a slug field to my model Profile after I had several profiles created, then an error appeared when reaching the profile page with the slug in the url saying : Django OperationalError: no such column: infrastructure_profile.slug so I looked here and saw this answer and it suggested I delete all my migrations files to restart the database , so I did and then I got the same error , so I thought I should delete all the users I already have that didn't had the slug field already including the superuser. so I followed this answer and I got that error django.db.utils.OperationalError: no such column: infrastructure_profile.slug any idea what's going on ? -
Storing a Name for Your Project and Calling It in a Template
I've recently started a new Django project and was wondering where to store data like the name of my project/website/brand. If my Django project was called "foo_bar" e.g., I wanna be able to save something like "FooBar" as my brand name somewhere and then use it in templates for titles etc. What is the best practise for achieving that? -
Having trouble increasing item quantity when multiple of the same item are added to cart
The image attachment: when i try to increase the quantity of the second item, the quantity of the first item increases to 2, instead of the quantity of the second item. You can watch the video i uploaded here for better understanding: https:// web.facebook.com/groups/1378481325739503/permalink/2373521109568848/ See views and template here: https://codeshare.io/GLp0Rg VIEWS @login_required def add_to_cart(request,slug): item = get_object_or_404(Item, slug=slug) item_var = [] #item variation if request.method == 'POST': for items in request.POST: key = items val = request.POST[key] print(key,val) try: v = Variation.objects.get( item=item, category__iexact=key, title__iexact=val ) item_var.append(v) except: pass order_item_qs = OrderItem.objects.filter( item=item, user=request.user, ordered=False ) if len(item_var) > 0: for items in item_var: order_item_qs = order_item_qs.filter( variation__exact=items, ) if order_item_qs.exists(): order_item = order_item_qs.first() order_item.quantity += 1 order_item.save() else: order_item = OrderItem.objects.create( item=item, user=request.user, ordered=False ) order_item.variation.add(*item_var) order_item.save() order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] #check if the order item is in the order if not order.items.filter(item__id=order_item.id).exists(): order.items.add(order_item) messages.info(request, "This item quantity was updated.") return redirect("core:order-summary") else: ordered_date = timezone.now() order = Order.objects.create(user=request.user, ordered_date=ordered_date) order.items.add(order_item) messages.info(request, "This item was added to cart.") return redirect("core:order-summary") TEMPLATE ORDER SUMMARY <td data-th="Quantity"> <div class="quantity buttons_added"> <a href="{% url 'core:remove-single-item-from-cart' order_item.item.slug %}"><input type="button" value="-" class="minus"></a> <input type="number" value="{{ order_item.quantity }}" class="input-text qty … -
Posting foreign key IDs in Django Rest Framework
I'm working on a Django API using Django Rest Framework. I have two related entities, Event and Venue. An Event takes place in a Venue. By using nested serialization I'm able to return the following to my API users: { "id": "1234", "name": "My event", "venue": { "id": "5678", "name": "My venue" } } This is all as expected. However, I'm now trying to POST an event and reference the venue as a parameter: POST /api/events/ { "name": "My new event", "venue_id": "5678" } But I'm struggling to make this work. I'm trying both venue_id and venue as attribute names (I'd prefer _id as it would be more correct, but it wouldn't be a big deal). I'm using the following serializers: class VenueSerializer(serializers.ModelSerializer): class Meta: model = Venue fields = ['id', 'name', 'created_at', 'updated_at'] class EventSerializer(serializers.ModelSerializer): venue = VenueSerializer() class Meta: model = Event fields = ['id', 'name', 'venue', 'created_at', 'updated_at'] What would be the correct approach to achieve this? -
django ajax json response
I come from PHP frameworks, but I want to format my response as if the username is invalid "login_message": "error_message" and send it to the page as msg, so I can use it later for ajax stuff , but it seems nothing to work as I want to class Login(LoginView): authentication_form = CustomAuthenticationForm form_class = CustomAuthenticationForm template_name = 'login.html' def form_valid(self, form): if form.is_valid(): user = authenticate( self.request, username=form.cleaned_data.get('username'), password=form.cleaned_data.get('password') ) if user is not None: if user.is_active: login(self.request, form.get_user()) else: return render(self.request, 'profile.html',{'login_message' : 'The user has been removed',}) else: return render(self.request, 'profile.html',{'login_message' : 'The user has been removed',}) return HttpResponseRedirect(self.get_success_url()) #login(self.request, form.get_user()) #return HttpResponseRedirect(self.get_success_url()) forms.py from django import forms from django.contrib.auth.forms import AuthenticationForm class CustomAuthenticationForm(AuthenticationForm): username = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Email','required': True,'autofocus' : True})) password = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control','placeholder':'Password','required': True})) login <form method="post"> {% csrf_token %} <h2 class="sr-only">Login Form</h2> <div class="illustration"><i class="icon ion-ios-locked-outline"></i></div> <div class="form-group">{{ form.username }}</div> <div class="form-group">{{ form.password }}</div> {{ login_message }} <div class="form-group"><button class="btn btn-primary btn-block" type="submit">Log In</button></div><a href="#" class="forgot">Forgot your email or password?</a></form> -
Running collectstatic from Heroku runs successfully, but fails to push the files to AWS, run locally it's successful
I'm trying to run a basic django app from Heroku using S3 to serve both static and media files. When I run the server locally with python3 manage.py collectstatic the static files are collected and placed into a newly created /static/ folder in my S3 bucket. When I run heroku run python3 manage.py collectstatic I am told that the static files have been collected and copied to /app/staticfiles (on build with collectstatic not disabled it's collected and copied to /tmp/build_[id]/staticfiles). Nothing is added to my S3 bucket; looking at the app filestructure on Heroku there is no folder /app/staticfiles; the app has no folder called /staticfiles; and I only have one S3 bucket, so I'm not accidentally pushing to the wrong bucket. Finally, I've quadruple checked that the dev and prod environment settings match (where appropriate). My hunch is that django.contrib.staticfiles has a very strong opinion about where the static files should end up and is overriding my settings for aws (aws_settings.py) once in production. Any pointers about how to resolve this, gratefully received! settings.py import os import dj_database_url import dotenv import django_heroku BASE_DIR = os.path.dirname( os.path.dirname( os.path.abspath(__file__))) dotenv_file = os.path.join(BASE_DIR, ".env") if os.path.isfile(dotenv_file): #DEV_ENV dotenv.load_dotenv(dotenv_file) os.environ['ENVIRONMENT']='DEV' from .envsettings.dev_settings import … -
upload_to based off foreign key value
I have an Image model. I want it to upload to a folder depending on which category the user chooses. For example if the user chooses the "apples" category I'd like it to upload to a media folder called "apples". class Image(models.Model): image = models.ImageField(upload_to=category) category = models.ForeignKey(Category, on_delete=models.CASCADE) -
Django REST Framework - How to apply permission_classes to APIRootView (browsable API)
according https://www.django-rest-framework.org/api-guide/permissions/#setting-the-permission-policy on a regular APIView you set permissions via attribute permission_classes: from rest_framework.permissions import IsAdminUser from rest_framework.response import Response from rest_framework.views import APIView class ExampleView(APIView): permission_classes = [IsAdminUser] def get(self, request, format=None): content = { 'status': 'request was permitted' } return Response(content) I would like to limit access to the APIRoot view (the browsable API) to only admin users. I tried via from rest_framework.permissions import IsAdminUser from rest_framework.views import APIView class APIRootView(APIView): permission_classes = [IsAdminUser] with no success :| some suggestions to get this to work? -
Recursively going through a model
I have a model like so: class CustomUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) slug = models.SlugField(blank=True) def lastfolder(self): try: return self.folder_set.all().order_by('-created_at')[0] except IndexError: return None def lastdrive(self): try: return self.drive_set.all().order_by('-created_at')[0] except IndexError: return None def lastfile(self): try: return self.drive_set.all().order_by('-created_at')[0] except IndexError: return None def save(self, *args, **kwargs): self.slug = slugify(self.user.username) return super().save(*args, **kwargs) def get_absolute_url(self): kwargs = {'slug' : self.slug} return reverse('', kwargs=kwargs) def __str__(self): return self.user.username class Drive(models.Model): owner = models.ForeignKey(CustomUser, on_delete=models.CASCADE) name = models.CharField(max_length=64) cover_picture = models.ImageField(upload_to=f'media/{user_path}', default="media/drive.png") created_at = models.DateTimeField() slug = models.SlugField(blank=True) def get_absolute_url(self): kwargs = {'slug' : self.slug} return reverse('', kwargs=kwargs) def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self.name) return super().save(*args, **kwargs) class Meta: unique_together = [['owner', 'name']] ordering = ('name',) class Folder(models.Model): owner = models.ForeignKey(CustomUser, on_delete=models.CASCADE) drive = models.ForeignKey('Drive', on_delete=models.CASCADE) name = models.CharField(max_length=64) parent = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True) cover_picture = models.ImageField(upload_to=f'media/{user_path}', default="media/folder-white.png") created_at = models.DateTimeField() path = models.CharField(max_length=2048, blank=True) slug = models.SlugField(blank=True) def __str__(self): return self.name def get_absolute_url(self): kwargs = {'slug' : self.slug} return reverse('', kwargs=kwargs) def get_path(self): yield self.name try: yield from get_path(self.parent) except: pass def complete_get_path(self): text = [] for i in self.get_path(): text.append(i) text.reverse() return "/".join(text) def save(self, *args, **kwargs): self.slug = slugify(self.name) self.path = self.complete_get_path() return super().save(*args, … -
Django: 404 Error Appears While Trying to Use Slug in URLs
I am a beginner in Django. Right now, I am learning the framework by building an app, called PhoneReview. It will store reviews related to the latest mobile phone. It will also display phone brands, along with the associated phone models and their reviews. Right now, I am trying to use slug in URLs. I have successfully used slug in two of my templates, which are index.html and phonemodel.html. However, I am facing issues with the third template, which is details.html. When I go to http://127.0.0.1:8000/index, I see this page: When I click on Samsung, I see this page: Up to this is fine. But when I click on any phone model, like Galaxy S10, I get 404 error. It looks like this: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/details/galaxy-s10 Raised by: PhoneReview.views.ReviewView No review found matching the query You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. When I click on Samsung, I am supposed to see the details.html page, which has the review of the phone, along with the news link. Instead, I am getting the 404 … -
How I can resolve this guys? Python.exe no such or fille directory
I use python 3.8 on Windows 10 I would like to beginning a djangoprojects. Manege.py can't run; no such or fille directory. Please how can resolve this. -
Clarification of guide to Heroku Celery
I'm trying to figure out the woeful instructions here Under the section "Configuring a Celery app" I'm not sure where i put the code: import os app.conf.update(BROKER_URL=os.environ['REDIS_URL'], CELERY_RESULT_BACKEND=os.environ['REDIS_URL']) Any clarification of these instructions is greatly appreciated. -
Get values in column between two dates in another columns in Python Django
kindly request function to get and calculates values in between time period with Python-Django function the database example will be as below **Case(1) start_time = 01-11-2019 end_time = 15-12-2019 rate = 35.00 Case(2) start_time = 16-12-2019 end_time = 31-12-2019 rate = 50.00** i need function to calculate the rate as following : user will request the period from 13-12-2019 till 18-12-2019 rate calculated [(13, 14, 15 December) = 35+35+35 = 105] + [(16, 17 , 18 December = 50+50+50 = 150] with total rate finally 255 class Items(models.Model): name = models.CharField(max_length=200, db_index=True) class Item(models.Model): name = models.ForeignKey(Items, on_delete=models.CASCADE) start_date = models.DateField() end_date = models.DateField() rate = models.DecimalField(max_digits=3, decimal_places=2) -
Does Django Support computing the most common value of a group by expression?
What would be the beaten path to computing the most common value in a group by? We're using the postgresql engine, which supports computing the most common value in a group by with mode() WITHIN GROUP (ORDER BY sort_expression). Do we have to go to SQL or Func expressions to access this function? Or is there some better way? -
How to render a User's name as text without refreshing the page in Django?
I am trying to display a User's name on top of a box where they enter their Employee # in a form, without having to refresh the page. For example, they enter their # and then after they click/tab onto the next field, it renders their name on top, which comes from the database, so the user knows they've entered the correct info. This name is stored in a separate model, so I try to retrieve it using the "id/number". I am not too familiar with AJAX but after reading a few similar questions it seems like an AJAX request would be the most appropriate way to achieve this. I tried to make a function get_employee_name that returns the name of the person based on the way I saw another ajax request worked, but I'm not sure how to implement this so it displays after the # is entered. My page currently loads, but when I check the network using F12, there is never a call to the function/url that searches for the name to display it on the page. I'm not sure where I might be missing the part that connects these two areas of the code, but I … -
Hidde url media Django Rest
Hello i have my django rest project in production with the url url/api/media/ with all my media files, but y need hidden this url and only leave his own files available I want to hide url/api/media. Need the url return 404 o 301 and url/api/media/file_owner_01.png return the file -
Why does `migrate` won't run after installing PostgreSQL database?
I installed PostgreSQL, set up a server and adapted my Django project settings to use that DB. Now when I try to migrate the changes made, I end up with the following error: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Program Files\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Program Files\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Program Files\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Program Files\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Program Files\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Program Files\lib\site-packages\django\core\management\commands\migra te.py", line 232, in handle post_migrate_state = executor.migrate( File "C:\Program Files\lib\site-packages\django\db\migrations\executor.py", li ne 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_i nitial=fake_initial) File "C:\Program Files\lib\site-packages\django\db\migrations\executor.py", li ne 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_ initial) File "C:\Program Files\lib\site-packages\django\db\migrations\executor.py", li ne 245, in apply_migration state = migration.apply(state, schema_editor) File "C:\Program Files\lib\site-packages\django\db\migrations\migration.py", l ine 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, projec t_state) File "C:\Program Files\lib\site-packages\django\db\migrations\operations\field s.py", line 249, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "C:\Program Files\lib\site-packages\django\db\backends\base\schema.py", l ine 534, in alter_field self._alter_field(model, old_field, new_field, old_type, new_type, File "C:\Program Files\lib\site-packages\django\db\backends\postgresql\schema. py", line 122, in _alter_field super()._alter_field( File … -
Add Product by Category in Django with out using form.py
I am trying to insert my product by category in django.I have two model Product and Category.I want to add Product in Product table.when i add product category comes in select box and select category .Category id in category value. which is insert in product table.Category is ForeignKey. But show this erroer: Cannot assign "'1'": "Product.p_c_name" must be a "Category" instance. 1 is the value of category id. model.py: from django.db import models from django import forms # Create your models here. class Category(models.Model): c_name = models.CharField(max_length=50) def _str_(self): return self.c_name class Product(models.Model): p_name = models.CharField(max_length=255) p_desc = models.TextField() p_price = models.CharField(max_length=255) p_date=models.DateTimeField(auto_now_add=True) status = models.BooleanField() p_c_name = models.ForeignKey(Category, on_delete=True) image = models.ImageField() def __str__(self): return self.p_name my view.py: # Product Start form here def product_add(request): print(request.POST) cats = Category.objects.all() if request.method == 'POST' and request.FILES['image']: p_name = request.POST['p_name'] p_desc = request.POST['p_desc'] p_price = request.POST['p_price'] p_c_name = request.POST['p_c_name'] status = 0 myfile = request.FILES['image'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) data = Product(p_name=p_name,image=filename,p_desc=p_desc,p_price=p_price,p_c_name=p_c_name,status=status) data.save() return redirect('/product/product-list',{ 'uploaded_file_url': uploaded_file_url }) else: return render(request,'product/add.html',{'cats':cats}) my form.html: <form class="text-center border border-light p-5" method="POST" action=""enctype="multipart/form-data"> {% csrf_token %} <!-- Name --> <input type="text" id="defaultContactFormName" class="form-control mb-4"name="p_name" placeholder="Product Name"> <input type="text" … -
Pass data between different views in Django
I have a basic view that retrieves some data, renders my page and sends some data to this page: def myview(request) one = values.objects.get(user=request.user).address two = values.objects.get(user=request.user).number return render(request, "main/mytemplate.html", context={'address': one, 'numbers': two}) So the values retrieved by those two queries are shown on my page. Now, on the same page, called mytemplate.html, i'm using another view, which is supposed to handle a form and some other operations: def secondview(request): if request.method == 'POST': if 'button1' in request.POST: form = MyForm(request.POST) # check whether it's valid: if form.is_valid(): profile = form.save(commit=False) profile.user = request.user profile.save() return HttpResponseRedirect(request.path_info) else: form = MyForm() return HttpResponse('it works!') How can i use the data retrieved by those two queries in the second view? The queries are executed when the page is loaded by the first view. Then, in the same page the second view is used. I want to use the two variables one and two in the second view. Is there a way to do this in Django? Why don't you make the same queries in the second view? Because i would like the second form to be as fast as possible in terms of reload, without having to do a DB … -
python requests library .json() + django 500
When I use the requests library with django and I get a 500 error back. response.json() gives mi this error: response = requests.post(....) print("-----------------------block found!!!-----------------------") print(response.status_code) print(response.json()) json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) Is there a way to represent a django 500 response with the requests library in a readable manner?