Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create a waiting room for users django
I would like to create something like FaceTime on a website based of the tastes of the users. I thought about creating a waiting room where all users will be. Then a matching algorithm will try to pair two of the users and take them to a private room where they will be able to chat. I tried to see for a solution on internet but I didn’t find any great answers. If you guys have any great ressources on how to do that it would be awesome :) PS: I use Django with python and rest framework for the backend. Thanks -
Template doesn't overwrite
I render a template and return it. Program seems to render template only once and then even though i change input arguments, return the first rendered template. The function named getNumber works properly and return different data. My template: <head> <meta charset='UTF-8'> <title>file uploader</title> </head> <body> <form id='selectForm'> <input id='selectInput' type='file' name='files' multiple> <div>Files:</div> <table id='selectTable'></table> </form> <script> ... </script> <p> Solution: {{ solution }} </p> </body> </html>``` Function that return HttpResponse in views.py resolving '/' url: ```def index(request): if request.method == 'POST': uploadFile1 = request.FILES['file1'] uploadFile2 = request.FILES['file2'] text1 = '' text2 = '' with open('file1', 'wb+') as file1: text1 = uploadFile1.read() with open('file1', 'wb+') as file2: text2 = uploadFile2.read() data = calcpy.views.getNumber(str(text1), str(text2)) print(data['number']) template = loader.get_template('main.html') context = {'solution' : data['number']} template.render(context); return HttpResponse(template.render(context)) template = loader.get_template('main.html') context = {'solution' : 0} return HttpResponse(template.render(context))``` Code in settings.py responsible for templates. I suppose here is the mistake. ```TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True }, ] # Application definition INSTALLED_APPS = ( 'version', 'current', 'calcpy', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles' ) I use django 1.9.5 and I can't really change the version. -
How to reverse an url from APIView in DRF for testing
I'm trying to test my view but when I try to reverse the URL I get: django.urls.exceptions.NoReverseMatch: Reverse for 'list_task' not found. 'list_task' is not a valid view function or pattern name. I'm not sure how to do it since I've seen people doing it the way I am and yet it does not work for me. Here is my view: from rest_framework import generics, filters from todo import models from .serializers import TaskSerializer from django_filters.rest_framework import DjangoFilterBackend #lists, creates and filters tasks class ListTask(generics.ListCreateAPIView): queryset = models.Task.objects.all() serializer_class = TaskSerializer filter_backends = [DjangoFilterBackend, filters.SearchFilter] filterset_fields = ['date'] search_fields = ['description'] #allows to see detail of a task class DetailTask(generics.RetrieveUpdateDestroyAPIView): queryset = models.Task.objects.all() serializer_class = TaskSerializer And here is my test view: from django.urls import reverse from rest_framework import status from rest_framework.test import APITestCase class CreateTaskTest(APITestCase): def setUp(self): self.data = {'title': 'title', 'description': 'desc', 'completed': False} def test_can_create_task(self): response = self.client.post(reverse('list-task'), self.data) self.assertEqual(response.status_code, status.HTTP_201_CREATED) -
Update database instance with specific form fields using Django (modify_personal_info)
I am quite new to Django, and I am working on a project, and I am trying to create a page to modify user data (code down below). What I am trying to do is allow the user to change one or more field, and not necessarily all the fields at the same time, and then update the user instance, I tried using multiple conditions on each field so I won't have an empty field in the database later, but nothing happens. Here's the corresponding view: ``` @login_required def profile(request, id_user): try: user = Account.objects.get(pk=id_user) if request.method == 'POST': form= request.POST if form.get('first_name'): user = Account(first_name=form.get('first_name')) user.save() if form.get('last_name'): user = Account(last_name=form.get('last_name')) user.save() if form.get('email'): user = Account(email=form.get('email')) user.save() if form.get('username'): user = Account(username=form.get('username')) user.save() if form.get('adress'): user = Account(adress=form.get('adress')) user.save() if form.get('phone'): user = Account(phone=form.get('phone')) user.save() except Account.DoesNotExist: user = None raise Http404("User does not exist") return render(request, "profile.html") And this is a snippet from the template: {% csrf_token %} Informations du compte Nom d'utilisateur Email Prénom Nom Informations de contact Adresse Télephone Appliquer ``` -
Slow requests whenever Psycopg2 reconnects to DB
I'm currently facing a very strange issue. I did some optimizations in my queries, which improved quite a lot the overall performance for my Django application's GET requests. However, I'm still facing a few very slow ones (1000ms or more). Checking on Elastic APM, I noticed that for all those cases, there was a DB reconnection. While it's obvious those requests would take more time, it's still takes WAY more time than the amount required for the reconnection itself. I have set the DB_CONN_MAX_AGE to None, therefore the connections themselves shouldn't be closed at all. Which makes me think the reason for the disconnection itself could also indicate the cause for this. The blue bars represent the amount of time a given transaction took. The total amount of time for this particular request was 1599ms. The DB reconnection took 100ms, the the queries about ~20ms. Adding those up, gives a total time of 120ms. I'm a bit clueless how to find out where the rest of the 1479ms. I did some load tests locally, but couldn't reproduce this particular issue. Of course is serializations, middlewares, authentication and other things that might add up some time to requests, but not nearly … -
Is it not possible to set ALLOWED_HOSTS as an environment variable in Django?
I have a Django app deployed on Heroku. During initial development, I defined ALLOWED_HOSTS manually in the settings.py file ALLOWED_HOSTS = ['127.0.0.1', 'localhost'] Before deploying to Heroku, I changed various settings to environment variables. In my application, I used the environs[Django] package to identify variables and I defined the variables in Heroku using "Config Vars" in app's settings tab. in my Django app, the environment variables looked like this... SECRET_KEY = env("DJANGO_SECRET_KEY") SECURE_SSL_REDIRECT = env.bool("DJANGO_SECURE_SSL_REDIRECT", default=True) During the initial deployment to Heroku, I also set ALLOWED_HOSTS as an environment variable using the same approach as described above. In my settings.py file, the variable looked like this... ALLOWED_HOSTS = env("ALLOWED_HOSTS") Long story short: This didn't work, so after a bit of trial and error, I manually defined the ALLOWED_HOSTS in the settings.py file as I had done during development. ALLOWED_HOSTS = [.herokuapp.com, etc...] I'm back to setting up ALLOWED_HOSTS as an environment variable, but in a development environment, with no luck. The message I get is... Invalid HTTP_HOST header: '127.0.0.1:8000'. You may need to add '127.0.0.1' to ALLOWED_HOSTS Haven't found anything online regarding this. The documentation says very little regarding ALLOWED_HOSTS as an environment variable, mainly in regards to DEBUG. At … -
Django Error - MultiValueDictKeyError at /new_bid/5 'total_bid.' (Beginner help appreciated)
I'm creating a page on a site to allow users to 'bid' on items similar to ebay. When I try to enter a number (dollar amount) on the item on the site (to enter a bid) I get the error: MultiValueDictKeyError at /new_bid/5 'total_bid.' The problem seems to be total_bid = request.POST["total_bid"] and I think the system believes it's None. I'm not sure why it thinks it's None because when entering the bid on the site, a number really is in the box, so if I type 100 meaning $100 bid, maybe the code is not actually taking in that number? So on POST it thinks there is nothing there? I also tried total_bid = request.POST.get["total_bid"] with the .get part and also received an error. I also tried adding something like "if total_bid is not none:" but I'm not sure how to do that with the syntax because I would need to declare total_bid = to something first. I'm new to Django so additional information on how this works would be so helpful. I've already read a lot of posts on this site about this and similar errors but I'm having some trouble understanding. views.py def new_bid(request, listingid): if request.method … -
update existing row in model with django forms
//i have a model class WerknemerCV(models.Model): bedrijfsnaam = models.CharField(max_length=50) werknemer = models.ForeignKey('auth.user', related_name='werknemer', null='False', blank='False', on_delete=models.CASCADE) def __str__(self): return self.bedrijfsnaam //my form based on the model class Create_CV(forms.ModelForm): bedrijfsnaam = forms.CharField(max_length=50) werknemer = forms.ModelChoiceField(queryset=User.objects.all()) class Meta: model = WerknemerCV fields = '__all__' //my view to create an instance with the form def maakCV(request): user = request.user if request.method == "POST": user = request.user form = Create_CV(request.POST) if form.is_valid(): form.save() return redirect(reverse("maak_cv")) else: print("form is not valid") form = Create_CV(initial={'werknemer': user}) return render(request, 'users/maak_cv.html', {"form": form}) //my html template snippet of the DETAIL view {% if user.is_authenticated %} <dt style="margin-left: 20px">Gewerkt in de functie van {{ object.functie }}.</dt> <dd style="margin-left: 20px">{{ object.omschrijving }}</dd> //my question ?, i want to update the existing instance of the model created with the form. I want to to this on the detail page. so, http://....../detail_view/1/. See my comment in the code below //my update code in view def updateCV(request): user = request.user if request.method == 'GET': cv_id = request.GET.get('cv_id', None) print('cv id', cv_id) if request.method == 'POST': cv = WerknemerCV.objects.get(pk=/////Here i want the pk of the detail, but i dont know how. form = Create_CV(request.POST,instance=cv) if form.is_valid(): form.save() return redirect(reverse("cv_detail")) else: print("form is not valid") … -
call parent dispatch before child dispatch django
I have a mixin which beside other things simplifies call of request.user object. class MyMixin(LoginRequiredMixin, View): ... leader = False employee = False def dispatch(self, request, *args, **kwargs): self.leader = request.user.is_leader() self.employee = request.user.is_employee() return super().dispatch(request, *args, **kwargs) ... And I have a heir of DetailView which has it's own dispatch method. class MyDetailView(MyMixin, DetailView): def dispatch(self, request, *args, **kwargs): if not self.leader: raise PermissionDenied return super().dispatch(request, *args, **kwargs) But as you could've told it ain't working. Is there a way to elegantly call parent dispatch method from it's heir? -
Django multiple annotation counts on a single queryset
I need to count the number of tasks pending, in progress and completed for each company at any given time. Using the code below I am able to achieve this however it is repeating the company name on each row instead of doing it once. Models.py class Company(models.Model): company = models.CharField(max_length=40) class Period(models.Model): period = models.CharField(max_length=7) class Status(models.Model): option = models.CharField(max_length=40) class Task(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE, default=None, blank=True, null=True) period = models.ForeignKey(Period, on_delete=models.CASCADE, default=None, blank=True, null=True) status = models.ForeignKey(Status, on_delete=models.CASCADE, default=1) Views.py if request.method == 'POST': if form.is_valid(): periods = Period.objects.get(period=form.cleaned_data['period']) status = Task.objects.filter(period=periods).values('period', 'company__compnay', 'status__option', 'status').annotate(count_all=Count('status__option')) args = {'form': form, 'periods': periods, 'status': status} Template {% if status %} <table class="table table-striped"> <thead> <tr> <th scope="col">Company</th> <th scope="col">Tasks Pending</th> <th scope="col">Tasks In Progress</th> <th scope="col">Tasks Completed</th> </tr> </thead> <tbody> {% for stat in status %} <tr> <td>{{stat.company__company}}</td> <td>{{stat.status__option}}</td> <td>{{stat.count_all}}</td> </tr> {% endfor %} </tbody> </table> {% endif %} Results Company Pending Tasks In Progress Tasks Completed Tasks Apple Completed 1 Apple In Progress 1 Apple Pending 2 Microsoft Completed 2 Microsoft In Progress 5 Microsoft Pending 5 Expected Result Company Pending Tasks In Progress Tasks Completed Tasks Apple 2 1 1 Microsoft 5 5 2 -
How to add real time date & time in a Djago app
I want to add date and time to the navbar of my Django app, so I added the following javascript code (reference) in the header of my base.html <script type="text/javascript"> var timeDisplay = document.getElementById("time"); function refreshTime() { var dateString = new Date().toLocaleString("en-US", {timeZone: "Indian/Christmas"}); var formattedString = dateString.replace(", ", " - "); timeDisplay.innerHTML = formattedString; } setInterval(refreshTime, 1000); </script> and the below HTML in the navbar: <p id="time"></p> I even tried putting this in the main content of my index.html file but it don't seem to work for me, what am I doing wrong? or is there any other way to add real time date and time in the navbar of my Django app? -
Can't render nested relationship in Django Rest Framework
The problem is I have a 'details' field which should render into a nested relationship with it's parent serializer. I have tried a bunch of stuff and nothing seems to be working. Here's my models: class BusinessOrderModel(OrderToModel): reference = models.IntegerField() business_num = models.ForeignKey('BusinessModel', on_delete=models.CASCADE) def __str__(self): return str(self.reference) class BusinessModel(models.Model): Business_num = models.IntegerField(primary_key=True) def __str__(self): return str(self.Business_num) class DetailModel(models.Model): id = models.AutoField(primary_key=True) detail = models.TextField() order = models.ForeignKey('BusinessOrderModel', on_delete=models.CASCADE) and here's my serializers which aren't working: class DetailSerializer(serializers.ModelSerializer): class Meta: model = DetailModel fields = ('id', 'detail') class BusinessOrderSerializer(serializers.ModelSerializer): details = DetailSerializer(many=True) class Meta: model = BusinessOrderModel fields = ('reference', 'business_num', 'details') I've tried many different things but I get this error: Got AttributeError when attempting to get a value for field details on serializer BusinessOrderSerializer. The serializer field might be named incorrectly and not match any attribute or key on the BusinessOrderModel instance. Original exception text was: 'BusinessOrderModel' object has no attribute 'details'. Any help is much appreciated. Thank you very much. -
How to integrate Chart(Bar,Line) with Django Project
I want to create Charts like Bar, line, and so on how to integrate with the Django project. -
How to call a function from views.py to tasks.py?
I'm trying this: but its throwing an TypeError: auto_sms() missing 1 required positional argument: 'request' error. Now I'm thinking of getting the function from views.py instead and calling it on tasks.py if requests is not working on tasks.py, how can I do it? Thanks! @shared_task def auto_sms(request): responses = Rainfall.objects.filter( level='Torrential' or 'Intense', timestamp__gt=now() - timedelta(days=1), ) count = responses.count() if not (count % 10) and count > 0: send_sms(request) return -
Django foreign key field not updating with selected value from React Select dropdown
I have a webpage in my issue tracker project that allows a project manager to assign a user to a project. I am using React Select to allow the manager to select a user from a dropdown. When they click the add user button, the selected value gets sent to the backend through an api call. I have an APIView called assignuser, which takes in the post request and updates the user foreign key field in my Project model. Am I referencing the selected value wrong? I have tried sending selectedValue.value to my backend but it keeps on coming up as undefined. Django Backend class assignuser(APIView): serializer_class = ProjectSerializer def post(self, request, format=None): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): user = serializer.data.get('user') project_name = serializer.data.get('project_name') project = Project.objects.get(name=project_name) project.user = user project.save(update_fields=['user']) return Response(ProjectSerializer(project).data, status=status.HTTP_201_CREATED) else: return HttpResponse("Incorrect Credentials") React Frontend import React, { Component } from "react"; import { useState, useEffect } from "react"; import { Grid, TextField, Button, Typography } from "@material-ui/core"; import { FixedSizeList as List } from 'react-window'; import css from './style.css'; import Select from 'react-select'; import {useLocation} from "react-router"; const manageusers = () => { const [role, setRole] = useState([]); const location = useLocation(); const [project_name, … -
Return appropriate error for unactivated users in Djoser
I am using Django 2.2.14 with the configuration below for Djoser 2.1.0 but when trying to get JWT token for an inactive user, it returns the same error as using a wrong password which makes it tricky to differentiate. I get HTTP STATUS 401 with the detail below { "detail": "No active account found with the given credentials } My configuration Djoser is shown below: 'LOGIN_FIELD': 'email', 'SEND_CONFIRMATION_EMAIL': True, 'PASSWORD_CHANGED_EMAIL_CONFIRMATION': True, 'USER_CREATE_PASSWORD_RETYPE': True, 'TOKEN_MODEL': None, 'SEND_ACTIVATION_EMAIL': True, "LOGOUT_ON_PASSWORD_CHANGE": False, "PASSWORD_RESET_SHOW_EMAIL_NOT_FOUND": True, "USERNAME_RESET_SHOW_EMAIL_NOT_FOUND": True, 'PASSWORD_RESET_CONFIRM_URL': 'account/password/reset/confirm/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL': 'account/username/reset/ /{uid}/{token}', 'ACTIVATION_URL': 'account/activate/{uid}/{token}', I am also using AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.AllowAllUsersModelBackend'] -
Django 3 Dynamic Default Value in Model
There are similar questions but none recent and based on Django 3 so here it goes: I am using py nanoid to generate some unique IDs so in my models I have from nanoid import generate and then class Work(models.Model): title = models.CharField(max_length=200) body = models.TextField() published = models.BooleanField(False) date = models.DateTimeField() nanoid = models.CharField(max_length=15, default = generate(size=10) ) def __str__ (self): return self.title my aim is to ensure that a new nanoid is generated each time a new work post is added. At the moment is the same repeated each time I try to add a new Work via admin. I read some replies about creating a custom class but I am a bit at a loss here! -
Adding pandas dataframe to the initial db.sqlite database in django + no duplicates
How can i convert and assign the fetched information (that is modified with pandas) to a predefined model + not include duplicate rows? As i understood, pandas.DataFrame.to_sql should be used, but i'm a bit confused how to do this / connect both things. models.py class Article(models.Model): article_author = models.CharField(blank=True, max_length=500) article_date_publised = models.CharField(blank=True, max_length=500) article_title = models.CharField(blank=True, max_length=500) article_description = models.CharField(blank=True, max_length=500) article_url = models.CharField(blank=True, max_length=500) article_urlToImage = models.CharField(blank=True, max_length=500) article_content = models.CharField(blank=True, max_length=500) article_network = models.CharField(blank=True, max_length=500) fetched information + pandas dataframe import pandas as pd import requests import time fox_url = "https://saurav.tech/NewsAPI/everything/fox-news.json" fox_news = requests.get(fox_url).json() df = pd.json_normalize(fox_news) fox_articles = pd.json_normalize(df["articles"].loc[0]) del fox_articles['source.id'] fox_articles["date_publised"] = pd.to_datetime(fox_articles['publishedAt']) del fox_articles['publishedAt'] fox_articles holds this table (snippet) author title description url urlToImage content source.name date_publised 0 Ronn Blitzer Dershowitz calls Trump impeachment a 'loaded w... Harvard Law professor emeritus and constitutio... https://www.foxnews.com/politics/dershowitz-tr... https://static.foxnews.com/foxnews.com/content... Harvard Law professor emeritus and constitutio... Fox News 2021-01-10 17:39:49+00:00 1 Evie Fordham Post-Capitol riot censorship shows 'unelected'... Online censorship in the wake of violence at t... https://www.foxnews.com/politics/capitol-censo... https://static.foxnews.com/foxnews.com/content... Online censorship in the wake of violence at t... Fox News 2021-01-10 17:30:15+00:00 settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', … -
Is there a possibility to pass fields from different models to CreateView in Django?
I'm extending polls app from official Django tutorial and want to pass Question field question_text along with Choice field choice_text to CreateView generic View, to let the user create a Question along with it's choices at the same time. Unfortunately I can only pass Question model with question_text to the CreateView I know CreateView takes only one model so is there a possibility to maybe overwrite it somehow? Question is a foreignKey in a database to the Choice model. I found some answers using extra_views but i do not want to use some external source to do that Below my code Views class CreateView(LoginRequiredMixin, generic.CreateView): success_url = reverse_lazy('polls:index') redirect_field_name = 'accounts:signup' model = Question fields = ['question_text'] template_name = 'polls/poll_form.html' def form_valid(self, form): form.instance.author = self.request.user response = super(CreateView, self).form_valid(form) return response Models class Question(models.Model): question_text = models.CharField(max_length=200) author = models.ForeignKey(User, default='Default', on_delete=models.CASCADE) pub_date = models.DateTimeField('date published', default=timezone.now) def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text Urls app_name = 'polls' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('new/', views.CreateView.as_view(), name='create'), path('<int:pk>/', views.DetailView.as_view(), name='detail'), path('<int:pk>/results/', views.ResultsView.as_view(), name='results'), path('<int:question_id>/vote/', views.vote, name='vote'),] -
How to save address form data and display in template using Django
Brand new to Django/Python and have almost completed my first big project. I've built a small ecommerce store with a staff backend to update/delete and create products. I would like to display the address entered in by the User at checkout with in the Staff template. My code so far looks like this: models.py: class Address(models.Model): ADDRESS_CHOICES = ( ('B', 'Billing'), ('S', 'Shipping'), ) user = models.ForeignKey( User, blank=True, null=True, on_delete=models.CASCADE) street_address = models.CharField(max_length=150) town_or_city = models.CharField(max_length=100) county = models.CharField(max_length=100, default=True) postcode = models.CharField(max_length=20) address_type = models.CharField(max_length=1, choices=ADDRESS_CHOICES) default = models.BooleanField(default=False) def __str__(self): return f"{self.street_address}, {self.town_or_city}, {self.county}, {self.postcode}" class Meta: verbose_name_plural = 'Addresses' I would like to captcha the data from the 'street_address', 'town_or_city', 'county' and 'postcode' fields and have that info displayed with in my staff template. The idea I had was to import my Address model and grab all objects using Address.objects.all() and have this display with in the template using something like {{ user_address}} views.py / StaffView: class StaffView(LoginRequiredMixin, generic.ListView): template_name = 'staff/staff.html' queryset = Order.objects.filter(ordered=True).order_by('-ordered_date') paginate_by = 10 context_object_name = 'orders' def get_address(self): user_address = Address.objects.all() return user_address staff.html: <tr> <td><a class="order-ref-number-link" href="{% url 'cart:order-detail' order.pk %}">#{{ order.reference_number }}</a> </td> <td>{{ order.ordered_date }}</td> <td>{{ order.user.email }}</td> … -
Django model be related to objects of different types
I have a model called Assignment. Each Assignment can hold multiple questions of different types. That is, an Assignment can have Multiple Choice Questions, Essay Questions, True or False Questions. Each of the question types have their own model. Of course, they are related to the assignment by ForeignKey. How can I related them to the assignment such that to get all the questions (of different types) all I have to do is call. assignment1.questions.all() I have seen a few write-ups on things like GenericForeignKey, ContentType, etc. but I am yet to make them work. -
Error when trying to add python in javascript django
I'm new to Django and javascript, I've been trying to add a leaflet map in my Django template, I achieved this but I am trying to centre this map with the location of my model but I'm having problems to access the location property in my model, I've been looking how to add python in javascript and almost everywhere they said it had to be done the same way I do it in the HTML {{ object.location }}. But it is not detecting it as python so it is giving 3 different errors (Property assignment expected, ',' expected and declaration or statement expected). My intention is to replace [41.38, 2.17] with the var I declared. Here is the leaflet javascript code: <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js" integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA==" crossorigin=""></script> <script type="text/javascript"> var event_location = {{ object.location }}; // Here I get the errors var mymap = L.map('mapid').setView([41.38, 2.17], 13); L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', { attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>', maxZoom: 18, id: 'mapbox/streets-v11', tileSize: 512, zoomOffset: -1, accessToken: 'myaccesstoken' }).addTo(mymap); </script> In my template, I have no problems accessing the location with {{ object.location }} -
How to wait or stop a celery task in the middle?
I have a form in my Django app which creates an object car. I use celery to run operations, once new object car was created (by using post_save signal). I have an option to delete the car. So it should delete it from the database and it should run deleting operations with Celery. I use pre_save for that. The problem is as following: The creating operations can take some time (a few minutes). This means, that user can create a new car and while running the Celery creation operation, he will ask to delete the object. The celery tasks: @app.task(bind=True) def create_car(self, car_pk): from cars.models import car if car_pk is None or not isinstance(car_pk,int): return False car_obj = car.objects.get(pk=car_pk) # Creation operations car_obj.save() return creation_status @app.task(bind=True) def delete_car(self, car_pk): from cars.models import car if car_pk is None or not isinstance(car_pk,int): return False car_obj = car.objects.get(pk=car_pk) # deletion operations return deletion_status The signals in models.py: @receiver(post_save, sender=Car) def queue_car_create_request(sender, instance, created, **kwargs): if not created: return create_car.delay(instance.pk) @receiver(pre_delete, sender=Car) def queue_car_delete_request(sender, instance, using, **kwargs): delete_car.delay(instance.pk) So my question is - how should I handle this case? Can I somehow "stop" the creation task? Or can I somehow "wait" until the creation … -
View didn't return an HttpResponse object, it returned None instead
That's my views.py file from django.shortcuts import render from django.http import HttpResponseRedirect from .forms import ReviewForm # Create your views here. #COMMENT_PAGE def Comment_page(request): if request.method == 'POST': form = ReviewForm(request.POST) if form.is_valid(): return HttpResponseRedirect('') else: form = Review(request.POST) return render(request, 'comment_page.html', {'form':form}) And my output is The view games.views.Comment_page didn't return an HttpResponse object. It returned None instead. -
How to create a custom Form Field for the Foreign Key Django
My models class Address(TimeStampModel): street_number = models.CharField(_("Street Number"), max_length=5, blank=True, null=True) street_line_1 = models.CharField(_("Street line 2"), max_length=250, blank=True, null=True) street_line_2 = models.CharField(_("Street line 1"), max_length=150, blank=True, null=True) postcode = models.CharField( _("Post/Zip-code"), max_length=64, blank=True, null=True ) city = models.CharField(_("City"), max_length=60, blank=True, null=True) state = models.CharField(_("State"), max_length=255, blank=True, null=True) country = models.CharField(max_length=50, choices=COUNTRIES, blank=True, null=True, default='France') class UserProfile(TimeStampModel): user = models.OneToOneField(CoreUser, related_name='userprofile', on_delete=models.CASCADE, verbose_name="Email") first_name = models.CharField(max_length=50, verbose_name="First name", null=True) last_name = models.CharField(max_length=50, verbose_name="Last name", null=True) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,12}$', message="Phone number must be entered in the format: '+999999999'. Up to 12 digits allowed.") phone_number = models.CharField(validators=[phone_regex], max_length=12, blank=True) birthdate = models.CharField(max_length=200, null=True) profile_picture = models.ImageField(default='default.jpg', upload_to=get_path) profile_address = models.ForeignKey( Address, related_name="userprofile_address", on_delete=models.SET_NULL, blank=True, null=True, ) agency = models.ForeignKey( Agency, on_delete=models.SET_NULL, null=True, blank=True ) My form class ProfileForm(forms.ModelForm): first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=254) phone_number = forms.CharField(max_length=254) profile_picture = forms.ImageField() def __init__(self, *args, **kw): super(ProfileForm, self).__init__(*args, **kw) self.fields['first_name'].initial = self.instance.user.userprofile.first_name self.fields['last_name'].initial = self.instance.user.userprofile.last_name self.fields['phone_number'].initial = self.instance.user.userprofile.phone_number self.fields['profile_picture'].initial = self.instance.user.userprofile.profile_picture def save(self, *args, **kw): super(ProfileForm, self).save(*args, **kw) self.instance.user.userprofile.first_name = self.cleaned_data.get('first_name') self.instance.user.userprofile.last_name = self.cleaned_data.get('last_name') self.instance.user.userprofile.phone_number = self.cleaned_data.get('phone_number') self.instance.user.userprofile.profile_picture = self.cleaned_data.get('profile_picture') self.instance.user.userprofile.save() class Meta: model = UserProfile fields = ['first_name', 'last_name', 'phone_number', 'profile_picture', 'agency', 'profile_address', ] In my view I'm looking for how to access the …