Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How To Declare JSON Fields in a Django Model?
I'm seeking to create my first Django mySQL model that contains a JSON field. I've read the docs here, but they don't seem to show an example of how to declare a model that contains multiple fields, including JSON fields. I've done a lot of searches on Google and SO, but haven't yet found examples. What would be the correct way to declare a model that would store data like this? candy_bar_name='Snickers', info={ 'target_markets': [ { 'market_type': 'type_a', 'included_markets': [array of strings] }, { 'market_type': 'type_b', 'included_markets': [array of strings] }, { 'market_type': 'type_c', 'included_markets': [array of strings] }, ], } -
TypeError many-to-many set is prohibited
I am trying to create a like model, when a user click on a button it generate to 1 like in database. This is the error i get when saving my code: Direct assignment to the forward side of a many-to-many set is prohibited. Use image_like.set() instead. class Image(models.Model): imageuploader_profile = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, null=True, blank=True) first_upload_image = models.FileField(upload_to ='picmate/%Y/%m/%d/',null=True, blank=True) image_caption = models.CharField(max_length=700) tag_someone = models.CharField(max_length=50,blank=True) date = models.DateTimeField(auto_now_add=True, null= True) class Likes(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True, blank=True) image_like = models.ManyToManyField(Image, related_name="likes") likes = models.IntegerField(default=0) def save_like(request,pk): image_like = get_object_or_404(Image,pk=pk) like_img, created = Likes.objects.get_or_create( image_like=image_like, ) like_img.likes += 1 like_img.save() return redirect('site:home') -
Django form in an extended template
I am very new to Django, I have a home template (home.html) which is extending a base template (base.html) with {% extends "base.html" %}. base.html containts a contact form. <form id="email-form" name="email-form" data-name="Email Form" method="post"> {% csrf_token %} <div> <label for="Name-2" class="field-label">Full name</label> {% render_field form.name class+="text-field w-input" %} </div> <div> <label for="Email-2" class="field-label">Email address</label> {% render_field form.from_email class+="text-field _2 w-input" %} </div> <div> <label for="Phone-2" class="field-label">Phone number</label> {% render_field form.phone class+="text-field _2 w-input" %} </div> <div> <label for="Timeline" class="field-label">More information</label> <div> {% render_field form.message class+="text-field area w-input" %} </div> </div> <div class="algin-center form-actions"> <input type="submit" value="Send Message" data-wait="Please wait..." class="button full w-button"> </div> </form> views.py from django.core.mail import send_mail, BadHeaderError from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render, redirect from django import forms class ContactForm(forms.Form): name = forms.CharField(required=True) from_email = forms.EmailField(required=True) phone = forms.CharField(required=True) message = forms.CharField(widget=forms.Textarea, required=True) def homeView(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] phone = form.cleaned_data['phone'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] try: send_mail(name, message, from_email, ['email@email.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('success') return render(request, "home.html", {'form': form}) The form is rendering fine, however, when I click the submit button nothing happens. I'm … -
How to return false from string converted in bool
I can't return False in settings.py from docker(.env) DEBUG = os.environ.get('DEBUG_MODE') DEBUG_MODE=False Python return: x = False bool(x) False print(bool(x)) False x = 'False' print(bool(x)) True How to return False? -
Django how to make model for user model
I'm developing to-list app with registration . I have two models : Model for User and Model for Tasks . I add new task throw Ajax to one user it adding and displaying for every user. Is there any solutions ? Here some pictures Here is my code: models.py class Task(models.Model): title=models.IntegerField() date = models.DateTimeField(default=datetime.now,blank=True) is_published=models.BooleanField(default=True) class CustomUser(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) image=models.FileField(upload_to='photos/%Y/%m/%d/',null=True,blank=True) views.py if request.method == 'POST' and request.POST['form_type'] == 'task': if request.is_ajax(): addtask = AddTask(request.POST) if addtask.is_valid(): user = request.user.id addtask.objects.filter(user=user).cleaned_data addtask.objects.filter(user=user).save() task_object = Task.objects.filter(user=user)(addtask) return JsonResponse({'error': False, 'data': task_object}) else: print(addtask.errors) return JsonResponse({'error': True, 'data': addtask.errors}) else: error = { 'message': 'Error, must be an Ajax call.' } return JsonResponse(error, content_type="application/json") addtask = AddTask() task = Task.objects.order_by('-date').filter(is_published=True) html page {% if task %} {% for tas in task %} Task content {% endfor %} {% else %} {% endif %} -
Django - setting CSRF token on API view
I'm creating a API endpoint to receive data and create model objects out of said data. I've currently got two views for this API - one that sends the data and one that receives it - but in reality, I'll be using a script to send the data instead of a view. I'm working on the view to receive data on my local host which is why I've got the one that sends it for now. The current issue I'm facing is with the function that sends the data to the API endpoint. My POST request is coming back with a 403 error and it says Forbidden (CSRF cookie not set.): /reports/swipe/data. To fix this I'm trying to add a CSRF cookie, but I'm very new to API endpoints and have had some trouble with it. I've tried using @csrf_exempt and adding verify=False among other things, but I haven't had any success yet. I've also spent a few hours searching online for resources that could help. Below is portions of my code. I'd appreciate whatever suggestions people can provide. views.py: from datetime import datetime, timedelta, date, time import time import datetime import json import os from django.shortcuts import render from … -
Switch from SQLite to postgres
Two things to note: One, I am executing these commands with my virtual environment running. So terminal appears as (env):. Two, every time I tried to enter su postgres, it asked me for a password. I am reading a book on Django(using a mac), the text says: "If you are using macOS, download PostgreSQL from https://www.postgresql.org/download/ and install it. You also need to install the Psycopg2 PostgreSQL adapter for Python. Run the following command to install it: pip install psycopg2==2.7.4." I already had postgres installed on my machine, as I was previously fumbling with trying to deploy a website, before reverting back to this example project I had built. So I did not go to the website and install it. I installed psycopg2 as instructed. "Let's create a user for our PostgreSQL database. Open the shell and run the following commands: su postgres then createuser -dP blog" I was thinking that "open the shell" meant enter the python virtual shell? So: python manage.py shell then su postgres this did not work, it asked me for a password. Exited the shell, ran the same command (env): su postgres, same result. From there I thought maybe since I am in a virtual … -
How to mount django app in docker with nginx and uwsgi
Hi before explaining my problem I will provide a small description of my requirements. I work with kong and konga to manage my projects with docker. It helps to run different apps in different folder as if they were all under the same site. I have different apps already running with docker but this is the first one in which I use Django. The app was developed initially using gunicorn to run the django app and nginx to serve static files under a different port. In local environment works but as I run my apps with Konga I need to hande both in a way that allows me to handle under the same port and I believe that uwsgi is the option. I actually could run the app with Konga but without serving any asset. The project structure is: blacklist/ asgi.py settings.py urls.py wsgi.py blacklist_app/ controllers/ migrations/ templates/ uploaded_files/ urls.py models.py views.py etc config/ nginx/ nginx.conf assets/ (Assets to be serve by nginx) uwsgi/ uwsgi.ini docker-compose.yml Dockerfile manage.py requirements.txt #docker-compose.yml version: '3' services: nginx: image: nginx:latest container_name: subida-excel-nginx ports: - "8011:8011" volumes: - ./nginx/src:/src - ./config/nginx:/etc/nginx/conf.d - ./config/uwsgi:/etc/uwsgi.d depends_on: - web networks: - subida-excels environment: - URL_BASE=${SUBIDAEXCEL_URLBASE} web: container_name: subida-excel … -
Filter by exact title inside a category
I have got a page where the items are displayed for specific category and I can filter the items further more using price and title__icontains, but I would like them to be filtered by exact title as well. So all the titles inside that category would be displayed and by clicking on one of them the items would be filtered by the title. so here's views.py for SearchView: def SearchView(request, category_id=None): if category_id: category = Category.objects.get(pk=category_id) item_list = Item.objects.filter(category__id=category_id) else: item_list = Item.objects.all() query = request.GET.get('q') if query: item_list = item_list.filter(title__icontains=query) price_from = request.GET.get('price_from') price_to = request.GET.get('price_to') item_list = item_list.annotate( current_price=Coalesce('discount_price', 'price')) if price_from: item_list = item_list.filter(current_price__gte=price_from) if price_to: item_list = item_list.filter(current_price__lte=price_to) context = { 'item_list': item_list, 'category': category } return render(request, "search.html", context) and views.py for TitleView: def TitleView(request, title): item_list = Item.objects.filter(title__icontains=title) return render(request, "search.html", {'item_list': item_list}) urls.py urlpatterns = [ path('search/', SearchView, name='search'), path('search/<category_id>', SearchView, name='category_search'), path('search/<title>', TitleView, name='title_search'), path('bike-category/<category_id>', category_view, name='category'), ] search.html simple list for displaying the titles: <ul> {% for item in item_list %} <li> <a href="{% url 'core:title_search' title=item.title %}"> {{ item.title }} </a> </li> {% endfor %} </ul> When I click on one of them I am geting an error ValueError at … -
Returning a response object from HTTP methods in Class based Views
class BaseListView(MultipleObjectMixin, View): """A base view for displaying a list of objects.""" def get(self, request, *args, **kwargs): self.object_list = self.get_queryset() allow_empty = self.get_allow_empty() if not allow_empty: # When pagination is enabled and object_list is a queryset, # it's better to do a cheap query than to load the unpaginated # queryset in memory. if self.get_paginate_by(self.object_list) is not None and hasattr(self.object_list, 'exists'): is_empty = not self.object_list.exists() else: is_empty = not self.object_list if is_empty: raise Http404(_('Empty list and “%(class_name)s.allow_empty” is False.') % { 'class_name': self.__class__.__name__, }) context = self.get_context_data() return self.render_to_response(context) So i've taken this code from the docs, im interested in the render_to_response() method, i have read around and i believe it constructs an instance of a some specified Response class (templateReponseMixin.response_class attribute) or default Response class(TemplateResponse class), could someone more experienced than me tell me whether the Response instance is also rendered within the render_to_response() method and returned or would it be rendered by another middleware code? -
GeoDjango - distance between a point and a queryset of multipolygons
I'm familiar with Django, but new to GeoDjango and Postgis. I have a problem where I want to find the nearest MuliPolygon to a point. The point can be outside or within the MultiPolygon. Nearest means nearest boundary point. I know that I can calculate distance between two points with from django.contrib.gis.db.models.functions import Distance - but I don't want to use the centroid because it is possible the border of a MultiPolygon is closer to one point than the centroid of another. I have a model Land with a field surface_area which is a MultiPolygon. I have a point object created with from django.contrib.gis.geos import Point. This is the data I'm using to try and build a query. Any help with best practices would be appreciated. -
Cannot use the submit button without refreshing page using Django
I'm new to django, and I have setup my project exactly the same way as the tutorial "polls" project. I'm trying to get the page not refreshing or being redirected to another view when I submit an option through a button. This is my detail.html: (...) <div class="cardq mt15"> <form action="{% url 'polls:vote' question.id %}" method="post"> {% csrf_token %} {% for choice in question.choice_set.all %} <!-- New Question --> <div class="cardq__qu"> <i class="far fa-question-circle"></i> <!--<p name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br> </p>--> <input type="submit" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> </div> {% endfor %} (...) I have this on my views.py: def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): return render(request, 'polls/detail.html', { 'question': question, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) What I basically want is to NOT get redirected to results.html and display the results on detail.html without refreshing the page, the same one that had the voting buttons. It's already accurately displaying the poll results on the same page, but if I click one of the buttons, it forces to get redirected to the results … -
Why is django rendering an empty page titled "Django Application"?
My django project was working properly but when i closed my django ide and re run the application it showed me a blank page with title Django Application while my applications title is something else. I tried running it many times but still facing the same issue. This is the hierarchy of my django application. I'm trying to my application so my base.html should run which includes header.html and footer.html But when i run my application it shows me something like this. Previously it was running properly. I don't know what exactly the issue is. -
Django (2.0.1) Row SQL Query - Putting Results into Templates Html *Raw query must include the primary key*
I am trying to fetch data from my database and displaying the results in a template. However, the results are not displayed. Result on the website is: "Raw query must include the primary key". This is my code: This is my code in the view: class EventListView(ListView): context_object_name = "events" template_name = 'core/event_detail_list.html' def get_queryset(self): queryset = Event.objects.raw("""select name, date from classroom_event""") return queryset This is my code in template(event_detail_list.html): {% extends 'base.html' %} {% block content %} <tbody> {% for event in queryset %} <tr> <td class="align-middle">{{ event.name }}</td> <td class="align-middle">{{ event.date }}</td> </tr> {% empty %} <tr> <td class="bg-light text-center font-italic" colspan="5">You haven't created any events yet.</td> </tr> {% endfor %} </tbody> {% endblock %} My Model looks the following: class Event(models.Model): owner_events = models.ForeignKey(User, on_delete=models.CASCADE, related_name='events') name = models.CharField(max_length=30) date = models.DateTimeField(default=timezone.now) def get_absolute_url(self): # defekt return reverse('event_detail', kwargs={'pk': self.pk}) return self.name def get_event(self): name = escape(self.name) date = escape(self.date) return "Name: " + str(name) + " Datum: " + str(date) class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) interests = models.ManyToManyField(Subject, related_name='interested_teachers') events = models.ManyToManyField(Event, related_name="teacher_events") def __str__(self): return self.user.username def get_events(self): return "Name: " + str(self.events.name) + "Datum: … -
How to add nested comments in a Django blog
I have a blog app where I have a comments section. The comments can be made by only authenticated user. I want to add the ability to add replies to comments in a nested format, but I have no idea how. Here is are the models which are involved into the comments part: class Article(models.Model): title = models.CharField(max_length=100) description = models.TextField() publish_date = models.DateField(auto_now_add=True) author = models.ForeignKey(Author, on_delete=models.CASCADE) tag = models.ManyToManyField(Tag) thumbnail = models.ImageField(blank=True) content = HTMLField() def __str__(self): return self.title def get_absolute_url(self): return reverse('post-page', kwargs={'id': self.id}) @property def get_comments(self): return self.comment_content.all() class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) article = models.ForeignKey(Article, related_name='comment_content', on_delete=models.CASCADE) content = models.TextField() def __str__(self): return self.user.username The modelform I created: class CommentForm(forms.ModelForm): content = forms.CharField( widget = forms.Textarea( attrs= { 'class': 'form-control', 'id': 'message', 'cols': '30', 'rows': '10', } ) ) The way each comment is rendered: {% for comment in article.get_comments %} <li class="comment"> <div class="comment-body"> <h3>{{ comment.user.username }}</h3> <div class="meta mb-3">{{ comment.timestamp }}</div> <p>{{ comment.content }}</p> <p><a href="#" class="reply">Reply</a></p> </div> </li> {% endfor %} I have used a @property to display the comments. Do I need to change the overall way the comments are rendered? Can someone help me with creating … -
Three column layout – Fitting my Articles in without gaps (Python, Django & Javascript)
can anyone help me with a technical interview challenge I am stuck on? My goal is to create a three-column grid format. Articles that appear in the grid have been given a layout value which determines how many columns they take up. Articles can be one-column, two-column, or three-column. Each of the columns is 300 pixels wide, giving a total grid width of 900 pixels. I have been given a dictionary containing 18 articles, each with a key-value pair. Each key-value pair contains a title and a column value (0-3). e.g { "title": "Star Ocean review", "columns": 2 }, My task is to create some code that places the articles next to one another with no gaps. To display the articles I have set up a template tag and a for loop to iterate through the data that I have in a database. I need to somehow grab the column data and whether it is a 1, 2 or a 3 and assign each column with a width and height then I can go about generating a script to fit the articles together randomly. This is the only way I can think to do it but I am finding it … -
Python - ValueError: Unable to configure handler 'file': [Errno 2] No such file or directory:
I am using MAC OS Catalina 10.15.3 and using Python 2.7 (just to replicate the old project developed in 2.7). I already went through the post about "ValueError: Unable to configure handler 'file': [Errno 2] No such file or directory:" and I am facing the similar problem. I tried to follow the procedure given in the post mentioned above, but it did not solve my problem. I am following a deployment procedure of a github project (cloud copasi). When I run the instruction (python manage.py migrate) it gives me the following error on zsh terminal. I am running the process inside virtual environment. I already have the file created in the specified directory but it is still giving me the same error. I am sorry but I am new to MAC and Python. Immediate help is appreciated. Thanks. Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/Users/cloudcopasi/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Users/cloudcopasi/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute django.setup() File "/Users/cloudcopasi/venv/lib/python2.7/site-packages/django/__init__.py", line 22, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/Users/cloudcopasi/venv/lib/python2.7/site-packages/django/utils/log.py", line 75, in configure_logging logging_config_func(logging_settings) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/config.py", line 794, in dictConfig dictConfigClass(config).configure() File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/config.py", line 576, in configure '%r: %s' % (name, e)) ValueError: Unable to … -
Is there a python function that orders a list or dictionary in function of a keyvalue?
I'm fairly new to python and I wonder if there's a way to organize a dictionary list in function of an item value. For example i have the following code: # This is a django query wich returns a list like: [{'date_started__week': x, 'total': p},{'date_started__week': y, 'total': q},.....] income = list(Project.objects.filter((Q(status = 1) | Q(status = 5)),date_started__year = timezone.now().year).values('date_started__week').order_by('date_started__week').annotate(total=Sum('aprox_cost'))) If i perform the following command it returns as follows: print(income[0]) {'date_started__week': 4, 'total': 2747} I would like to know if there is a short way that income[0] becomes income[4] (basically the 'date_started__week' value) and fill the ones that do not have values with Nones, without looping through each week and making some logic on it. Thank you! -
I would like to get count of rows within 2 related Django Models
I have the following models within my models.py as shown below: class Classroom(models.Model): name = models.CharField(max_length=10) class Student(models.Model): reg_no = models.CharField(max_length=10) name = models.CharField(max_length=64) dob = models.DateField() current_class = models.ForeignKey(Classroom, on_delete=models.CASCADE) I would to display count of how many students are there in each class. For example, if we have 10 students in Class 1, 15 students in Class 2, 20 students in Class 3, 25 students in Class 4 and so on. I would like to display something like, what's shown below: Class 1 (10) Class 2 (15) Class 3 (20) Class 4 (25) I would be really thankful if anyone could help me with this. Thanks in advance! -
Should I use Django or Nginx to serve static image files? Their file paths are generated by Django?
I'm trying to serve static images from a server. The path where images are being saved to is generated using a function I wrote for mass image storing. Essentially, the image file name becomes the hash of the image index in the database. For example, the 1st image filename would be 356a192b7913b04c54574d18c28d46e6395428ab. The path is then extracted from the filename based on the first four characters of the hash. For filename above, the path would be /static_root/35/61/356a192b7913b04c54574d18c28d46e6395428ab. The issue is that when a client requests for a particular file (ie /images/356a192b7913b04c54574d18c28d46e6395428ab), the path to that image still needs to be deconstructed. I want to use Nginx to take some load off of my Django application, but the function to decode/encode file paths is written in python. How should I be transforming the url and serving the image? -
Firefox Debbuger for VSCode
I'm trying to debug ts files in a project with django and angular. but the breakpoints i put in the code does not work. I've tried with launch and attach config with firefox debbugger but it still does not working. I hope you can help me. -
Django check if field is valid for prefetching
Given models: class Parent: ... class Child: parent = models.ForeignKey(Parent, on_delete=models.CASCADE) parent_id = models.IntegerField() Is there a way to check that parent is valid for prefetch - without actually running the query and crashing? Given a list like ['parent', 'parent_id'] I want to do something like: Child.prefetch_related(['parent', 'parent_id']) where it ignores parent_id. -
How to Sum a column from a JSON field in string format? DJANGO
How to Sum a column from a JSON field in string format? DJANGO I have done it in several ways. Could we help with this problem? I am very grateful for everyone's attention. Thanks. transaction = Transactions.objects.all().annotate(amount=KeyTransform('amount','metadata')).aggregate(Sum('amount')) print(totalAmount) django.db.utils.ProgrammingError: function sum(jsonb) does not exist APP | LINE 1: SELECT SUM("amount") FROM (SELECT("libertyblue_transaction"... APP | HINT: No function matches the given name and argument types. You might need to add explicit type casts. -
I did python upgrade from 2.7 to python 3.5.2 , but gunicorn is not working in Linux 6.10 - 0 instances are running - failed
we upgraded virtual environment too , through svn revision number we updated all requirements we have both 2.7 and 3.5.2 python versions in the system . is this making issue ? -
In Django, why blank=True in the model is not making the form field not mandatory?
In the django documentation there is information that by declaring a model field of type CharField as blank=True, the form will not require filling in the respective field. However, in my project that is not working. To make a field not mandatory in the form, the only alternative I found was to define it as required=False. I am using Django 3.0.2.