Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Register button won't disappear when user logs in(django, html, css, bootstrap)
Why is this code showing the register button regardless of whether or not a user is logged in? (this is for Django with bootstrap) ''' {% if user.is_authenticated %} <li class="nav-item"> <span class="navbar-text"}">Study hard, {{ user.username }}.</span> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'users:logout' %}">Log out</a> </li> {% else %} <li class="nav-item"> <a class="nav-link" href="{% url 'users:register' %}">Register</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'users:login' %}">Log in</a></li>''' -
Django displays source code instead of web page
I am new to django. Any help will be appreciated. It displays source code instead of web page. To be specific the base page (base.html). What I want is to use the data from patient details and doctors detail as they are from different groups. I think that the problem is when i pass my dictionary. Views.py def booking(request): if not request.user.is_active: messages.success( request, ("In order to book an appointment you must login first")) return redirect('login') doctor_details = Doctor.objects.all() f = {'doctor_details': doctor_details} g = request.user.groups.all()[0].name if g == 'Patient': patient_details = Patient.objects.all().filter(EmailAddress=request.user) d = {'patient_details': patient_details} return render(request, 'booking.html', f, d) Html {% extends 'base.html' %} {% block content %} {% load static %} <div class="loginContainer"> <div class="img"> <img src="{% static 'image/booking.svg' %}"> </div> <div class="login-content"> {% for d in patient_details %} <form method="POST" id="signupForm"> {% for f in doctors_details %} {% csrf_token %} <h2 class="title">Booking form</h2> <div class="input-div one"> <div class="i"> <ion-icon name="person-circle"></ion-icon> </div> <div class="div"> <h5>Patient ID: PID - {{d.id}}</h5> </div> </div> <div class="input-div one"> <div class="i"> <ion-icon name="person"></ion-icon> </div> <div class="div"> <h5>Name: {{d.FirstName}} {{d.LastName}}</h5> </div> </div> <div class="input-div one"> <div class="i"> <ion-icon name="business"></ion-icon> </div> <div class="div"> <h5>Department</h5> <input type="text" class="input" name="age" required> </div> </div> <div class="input-div … -
Save multiple objects in Django DRF ViewSet create
I have a model in Django which stores some basic information. class Inventory(models.Model): created_at = models.DateTimeField(auto_now_add=True) added_by = models.ForeignKey(User, on_delete=models.SET("anonymous"), name = models.CharField(max_length=100, unique=True) nickname = models.CharField(max_length=100, blank=True, null=True) manufacturer = models.ForeignKey(InventoryManufacturer, on_delete=models.PROTECT) comment = models.TextField(max_length=500, blank=True, null=True) link = models.URLField(max_length=100, blank=True, null=True) class Meta: unique_together = ('manufacturer', 'manufacturer_part_no') I have another table which stores images for this model: class InventoryImages(models.Model): created_at = models.DateTimeField(auto_now_add=True) added_by = models.ForeignKey(User, on_delete=models.SET("anonymous"), blank=True, null=True) file = ImageField(blank=True, default='', upload_to='inventory/images/%Y/%m/') primary = models.BooleanField(default=False) order = models.IntegerField(blank=True, null=True) item = models.ForeignKey(Inventory, on_delete=models.CASCADE, blank=True, null=True, related_name='images') What is the right way to handle a scenario where a user can fill out a form (where you can set the Inventory model fields) and also upload multiple images. What I did now that the user can upload images everytime on this form, the image gets uploaded but the item Foreign Key stays null. When the user submits the form, the ForeignKey is set for each uploaded image. The scenario when a image gets discarded (no form submission) is handled. This is what I did now: def create(self, request, *args, **kwargs): # Create Inventory item serializer = CreateInventoryItemSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save(added_by=self.request.user, updated_by=self.request.user) # Save properties inventory_id = serializer.data['id'] # Add id … -
Django - convert datetime string to timezone aware datetime object
So I have a a list of dates and times as a string "2022-01-23 21:30” that I need to import into my Django Application My Django server UTC, however the strings are intended to be UTC+2. So if I import it directly, Django would assume it’s UTC and then the timestamp would saved as 2022-01-23 21:30 (UTC), where in reality it should be converted to 2022-01-23 19:30 (UTC). Is there a specific way I should format it before saving the object in a Django DateTimeField so it will become timezone aware? Thanks in advance. -
formset function update view does not save the forms because the id is missing
I have a view to update 6 of my formset only that the click of the send button gives me the error that the id of each form is missing ... how do you fix it? When I have to create formset there are never problems with the id... Can anyone tell me where I'm wrong? I leave my code below view @login_required def PianoSingleUpdateView(request, id): piano = models.Piano.objects.get(single_piano__id = id) piano_sett = models.PianoSingleDay.objects.get(id = id) dato = models.PianoDay.objects.filter( piano_day = piano_sett) DatiFormSet = modelformset_factory(models.PianoDay, extra = 0, fields=('id', 'kcal', 'carboidrati', 'proteine', 'grassi')) if request.method == 'POST': dati_formset = DatiFormSet(request.POST, request.FILES, queryset = dato) if dati_formset.is_valid(): for dato in dati_formset: dato.save() return redirect('gestione-piano', id = piano.id) else: dati_formset = DatiFormSet(queryset = dato) context = {'piano': piano, 'piano_sett': piano_sett, 'dati_formset': dati_formset} return render(request, 'crud/update/update_piano_giornaliero.html', context) models class Piano(models.Model): nome_piano = models.CharField(max_length=100) data_inizio = models.DateField() data_fine = models.DateField() utente_piano = models.ForeignKey( User, on_delete = models.CASCADE, related_name = 'utente_piano' ) def __str__(self): return self.nome_piano class PianoSingleDay(models.Model): giorni_settimana_scelta = [ ("1","Lunedì"), ("2","Martedì"), ("3","Mercoledì"), ("4","Giovedì"), ("5","Venerdì"), ("6","Sabato"), ("7","Domenica") ] giorni_settimana = models.CharField( choices = giorni_settimana_scelta, max_length = 300 ) single_piano = models.ForeignKey( Piano, on_delete = models.CASCADE, related_name = 'single_piano' ) def __str__(self): return self.giorni_settimana class … -
Parse File While Upload in Django
May I know how to parse XML tags from XML files while upload in django ? I wanted to make sure below things :- Once I upload file from GUI i wanted to parse data from it and store somewhere in models in django and then land file in media storage directory -
CSRF cookie is not set in Django after API call
I have a small Django web app that allows you to log in with a platform using their API. The user is able to log in, but the callback from the log in returns this error: Forbidden (CSRF cookie not set.): /account/platforms/apicallback/ on my server output. I believe that the callback does route to the correct url in my web app, but when it gets to the view associated with it, the CSRF cookie error arises. My request code is below: params = { "app_name": "My App", "scope": scope, "user_id": request.user.id, "return_url": redirect_uri, "callback_url": "https://www.myapp.co.uk/account/platforms/apicallback", "state": {"platform":"api"} } query_string = urlencode(params) url = "%s%s?%s" % (auth_url, query_string) return redirect(url) Here is the urls.py file that contains the callback url: urlpatterns = [ path(r'apicallback/', views.apicallback, name='apicallback'), ] Here is the views.py file with the view for the callback url: @login_required def apicallback(request): consumer_key = request.GET.get('consumer_key') consumer_secret = request.GET.get('consumer_secret') I have got two APIs already working with my web app that both use OAuth2.0, and I haven't come into this issue before. Any ideas on how to fix it without disabling CSRF cookies. Thank you -
Can not use POST method with Django 4 Rest Framework
I'm having an issue with a new django 4 app not processing or not allowing POST method. I used to bypass this in Django version 3 by adding a trailing slash "/" to the end of url in Postman API Tester like http://127.0.0.1:8000/api/didipay/ instead of http://127.0.0.1:8000/api/didipay . But now in my Django 4 API I completed the url with the slash but POST method is still not processing the data. It gives me a "500 internal server error" and I don't understand where it is coming from. The GET method is rather giving an empty array which is normal because I've not inserted any data yet in the database. I'm using venv, Django 4 Rest framework, serializer, viewSet and these is my models and API urls configurations: //Serialize.py from rest_framework.decorators import permission_classes from didipay_app.models import Didipay_app from rest_framework import viewsets, permissions from .serializers import Didipay_appSerializer class Didipay_appViewSet(viewsets.ModelViewSet): queryset = Didipay_app.objects.all() permission_classes = [ permissions.AllowAny ] serializer_class = Didipay_appSerializer // Project folder's urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('didipay_app.urls')), ] // App folder's urls.py from rest_framework import routers, urlpatterns from .api import Didipay_appViewSet router = routers.DefaultRouter() router.register('api/didipay', Didipay_appViewSet, 'didipay') urlpatterns = router.urls The … -
Python Paramiko "exec_command" does not execute - Django
I am facing an issue with the Python Paramiko library in my Django Application This is a function I have written to create an SFTP connection: def createSFTPConnection(request,temp_pwd): ssh=paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) user = User.objects.get(username=request.user) ssh.connect(hostname=temp_host,username=user.username,password=temp_pwd,port=22) sftp_client=ssh.open_sftp() return ssh,user,sftp_client This just returns me the variable for ssh, the username, and sftp_client Then I execute a command on the remote server using this code - ssh,user,sftp_client=createSFTPConnection(request,temp_pwd) # passes the password on that server for the user for creating the connection cmd_to_execute="(cd "+temporary_path+"; sh temp.sh"+" "+var1+" "+var2+")" # executing a shell script by passing it 2 variables stdin, stdout, stderr = ssh.exec_command(cmd_to_execute) # actual call print("stderr: ", stderr.readlines()) print("pwd: ", stdout.readlines()) Now, this code works fine and executes the script "temp.sh" on the remote server, but it takes a lot of time as I am returning stdin, stdout and stderr and printing them on the console But, since I don't want that I removed the readlines() calls from there making my code look like this - cmd_to_execute="(cd "+temporary_path+"; sh temp.sh"+" "+var1+" "+var2+")" stdin, stdout, stderr = ssh.exec_command(cmd_to_execute) # actual call But for some reason, this code just doesn't execute on the remote server after removing the readlines() calls Thus, making me think that exec_command … -
From where Django takes the paramenters for "field_names" and "values" in the "from_db" method?
Model class has a method from_db which accepts 3 parameters: @classmethod def from_db(cls, db, field_names, values): Where the arguments that Django passes as field_names, values come from? I need to use them in a different custom method. Thanks in advance for suggestions or solutions. -
Django Form.errors can not display in templates
Django form validation. I'm trying to submit the data form but form.errors can not display in the templates. views def registerUser(request): page = 'register' form = CustomUserCreationForm() if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.username = user.username.lower() user.save() messages.success(request, 'User account was created!') login(request, user) return redirect('edit-account') else: messages.success( request, 'An error has occurred during registration') context = {'page': page, 'form': form} return render(request, 'users/login_register.html', context) template form <form method="POST" action="{% url 'register' %}" class="form auth__form"> {% csrf_token %} {% for field in form %} <div class="form__field"> <label for="formInput#text">{{field.label}}</label> {{field}} <!-- {% if field.help_text %} <small>{{field.help_text}}</small> {% endif %} --> {% for error in field.errors %} <p style="color: red;">{{error}}</p> {% endfor %} </div> {% endfor %} <div class="auth__actions"> <input class="btn btn--sub btn--lg" type="submit" value="Sign In" /> </div> </form> I have not been able to understand why the error message can not display. any help is apriciated. -
Django Models Multiple Field Saving
I'm trying to create an object in my Order model. My js return a list of multiple values for Model database however I can not save multiple values that I received from ajax as a list. I see it's an array in js and a list in django but it's not happening. I've tried ManyToManyField instead of ForeignKey for my Order model model field, but that did not work too. Is there any way to save multiple values (list) that are already objects in my other models? models.py from django.db import models class Car(models.Model): name = models.CharField(max_length=80) country = models.CharField(max_length=100) def __str__(self): return str(self.name) class Model(models.Model): name = models.CharField(max_length=50) car = models.ForeignKey(Car, on_delete=models.CASCADE) def __str__(self): return f"{self.car}-{self.name}" class Order(models.Model): car = models.ForeignKey(Car, on_delete=models.CASCADE) model = models.ForeignKey(Model, on_delete=models.CASCADE) def __str__(self): return str(self.pk) views.py def create_order(request): if request.method == 'POST': print("***", request.POST) my_car_id = request.POST.get('car') my_model_id = request.POST.getlist('model[]') print("***", my_car_id, my_model_id) print("***", type(my_car_id), type(my_model_id)) car_obj = models.Car.objects.get(id=my_car_id) model_obj = models.Model.objects.get(id=my_model_id) print("obj", car_obj, model_obj) models.Order.objects.create(car=car_obj, model=model_obj) return JsonResponse({'created':True}) return JsonResponse({'created':False}) html <form id="car-form"> {% csrf_token %} <div class="row"> <div class="col"> <label for="cars-data-box">Choose a car</label> <select style="width: 15rem;" class="form-control" id="cars-data-box"> <option value="---">---</option> </select> </div> <div class="col"> <label for="models-data-box">Choose a model</label> <select multiple style="width: 15rem;" … -
Python Django Static not showing
I tried many solutions available in stock overflow too but non of it solved my problems.Django is my very first framework right after learning HTML,CSS,python(basics) I don't know what I am doing wrong please help me fix it here is my code Here is my folder structure: [folder structure][1] Here is my settings,URL,HTML code STATICFILES_DIR=[ os.path.join(BASE_DIR,"static") #BASE_DIR/'static' ] from django.urls import path from . import views from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns=[ path('', views.home, name='home'), path('customer',views.customer,name='customer'), path('products',views.products,name='products') ] urlpatterns += staticfiles_urlpatterns() {% load static %} <!DOCTYPE HTML> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Dash Board</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <link type="text/css" rel="stylesheet" href="{% static 'css/main.css' %}"> </head> <body> {% include "navbar.html" %} {% block content%} {% endblock %} <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js" integrity="sha384-7+zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossorigin="anonymous"></script> </body> </html>``` [1]: https://i.stack.imgur.com/65Z9x.png -
Django & React - 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*'
The error I get on the react console is Access to XMLHttpRequest at 'http://127.0.0.1/api/analyse/' from origin 'http://localhost' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Here are my Django settings ALLOWED_HOSTS = ['localhost', 'http://localhost', '127.0.0.1'] CORS_ALLOWED_ORIGINS = ['http://localhost', 'localhost', 'http://127.0.0.1' ] CORS_ORIGIN_WHITELIST = ['localhost', 'http://localhost', 'http://127.0.0.1'] CSRF_TRUSTED_ORIGINS = [ 'localhost', 'http://localhost', '127.0.0.1'] INSTALLED_APPS = ['corsheaders',] MIDDLEWARE = ['corsheaders.middleware.CorsMiddleware',] The axios.post is axios.post(ip_address, formData, { headers: { 'accept': 'application/json', 'content-type': 'multipart/form-data' }, This seems to be a common problem and many others had it before but not sure what did I do wrong. Can someone please help? -
Django custom validation AFTER to_internal_value
I am doing a business logic heavy project and uncertainty of data passed to validate function adds unnecessary extra work. For example I am not sure about date formats and ids/objects in PrimaryKeyRelatedFields Is there any way to run validations after converting fields to internal values? -
Django - Populating Edit/Update Form With an Object's Preexisting Data
I have an edit/update values form in Django, in which you need to choose the object you want to change its details from a drop down menu and then enter the new information you wanted to edit/update. When you choose an object from the dropdown menu the form looks like this: I am trying to populate the edit form with the pre existing fields of the object that I chose from the dropdown menu to make it easier to make changes. it should look like this screenshot: Any ideas how I can achieve that? Views.py Code: def tasks(request): if request.user.is_superuser: context = { 'tasks':Task.objects.all(), 'title': 'Tasks', 'addForm':AddNewTask(prefix = 'add'), 'editForm':EditTask(prefix = 'edit'), } else: context = { 'tasks':Task.objects.filter(created_by=request.user), 'title': 'Tasks', 'addForm':AddNewTask(prefix = 'add'), 'editForm':EditTask(prefix = 'edit'), } if request.method =='POST': if 'addNew'in request.POST: addForm = AddNewTask(request.POST,prefix = 'add') if addForm.is_valid(): task = addForm.save(commit=False) task.created_by = request.user task.save() messages.success(request, f' Task Created Successfully ') else: messages.warning(request, 'Something Went Wrong !') elif 'editExisting' in request.POST: editForm = EditTask(request.POST,prefix = 'edit') if editForm.is_valid(): taskID = editForm.cleaned_data['existing_task'].id new_title = editForm.cleaned_data['title'] new_desc = editForm.cleaned_data['description'] new_status = editForm.cleaned_data['status'] object = Task.objects.get(id=taskID) object.title = new_title object.description = new_desc object.status = new_status object.save() messages.success(request, f'Task #{taskID} Has Been … -
ImportError: cannot import name 'gTTS' from 'gtts'
I want to use the gtts library over my django project so i also installed django-gtts. The command "from gtts import gTTS" runs fine when I run it in a virtual environment in an empty folder, but the moment i install Django or django-gtts it starts giving me the error ImportError: cannot import name 'gTTS' from 'gtts' (/Users/amay/Desktop/untitled folder 2/tts/lib/python3.10/site-packages/gtts/__init__.py) asgiref==3.4.1 certifi==2021.10.8 charset-normalizer==2.0.10 click==8.0.3 Django==4.0.1 Django-Gtts==0.4 gTTS==2.2.3 idna==3.3 requests==2.27.1 six==1.16.0 sqlparse==0.4.2 urllib3==1.26.8 These are all the Dependencies in my Project and i am Running it on my Mac OS System. What can be the possible error? Is the gTTS module conflicting with some other dependency? -
GeoDjango Admin displaying openlayers map instead of open street map in Admin
i am have enabled everything needed to work with spatial data at the database and django setting level, my profile model has a default_location field that is a PointField. as shown below. from django.contrib.gis import models class Profile(models.Model): ... default_location = models.PointField() i registered the profile model as an inline to be viewed and edited from within a User model (one-to-one relationship between user and profile).code shown below class ProfileInline(StackedInline): model = models.Profile class NewUserAdmin(admin.GISModelAdmin): gis_widget = OSMWidget inlines = [ProfileInline] admin.site.unregister(models.User) admin.site.register(models.User, NewUserAdmin) however i keep getting a openlayer map in my django admin page please can anyone suggest a fix to this. i need open street map because of it detailed street feature. -
Django submitting two forms cannot assign instance error
I have the following models/forms/view in which I have managed to submit to two different models as follows: Models class Account(models.Model): username = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=150) actflag = models.CharField(max_length=1, blank=True) acttime = models.DateTimeField(blank=True, null=True) comments = models.TextField(_('comments'), max_length=500, blank=True) def __str__(self): return self.name class ISIN(models.Model): code = models.CharField(max_length=12) account_name = models.ForeignKey(Account, on_delete=models.SET_NULL, null=True) actflag = models.CharField(max_length=1, blank=True) acttime = models.DateTimeField(blank=True, null=True) def __str__(self): return self.code Forms from apps.portfolio.models import Account, ISIN class PortfolioForm(forms.ModelForm): class Meta: model = Account fields = ['name', 'comments'] class IdentifierForm(forms.ModelForm): class Meta: model = ISIN fields = ['code'] View def portfolios(request): if request.user.is_authenticated: if request.POST: fm = PortfolioForm(request.POST) fm2 = IdentifierForm(request.POST) if fm.is_valid(): messages.success(request, 'Portfolio has been created.') account = fm.save(commit=False) account.username = request.user account.acttime = timezone.now() account.actflag = 'I' account.save() isin = fm2.save(commit=False) #isin.account_name = account.name isin.acttime = timezone.now() isin.actflag = 'I' isin.save() return redirect('portfolios') else: fm = PortfolioForm() fm2 = IdentifierForm() context = {"name": request.user, "form": fm, "form2": fm2} return render(request, 'portfolios.html', context) else: return redirect('login') However, you will notice the commented line in my view: isin.account_name = account.name, when I uncomment this line and try to submit the forms again I get the following error: Cannot assign "'test'": "ISIN.account_name" must … -
Django not logging all errors on production
My Django app is locally properly logging and emailing errors. However, on production, I'm only getting 'Invalid HTTP_HOST header' errors in both the log file and my inbox. Every other error is not logged in the django log nor is it emailed to me. I'm not sure what could cause this or how to continue investigating the issue. I've tried some things with this test request: def test(request): logging.debug('debug test message') // Appears in log file from django.core.mail import mail_admins mail_admins('test error', 'test error via call to mail_admins()') // Arrives in my inbox raise Appointment.DoesNotExist // On production, Does not appear in log file or in inbox. Behaves as expected locally. Could it possibly be something to do with directory and file permissions? I would expect logging not to work at all in that case. My logging settings for both local and production: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '%(levelname)s %(message)s' }, 'csv_formatter': { 'format': '%(levelname)s;%(asctime)s;%(message)s' } }, 'handlers': { 'null': { 'level': 'DEBUG', 'class': 'logging.NullHandler', }, 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'verbose' }, 'default': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'maxBytes': 1024 … -
Django testing of views.py and model.py
I am new to django testing am doing the testing for my views.py file which cintain alot oif classes Here we are take one of the class among the others the views.py file looks like class AssignSubFarmer(viewsets.ViewSet): permission_classes = [permissions.AllowAny] http_method_names = ['patch', 'post'] serializer_class = BatchSerializer queryset = Farm.objects.all() def create(self, request, *args, **kwargs): header = {'Content-Type': 'application/json', 'Authorization': request.headers['Authorization']} farm_id = request.data.get('farm_id', None) batch_id = request.data.get('batch_id', None) subfarmer_id = request.data.get('user_id', None) mobile = request.data.get('mobile', None) name = request.data.get('name', None) document_photo = request.data.get('document_photo', None) user_type = request.data.get('user_type', None) aadhar_number = request.data.get('aadhar_number', None) pancard = request.data.get('pancard', None) voter_id = request.data.get('voter_id', None) gst_no = request.data.get('gst_no', None) primary_user_id = request.data.get('primary_user_id', None) if not subfarmer_id: payload = { "name": name, "mobile": mobile, "document_photo": document_photo, "user_type": user_type, "aadhar_number": aadhar_number, "pancard": pancard, "voter_id": voter_id, "gst_no": gst_no } response = requests.post(url=settings.CREATE_SUB_FARMER.format(primary_user_id), data=json.dumps(payload), headers=header) data = json.loads(response.content) secondary_user_id = None if not data['error'] and data['data']: secondary_user_id = data['data'].get('secondary_user_tbl_id', None) else: return Response({"message": data['message'], "error": data['error']}, status=status.HTTP_200_OK) subfarmer_id = 0 if secondary_user_id: subfarmer_id = secondary_user_id if farm_id and subfarmer_id: Batch.objects.filter(farm_id=farm_id).update(sub_farmer_id=subfarmer_id) elif batch_id and subfarmer_id: Batch.objects.filter(id=batch_id).update(sub_farmer_id=subfarmer_id) elif farm_id: Batch.objects.filter(farm_id=farm_id).update(sub_farmer_id=subfarmer_id) elif batch_id: Batch.objects.filter(id=batch_id).update(sub_farmer_id=subfarmer_id) return Response({"message": "Successfully updated", "error": "False"}, status=status.HTTP_200_OK) and when I am doin the testing for this class … -
How to render Django template after ajax call
Iam Building a application that renders a group of cards based on options clicked by user, iam using ajax on option click so that cards appear without page reload,but the problem is i cannot render the cards into my page,iam passing calculated values to frontend as django context using return render(request,'base.html',{'context':context}) Ajax: <script > function sendData(date){ $.ajax({ type : "POST", url: "", data: { date : date, csrfmiddlewaretoken:'{{ csrf_token }}', click:'click' }, }); return false; } view.py: def datepicker(request): if 'click' in request.POST: return render(request,'datepicker.html',{'dates':availabe_dates,'time':time}) return render(request,'datepicker.html',{'dates':availabe_dates,'time':['choose a date']}) I have tried giving: <div class="card-body"> {% for t in time %} <p>{{t}}</p> {% endfor %} </div> Only choose a date is shown instead of cards.I am sure that if 'click' in request.POST: is runned as i have tried giving some print statements Please Help as iam new to Ajax and Django -
I get 400 bad request when refreshing django-simple-jwt token
I am getting 400 bad request when I request a new token. It throws an error saying that refresh field is required. my code: export const refreshToken = (token) => { let object = { refresh: token, }; return (dispatch) => { api .post(TOKEN_REFRESH_ENDPOINT, object) .then((response) => { dispatch(refreshSuccess(response.data)); }) .catch((error) => { dispatch(refreshFail(error.message)); }); }; }; React.useEffect(() => { let refreshToken = Cookies.get(TOKEN_REFRESH_NAME); let timer = setTimeout( () => dispatch(action.account.refreshToken(refreshToken)), 2 * 1000 ); return () => { clearTimeout(timer); }; }, [dispatch]); What am I doing wrong? -
Django form with formset between three models
I have three models: Experiment, Label and LabelMappings while LabelMappings is connecting Devices with Labels. I want to create ExperimentForm but don't know how to add Label field to it using inline formset. I am using ClassBasedViews but couldn't figure out how to save Labels and build this relationship in backend class Experiment(models.Model): name = models.CharField(max_length=255) comment = models.TextField(blank=True, null=True) class Label(models.Model): name = models.CharField(max_length=255) comment = models.CharField(max_length=255, blank=True, null=True) class LabelMappings(models.Model): experiment = models.OneToOneField(Device, models.DO_NOTHING) label = models.ForeignKey(Location, models.DO_NOTHING) I thought about somethinglike LabelMappingFormSet = inlineformset_factory(Experiment, LabelMapping, form=LabelMappingForm, extra=1 ) LabelFormSet = inlineformset_factory(LabelMappingForm, Label, form=LabelForm, extra=1 ) but i didn't work out. -
How to capture "close browser windows" and then update a DataBase item with Django?
first of all happy new year! I am starting to learn Django, sorry if the question is too obvious. Context: I have a web aplication in Django, this aplication is a dashboard where the users can verify and validate the recognition made by an AI of each part of an invoice (prices, taxes...). The user can manually review this recognition and consequently validate if everything is correct. Situation: Now when a user to do click on the verify button redirect to another view. This new view is a Django template with a iframe. This Django view executes a function which update the status of the item to '31.Verificando usuario' in the DB. urls.py: path('verification/<int:id>/', views.VerificationPage, name="fci-verification" ) views.py: def VerificationPage (request, id): invoice= Invoice.objects.get(id=id) url= invoice.verification_url invoice_id = invoice.id status = '31.Verificando usuario' message = _('Invoice in web verification') try: change_invoice_status(invoice_id, status, message) except Exception as e: capture_exception(e) return render(request, "fci_verification.html", {'verification_url': url,'invoice_id': id}) When this user click on "verified" into iframe, I catch this event with window.addEventListener("message", receiveMessage, false); and update to new status. Problem: If the user close tab or browser, item status stays as "31.Verificando usuario" and another user cannot review this invoice. **How can I capture …