Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use proxy server in my django local development?
I am trying to create a web project which need to make a request to another API which use a kind DATADOME capcha system. To bypass it, I need to use a rotating proxy API. When I use that on a simple script it works but when I use django I am locked by this CAPCHA. So, how it is possible to use proxy in my project development.In my projet, I need to make a request in order to catch the data. Thanks for your help everyone! here is the format of my proxy: username = "********" password = "********" ADDRESS_DNS = "***********:9000" proxy = {"http":"http://{}:{}@{}".format(username, password, ADDRESS_DNS)} -
Why is 'b' being added to my Django app's varchar data after upgrading to Django 4.2?
I am migrating an application from Django1.11/Python2.7/Postgres9.2 to Django4.2/Python3.11/Postgres14.3 (FYI I am also migrating the data from postgres 9 to 14). I am running into an issue where I call a form where the varchar data that is displayed in my app gets a "b'" and "'" appended to the data displayed by the form. Example (John is now 'bJohn') and modifies the data in the postgres database by adding the "b'" and "'" to the data. I have tried to clean the data, removed migrations, dropped the database, etc. FYI when I type() the fields everything returns as type 'str', even after the b' is added to the data. Here is my Model class User(TimeStampedModel): number = models.CharField(max_length=6, primary_key=True, verbose_name="Number") moniker = models.CharField(max_length=32) first_name = models.CharField(max_length=32) last_name = models.CharField(max_length=32) full_name = models.CharField(max_length=128) department = models.CharField(max_length=32) location = models.CharField(max_length=32) employee_type = models.CharField(max_length=32) title = models.CharField(max_length=128, blank=True) mail = models.EmailField(max_length=32) Here is my form class UserForm(forms.ModelForm): class Meta: model = User fields = ['number', 'first_name', 'last_name', 'department', 'location', 'employee_type', ] labels = { 'number': _('Number'), 'first_name': _('First Name'), 'last_name': _('Last Name'), 'mail': _('E-Mail Address'), } Here how I call the form in my template. {% block mainblock %} <h1>System</h1> <p>Please select … -
Redirecting to post detail page after editing a comment in Django causes 'NoReverseMatch' error. What am I doing wrong?
I want to do 2 redirects with url having 1 pk is that possible? please help i am getting error I am working on a blog application. I have a views function for the user to edit his comment. my problem is this: when user clicks save button after editing, i can't redirect him to post detail page. my views.py @login_required def comment_edit(request, pk): comment = Comment.objects.get(id=pk) form = CommentUpdateForm(instance=comment) if request.method == 'POST': form = CommentUpdateForm(request.POST, instance=comment) if form.is_valid(): form.save() return redirect('blog-post-detail') context = {'form':form,} return render(request, 'comment_edit.html', context) @login_required def post_edit(request, pk): post = Post.objects.get(id=pk) if request.method == 'POST': form = PostUpdateForm(request.POST, instance=post) if form.is_valid(): form.save() return redirect('blog-post-detail', pk=post.id) else: form = PostUpdateForm(instance= post) context = { 'post': post, 'form': form, } return render(request, 'post_edit.html', context) my urls.py from django.urls import path from .import views urlpatterns=[ path('blogs/', views.blog, name="blog"), path('post_detail/<int:pk>/', views.post_detail, name="blog-post-detail"), path('post_edit/<int:pk>/', views.post_edit, name="blog-post-edit"), path('post_delete/<int:pk>/', views.post_delete, name="blog-post-delete"), path('comment_delete/<int:pk>/', views.comment_delete, name="blog-comment-delete"), path('comment_edit/<str:pk>/', views.comment_edit, name="blog-comment-edit"), ] my html: {% extends 'blog.html' %} {% load crispy_forms_tags %} {% block title %}Yorumu Düzenle{% endblock %} {% block content %} <div style="margin-top: 10%;" class="container"> <div class="row mt-5 pt-3 fluid"> <div class="col-md-8 offset-md-2"> <div class="card"> <div class="card-body"> <form method="POST"> {% csrf_token %} {{ … -
VSCode debugger in Django only hits once - on initial load
I am trying to make the debugger hit a breakpoint when Django handles a request. I set a breakpoint in a View and start the debugger in VSCode. The breakpoint get's hit when I start the app and continues when I press play. However, it never hit's the breakpoint again if I make requests to that view. It looks like the debugger works on load and then the code runs in the normal terminal and the debug console is just blank. So it seems like the code is not actually running inside the debugger. Any suggestions? { "version": "0.2.0", "configurations": [ { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}/src/python/.../manage.py", "args": [ "runserver", "--noreload", "--nothreading" ], "django": true, "justMyCode": true }, ] } # urls.py router.register("products", ProductViewSet) # products.py class ProductViewSet(viewsets.ReadOnlyModelViewSet): queryset = ... breakpoint() # Trying to hit a breakpoint here when a request is made serializer_class = ProductSerializer @extend_schema(request=None, responses=ProductPriceSerializer()) -
How can I ensure correct grouping in a Django subquery annotation?
When I'm writing Django Subquery expressions, sometimes I have no idea how Django is going to group the result. Example: subquery = ( RelatedModel.objects.filter( category="some_category", grandparentmodel=OuterRef("relatedmodel__grandparentmodel"), mymodel__created_at__date=OuterRef("created_at__date"), ) .values("grandparentmodel", "mymodel__created_at__date") .annotate(net=Sum("mymodel__amount")) .values("net")[:1] ) query = ( MyModel.objects.annotate( net=Coalesce( Subquery(subquery), Decimal("0.00") ) ) ) With this, my goal is to group a bunch of ParentModel instances (with category "some_category") by grandparentmodel and mymodel__created_at__date. This seems to work only if I include the .values("mymodel__created_at__date") before my annotation. If I do not include that before my annotation of net, the subquery still runs and just gives incorrect net. However, the .values("grandparentmodel") seems not required to get the correct grouping; I can exclude it and I still get the values I'm expecting. What's going on behind the scenes? How would I know to use a .values() call before my annotation to group correctly? How would I know what to include in said values() call? Is there some rule of thumb to follow when aggregating in subqueries? -
How to fix this issue in django & mysql It is impossible to change a nullable field 'description' on item to non-nullable without providing a default
i am having this problem where when i try to make migrations in python it shows this error -> It is impossible to change a nullable field 'description' on item to non-nullable without providing a default. This is because the database needs something to populate existing rows. Please select a fix: Provide a one-off default now (will be set on all existing rows with a null value for this column) Ignore for now. Existing rows that contain NULL values will have to be handled manually, for example with a RunPython or RunSQL operation. Quit and manually define a default value in models.py. Select an option: -
Problema al guardar los datos actualizados de una tabla de Django (Vinculada a MySQL) a través de un formulario HTML
estoy tratando de llevar a cabo la función de actualizar de mi CRUD, sin embargo cuando intento guardar los cambios me da un error indicando que el formulario fue invalido (Sin importar si se cambiaron o no los valores de los campos). Estoy utilizando Python con el framework Django junto a HTML y Bootstrap 5. El modelo que estoy implementando es este: #LIBRERIAS NECESARIAS PARA QUE TODO FUNCIONE CORRECTAMENTE from django.db import models from django import forms from django.contrib.auth.models import User #CREACIÓN DE LOS MODELOS class Arbol(models.Model): #Defino las opciones de estado ESTADO = [ ("AJOV","Árbol joven"), ("AADU","Árbol adulto"), ("AANC","Árbol anciano") ] #Defino las opciones de salud SALUD = [ ("ASAN","Árbol sano"), ("AHER","Árbol herido"), ("AENF","Árbol enfermo"), ("AMUE","Árbol muerto") ] #Campos que lleva la tabla en la base de datos id = models.AutoField(primary_key=True, verbose_name="Identificador") especie = models.CharField(max_length=100, null=True, verbose_name="Especie") # estado = forms.ChoiceField(choices=ESTADO, required=True, label="Estado") # salud = forms.ChoiceField(choices=SALUD, required=True, label="Salud") estado = models.CharField(max_length=20, choices=ESTADO, null=True, verbose_name="Estado") salud = models.CharField(max_length=20, choices=SALUD, null=True, verbose_name="Salud") edad = models.DecimalField(max_digits=10,decimal_places=2 ,null=True, verbose_name="Edad [Años]") altura = models.DecimalField(max_digits=10, decimal_places=2, null=True, verbose_name="Altura [Metros]") encargado = models.ForeignKey(User, on_delete=models.PROTECT, verbose_name="Encargado") #INFORMACIÓN DEL OBJ PRESENTADA EN EL ADMINISTRADOR (TO STRING) def __str__(self): info = f"Especie: {self.especie} - Estado: {self.estado} - Salud: … -
typeError: fromisoformat: argument must be str,
I trie many solutions from the internet nothing worked.. thanks in advance Error typeError: fromisoformat: argument must be str view.py def notes(request): now = datetime.datetime.now() month = now.month year = now.year cal = HTMLCalendar() events = Note.objects.filter(date_month=month, date_year=year) notes = Note.objects.all() return render(request, 'notes/home.html',{ 'cal': cal, 'events': events, } -
Why am I getting the 'Welcome to nginx!' page when I launch my Django app with Docker and Nginx?
My tech stack: Django, Gunicorn, Postgres, Nginx, Docker (and Docker Hub). I'm currently trying to deploy my web app, and when I launch my website with Docker, I get "Welcome to nginx!" page as a starting page. Here's the code of the docker-compose file that I use to launch my images: version: '3' services: db: image: sh1nkey/outtask1:latest ports: - "5432:5432" django: image: sh1nkey/django_outtask1:lastest ports: - "8000:8000" nginx: image: sh1nkey/outtask1_nginx:latest ports: - "80:80" Here's the Dockerfile code: FROM python:3.10 ENV PYTHONUNBUFFERED 1 WORKDIR /code COPY ./requirements.txt . RUN pip install --upgrade pip && pip install --upgrade setuptools wheel RUN pip install -r requirements.txt COPY . . EXPOSE 8000 Here's docker-compose file code i use to build images (i know this code sucks, so i'll gladly accept critique): version: '3.9' services: db: image: postgres volumes: - type: volume source: pg_data target: /var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres ports: - "5432:5432" expose: - 5432 django: image: django-docker:0.0.1 build: . command: sh -c "gunicorn --bind 0.0.0.0:8000 outtask.wsgi" # sh -c "gunicorn --bind 0.0.0.0:8000 outtask.wsgi" volumes: - type: bind source: . target: /outtask - type: volume source: static_data target: /outtask/static ports: - "8000:8000" expose: - 8000 environment: - DJANGO_SETTINGS_MODULE=outtask.settings depends_on: - db nginx: … -
Custom classes and views
I have set up the following custom class and am trying to output its contents into a Django view, however I keep hitting various Attribute and Type errors. I wondered if someone could point me in the right direction, please? Custom class from pickle import OBJ from urllib.request import HTTPPasswordMgr from django.shortcuts import render from django.http import request class Bloodcancer(): def __init__(self, my_symptoms=None, my_causes=None, my_treatments=None): self.symptoms = my_symptoms self.causes = my_causes self.treatments = my_treatments class AcuteMyeloidLeukemia(Bloodcancer): def my_symptoms(): symptomatology = { tuple({'a': "pale appearance",'b': "weakness or feeling tired", 'c': "shortness of breath", 'd': "easy brusing or bleeding",'e': "petechiae which are flat, pinpoint spots under the skin caused by bleeding", 'f': "loss of weight", 'g': "loss of appetite", 'h': "fever", 'i': "frequent minor infection"} ) } print (symptomatology) def my_causes(self): causes = ['age', 'being male', 'genes', 'environment', 'other bone marrow diseases'] return render(request, 'Healthcare/Conditions/Blood/Causes.html', {{causes}}) def my_treatments(self): treatments = ['induction therapy', 'consolidation therapy', 'chemotherapy', 'allogenic stem cell transplantation', 'central nervous system treatment', 'treatment of older and frail patients with AML', 'Treatment of refractory or relapsed AML', 'Supportive treatment'] return render(request, 'Healthcare/Conditions/Blood/Treatments.html', {{treatments}}) views.py from django.shortcuts import render from django.http import HttpResponseBadRequest, request from django.urls import path from Healthcare.Conditions.Blood.blood import AcuteMyeloidLeukemia as … -
Return object instead of string for FK field in SerializerMutation in Graphene Django
I have two models ProjectType and Project as follows class ProjectType(Base): name = models.CharField(max_length=100, unique=True) class Meta: db_table = 'project_types' def __str__(self): return self.name class Project(Base): name = models.CharField(max_length=100, unique=True) project_type = models.ForeignKey(ProjectType, on_delete=models.DO_NOTHING, related_name='related_projects') class Meta: db_table = 'projects' def __str__(self): return self.code and I have Mutations for both using SerializerMutation from Grapehene Django class ProjectTypeMutation(SerializerMutation): class Meta: serializer_class = ProjectTypeSerializer model_operation = ['create', 'update'] class ProjectMutation(SerializerMutation): class Meta: serializer_class = ProjectSerializer model_operation = ['create', 'update'] class Mutation(graphene.ObjectType): cudProjectType = ProjectTypeMutation.Field() cudProject = ProjectMutation.Field() When I perform a create mutation for project, I have to also specify the project_type. The resulting response also has the project_type but as a String. Not an object. Is there any way to get project_type back as an object? Current Mutation ⬇️ mutation{ cudProject(input: {name: "Project1" project_type: "1"}) { id name project_type } } Current Output ⬇️ { "data": { "cudProject": { "id": 200, "name": "Project1", "project_type": "1" } } } I want project_type to be an object which I can use as follows: Expected Mutation Request ⬇️ (This brings an error currently) mutation{ cudProject(input: {name: "Project1" project_type: "1"}) { id name project_type{ id name } } Expected Output ⬇️ { "data": { "cudProject": … -
Django and tailwind page responsiveness issues
I am trying to integrate tailwind with Django using django-tailwind library everything works fine only the page mobile design does not work properly so when I am on desktop and a resize (downsize) the window it works but when I use inspect element to see how the page look on phone size it does not work i am using Django-tailwind version 2.2 this is the result on inspect element (it shows 2 blog per row but it has to show only one) : this is the result on window resize (works fine): -
Empty results in dynamical form in Django
My views.py: from django.shortcuts import render from django.shortcuts import HttpResponse from .models import * from .forms import TestForm from django import forms def TestView(request,id): test = Tests.objects.get(id=id) queshions = Queshions.objects.filter(test=test) form = TestForm(queshions=queshions) if request.method == 'POST': print(request.POST) form = TestForm(data=request.POST, queshions=queshions) print(form) print(form.is_valid()) else: context = {'queshions':queshions,'test': test,'form':form } return render(request,'testview.html',context) My forms.py: from django import forms class TestForm(forms.Form): def __init__(self, *args, **kwargs): queshions = kwargs.pop('queshions') super(TestForm, self).__init__(*args, **kwargs) for queshion in queshions: self.fields[queshion.id] = forms.CharField(label=queshion.text) POST request is correct, but form.is_valid returns False, and when i am printing form it writes "This field is required." like it is empty -
Email verification after the user edits the email - Django
So, I'm trying to make a blog website. I'm with the authentication, and I'm struggling a bit with the security part. I'm trying to make email verification security a thing in my auth security. I've done all the basic stuff like user registration, login & logout functions, view profile, and edit profile. I have done the email verification part in the user registration, but I am somehow struggling a lot when trying to add email verification after users change their email. What I want my code to do is when a user edits his/her email, the code has to save the user's new email address temporarily and not change the email to the new one just then. I, instead, want the code to send an email to the old one (as the old one still is the recovery email address ... Additionally, I want the code to display the old email when clicked), asking for verification if he/she were the one to request to change the email. If the link provided is clicked then the email should change automatically with a message saying so, but if not then after 24 hours, deactivate the link. Oh, and I just wanted to … -
Django error Health checks failed with these codes: [502]
I'm trying to deploy a Django app on AWS Elastic beanstalk. I'm not an experienced tech guy but learning about AWS. I followed all the deployment steps till 'eb status'. Under EC2 > Target groups on AWS dashboard, Health status details are : Health checks failed with these codes: [502] How to troubleshoot this error so as to make the app run on the address provided by the CNAME of 'eb status' command? Tried many solutions from various stackoverflow posts but nothing seems to work. -
how to create a cycle approval?
I have an application made from the backend in django and from the frontend in nextjs, I have this models.py, you have to help me with the PurchaseOrders, ApprovalCycle and Approvalcycle models these 3 together regulate an approval cycle, I need to create a signals to make the status you change from the default value it currently has, which is given by the StatiPurchaseOrder class and you become approved when on the front-end side I'm going to use the function connected to the button, but this part of the frontend now let's leave it aside, let's focus on the backend, on the logic. Could you help me to write a signal that creates this approval? this is my signals @receiver(post_save, sender=ApprovazioniCiclo) def check_approvazione_ciclo(sender, instance, **kwargs): ciclo_approvazione = instance.purchase_order.ciclo_approvazione if ciclo_approvazione.check_approvazione(instance.purchase_order): # Il ciclo di approvazione è stato completato, quindi impostiamo lo stato del PurchaseOrder come 'Approvato' instance.purchase_order.stato = StatiPurchaseOrder.APPROVATO instance.purchase_order.save() -
django: How to defer TextField and localized variants of field from queryset including related models
When making the query to the model which has related models with large text fields, django loads all data in SQL query. How to defer automaticaly textfields, from main model and related in queryset? how to exclude from query fields like description, description_??, text, text_?? SELECT DISTINCT store_item.id, store_item.store_id, ..... store_item.product_id, store_item.price_in, store_item.price_out, store_item.count, product.id, product.name, product.name_uk, product.name_ru, product.name_en, product.manufacturer_id, ... product.description, product.description_uk, product.description_ru, product.description_en, product.text, product.text_uk, product.text_ru, product.text_en, ... product_manufacturer.id, product_manufacturer.action_id, product_manufacturer.name, product_manufacturer.slug, product_manufacturer.code, ... product_manufacturer.description, product_manufacturer.description_uk, product_manufacturer.description_ru, product_manufacturer.description_en, ... product_manufacturer.text, product_manufacturer.text_uk, product_manufacturer.text_ru, product_manufacturer.text_en, ... FROM store_item INNER JOIN product ON store_item.product_id = product.id LEFT OUTER JOIN product_manufacturer ON product.manufacturer_id = product_manufacturer.id ORDER BY product_manufacturer.name ASC, product.name ASC SELECT DISTINCT store_item.id, store_item.store_id, ..... store_item.product_id, store_item.price_in, store_item.price_out, store_item.count, product.id, product.name, product.name_uk, product.name_ru, product.name_en, product.manufacturer_id, ..... product_manufacturer.id, product_manufacturer.action_id, product_manufacturer.name, product_manufacturer.slug, product_manufacturer.code, FROM store_item INNER JOIN product ON store_item.product_id = product.id LEFT OUTER JOIN product_manufacturer ON product.manufacturer_id = product_manufacturer.id ORDER BY product_manufacturer.name ASC, product.name ASC -
How to handle user local timezone conversion for datetimes in Django forms/views/templates?
I'm having a problem with timezones in Django. I'm not sure how to go about storing datetime as UTC, but also displaying and accepting datetimes from the user as their local timezone. I'm planning to include a timezone setting option for the user that would be stored in the database and could be used to decide which timezone to accept input and display output as, but I'd like to know if there is way to automate the conversion for both directions that could be easily implemented without needing to manually add a piece of conversion logic (or the to every existing form/view/template/etc. to display the correct time. Something like how a Mixin works for views that can be easily applied to handle the conversion. -
how i can convert a docx to pdf using python on a heroku app?
I have a Django app running on Heroku, and I'm trying different ways to convert a DOCX file to PDF. Are there any methods available for accomplishing this? I would greatly appreciate some assistance. i've tried install libreoffice with buildpacks, but logs return "FileNotFoundError: [Errno 2] No such file or directory: 'libreoffice'" -
Django with docker-compose : OperationalError: FATAL: database "" does not exist
I am currently on a project based around react in the frontend, django in the backend, postgresql for the database and nginx for the reverse proxy. Everything is linked up with a Docker-compose file. My previous question asked in this forum was about linking the database to the django backend. Altough it was resolved, I have another problem now : when I try to create a superuser account in the container, the container responds me with this error : django.db.utils.OperationalError: FATAL: database "" does not exist One of my first try to solve it was to check if the database is correctly created. Unfortunately I do not why but neither the database nor the role is created. Docker-compose.yaml file : version: '3.8' services: nginx: container_name: app_server_conf build: context: ./ dockerfile: ./Dockerfile ports: - "80:80" depends_on: - backend environment: - PUBLIC_URL=127.0.0.1 networks: app_network: volumes: - staticfiles:/staticfiles backend: container_name: backend ports: - "8000:8000" build: context: backend dockerfile: ./Dockerfile command: "make run" env_file: - .env depends_on: - database networks: - app_network volumes: - staticfiles:/app/staticfiles/ database: container_name: database build: context: ./postgres/ dockerfile: ./Dockerfile command: ['postgres', "-c", 'log_statement=all'] ports: - "5432:5432" restart: always volumes: - postgres_data/:/var/lib/postgresql/data environment: - POSTGRES_DB= - POSTGRES_USER= - POSTGRES_PASSWORD= networks: - … -
Django: 'list' object has no attribute '__dict__'
I try to implement modelformset_factory but got an error on form_valid(). 'list' object has no attribute 'dict' Neverthless all formset are correctly registered in database what is wrong with return super().form_valid(formset)? TraitementFormSet = modelformset_factory( Traitement, form=TraitementForm, fields=('arv_num','arv_reg','arv_reg_pre','arv_deb_dat','arv_fin_dat','arv_enc','arv_rai_eff','arv_rai_vir','arv_rai_gro','arv_rai_per','arv_rai_inc','arv_rai_aut','arv_rai_aut_pre'), extra=1 ) @method_decorator(login_required, name="dispatch") class TraitementFormSetCreate(SuccessMessageMixin, CreateView): model = Traitement form_class = TraitementForm template_name = "ecrf/traitements_form.html" success_message = "Fiche Traitement créée." success_url = reverse_lazy('ecrf:inclusion_list') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['formset'] = TraitementFormSet(queryset=Traitement.objects.filter(pat=self.kwargs['pk'])) context['action'] = 'create' context['patient'] = Patient.objects.get(ide=self.kwargs['pk']) context['model_name'] = self.model._meta.model_name context['is_locked'] = self.object.ver if self.object else None return context def post(self, request, *args, **kwargs): formset = TraitementFormSet(request.POST) if formset.is_valid(): return self.form_valid(formset) def form_valid(self, formset): print('valid',type(formset)) patient = Patient.objects.get(ide=self.kwargs["pk"]) traitements = formset.save(commit=False) for traitement in traitements: traitement.pat = patient traitement.arv_sai_log = self.request.user.username traitement.save() return super().form_valid(formset) def form_invalid(self, formset): print('invalid',formset.errors) context = self.get_context_data(formset=formset) return self.render_to_response(context) -
Getting 401 error instead of being redirected to login page with ms_identity_web.login_required decorator in Django app
I have a django app which uses the ms_identity_web repository (https://github.com/Azure-Samples/ms-identity-python-samples-common) to authenticate against an Azure Active Directory. Authentication works fine, but when i directly (not logged in) browse to a page that requires the user to be logged in (using the provided @ms_identity_web.login_required decorator) I get a 401 error instead of being redirected to my login page (as i'm used to with the Django @login_required decorator and LOGIN_URL setting's variable). As I cannot find much documentation on this topic I resolved to writing a custom middleware (which sounds like it shouldn't be neccesary, but again; i couldn't find an option like MS_LOGIN_URL that should/is included in the repo). Where I'm stuck is that I need to find out whether the requested page/path requires login or not (basically if it has the decorator or not). The best solution would be one that's included in the library of course, but other solutions are welcome. I followed the tutorial on: https://learn.microsoft.com/en-us/training/modules/msid-django-web-app-sign-in/2-register-web-app-in-azure-active-directory-tenant In my settings.py I added: from ms_identity_web.configuration import AADConfig from ms_identity_web import IdentityWebPython AAD_CONFIG = AADConfig.parse_json(file_path='aad.config.json') MS_IDENTITY_WEB = IdentityWebPython(AAD_CONFIG) ERROR_TEMPLATE = 'auth/{}.html` I have a view with the decorator: ms_identity_web = settings.MS_IDENTITY_WEB @ms_identity_web.login_required def view_data(request): context = { 'data': 'test' } … -
How to show clusters in a map?
I'm building a Flutter map and I want show clusters that are storred in a Django server database. I want to do a similar view as this but instead of showing all the users location, I want to show the surface that these users are occupying (the surface of a cluster). PS: I'm using a package named flutter_map to display the map. -
Save to db only if changing fields
Is there a better way of doing the following in Django: obj = Thing.objects.get(name=name) if obj.a != a or obj.b != b: obj.a = a obj.b = b obj.save() So I wish to save if ether a or b has become invalid and I can’t make any change to the save implementation. And I’d like to stick to using the model instance rather than solving this using a query set. -
Database not updating between tests in Django
I'm trying to run a create test followed by an update, however on the second test I'm unable to find the object created in the first test. I've realised that this is because the object is not added to the DB until after both tests have run. Does anyone know why this is? And how I can run a create test, followed by an update test that uses the object created in the create test? from unittest import TestCase class QuantsTests(TestCase): def setUp(self): self.factory = RequestFactory() def test_create_object(self): object = Object() object.name = "123456789" object.save() def test_update_object(self): Object.objects.filter(name="123456789") Error: object.models.Model.DoesNotExist: Object matching query does not exist.