Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why am I seeing an NGINX 502 error in Chrome, only on MacOS?
I have a very strange issue happening. Multiple users have reported it, across multiple computers, and multiple sites. They keep getting an NGINX 502 error. It only occurs on Google Chrome. It has only been reported from users using MacOS. I have not been able to recreate the issue I haven't found anything in logs, aside from I can see the access failure. The only commonality between the sites, is they have all been a Django/NGINX/Uwsgi stack on CentOS. The issue is not present if the user switches to incognito. The issue persists if the website cache is cleared. The issue disappears if the entire browser cache is cleared. One site is new, the other is old and has not had a configuration change since the problem began. The problem is sporadic, and seemingly random. First noted in the past ~1 month. Any thoughts on this would be helpful. Since I can't recreate the issue, I am having a hard time troubleshooting. Thanks in advance. -
Django Select2 field query return no select options
On a Django model, I have a foreign key field 'owner', refer to User model. I have a view class and form class for the model instance creation page. I made the form 'owner' field using select2 widget as below. All worked fine. class OwnerWidget(ModelSelect2Widget): search_fields = ["name__istartswith", "email__icontains",] Now I changed the page to use bootstrap modal. All other model fields behaved okay but not the 'owner' field: when I type in search characters like 'te', it start to send query to the server, but server returned 404 not found. See log below. "GET /select2/fields/auto.json?term=te&_type=query&q=te HTTP/1.1" 404 2699 I have nowhere configured the path '/select2/fields/auto.json'. I guess it's select2 default path. Did I miss anything on the view or form classes in order for this path to work? or I need to configure a different URL path somehow base on my view and form? I added line below to the widget, but no help. model = settings.AUTH_USER_MODEL I have no clue how this select2 search work. Any help appreciated. -
Change email verify code to 6 digits code in authemail django
I am using authemail for email verifications of users. I need to change code's length to 6 and make it only digits. In authemail models I have following function and I want to override it. This function is not in any class. def _generate_code(): return binascii.hexlify(os.urandom(20)).decode('utf-8') I am attaching link so you can check models yourself authemail I have tried to override this function in my models like following but Its instead of my custom function, authemail's function is called. from django.db import models from authemail.models import EmailUserManager, EmailAbstractUser, SignupCodeManager, SignupCode import os import binascii from .auth import custom_generate_code class CustomSignupCodeManager(SignupCodeManager): def create_signup_code(self, user, ipaddr): code = custom_generate_code() signup_code = self.create(user=user, code=code, ipaddr=ipaddr) return signup_code def set_user_is_verified(self, code): try: signup_code = self.get(code=code) signup_code.user.is_verified = True signup_code.user.save() return True except self.model.DoesNotExist: pass return False class MyCustomSignupCode(SignupCode): objects = CustomSignupCodeManager() -
There is a problem for updating database using forms.form in Django and I want use only one 'update' button to update many database data
what I want do make is that show the existing data in the database to a user through HTML page. let a user update the existing data if he wants to do. Promblem 1> the problem is that,when running my code, a user input the new data and clicked 'update' button, but the update did not work. I don't know whether it is the reason or not, anyway, when I put 'def show_data' and 'def input' together, updating did work well. However 'def show_data'and 'def input' should be separate. 'def show_data' : it is for saving the data from excel file into the database using pandas 'def input': it is for receiving the input data from a user and updating the existing data with the input data Promblem 2> There are many 'update' button in the web page. I want to make only one 'update' button at the bottom of web page for updating all data user input into the database. Please refer to the below codes and result image. <forms.py> from django import forms from report.models import Upload, Memo class InputForm(forms.Form): item_id = forms.IntegerField(widget=forms.HiddenInput()) memo = forms.CharField() user_input = forms.CharField() <models.py> from django.db import models class Memo(models.Model): memo = … -
"I get utf-8 error when django makemessages command runs"
Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "myvenv\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "myvenv\Lib\site-packages\django\core\management\__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "myvenv\Lib\site-packages\django\core\management\base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "myvenv\Lib\site-packages\django\core\management\base.py", line 458, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "myvenv\Lib\site-packages\django\core\management\commands\makemessages.py", line 430, in handle potfiles = self.build_potfiles() ^^^^^^^^^^^^^^^^^^^^^ File "myvenv\Lib\site-packages\django\core\management\commands\makemessages.py", line 508, in build_potfiles self.process_files(file_list) File "myvenv\Lib\site-packages\django\core\management\commands\makemessages.py", line 599, in process_files self.process_locale_dir(locale_dir, files) File "myvenv\Lib\site-packages\django\core\management\commands\makemessages.py", line 675, in process_locale_dir msgs, errors, status = popen_wrapper(args) ^^^^^^^^^^^^^^^^^^^ File "myvenv\Lib\site-packages\django\core\management\utils.py", line 26, in popen_wrapper p.stdout.decode(stdout_encoding), ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ UnicodeDecodeError: 'utf-8' codec can't decode byte 0xfe in position 978: invalid start byte When I run the "django makemessages" command, I keep getting this error. I've gone through all the files in a loop to check for UTF-8 issues, but I couldn't find any. I've verified that all my files are encoded in UTF-8, but I still keep encountering this error. -
The X variable is not set. Defaulting to a blank string
I have a django secret key in a .env which is being read as a blank string part of the secret key is attached below SECRET_KEY=|$u6qthu06zp|$q at the point where the $ sign starts I keep getting the message level=warning msg="The "u6qthu06zp" variable is not set. Defaulting to a blank string." level=warning msg="The "q" variable is not set. Defaulting to a blank string." the settings file has import os import environ PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BASE_DIR = os.path.dirname(PROJECT_DIR) env = environ.Env(DEBUG=(bool,False)) environ.Env.read_env(env_file=".env") and in the final secret key is written SECRET_KEY = env("SECRET_KEY") however I am not being able to run the docker-compose build --remove-orphan as the SECRET_KEY is coming back as an empty string seemingly because the $ sign is causing some kind of failure. Any advice will be appreciated -
Django i18n is not detecting texts inside the for loop
I couldn't understand why the i18n is not detecting the data in my loop: {% trans service.title %} anyone who can help!? Thanks in advance! {% load i18n %} {% for service in services %} <div class="col-sm-3"> <div class="service bg-white"> <div class="img-block"> <img alt="" class="service-img img-fluid" src="{{service.img.url}}"> </div> <div class="service-feature"> <h4 class="feature-text text-center"> {% trans service.title %} </h4> <p>{{service.desc}}</p> </div> </div> </div> {% endfor %} I tried several different ways such: {% translate service.title %} no reactions {{ service.title|trans }} no reactions -
Displaying Real-time Data from Arduino IDE to Django
I am new to Django. Is there a possible way to display the value from the Arduino IDE to Django in real time? The data that displays in the inserted coins came from Arduino, but it does not automatically change unless you refresh the site. views.py from django.shortcuts import render import serial def home (request): return render(request, 'home.html' ) def usb (request): try: arduino = serial.Serial('COM6', 9600) data = arduino.readline().decode().strip() arduino.close() except Exception as e: data = f"Error communicating with Arduino: {str(e)}" return render(request, 'usb.html', {'data' : data}) def nfc (request): return render(request, 'nfc.html') def bluetooth (request): return render(request, 'bluetooth.html') usb.html <div class="estimated-price"> <label>Inserted Coins:</label> <span id="inserted-coins">₱{{data}}</span> </div> The data that displays in the inserted coins came from the arduino but it does not change automatically, i also need to refresh the page in order to update the data enter image description here Is there a way to display the data in real-time without refreshing the file? -
Wagtail custom permissions
I have a wagtail site. I have certain pages that I only want certain users to be able to access. I have used the standard django permissions setup to do this: models.py class Case(TimeStampedModel): case_userdefined_id = models.CharField( max_length=17, null=False, blank=False, unique=True, default='default' ) user = models.ForeignKey( get_user_model(), blank=False, null=True, on_delete=models.SET_NULL) class Meta: permissions = (("can_access_case", "Can Access case"),) views.py class CreateCaseView(PermissionRequiredMixin, CreateView): permission_required = 'Case.can_access_case' print('test2') template_name = 'cases/create_case.html' form_class = CaseForm success_url = reverse_lazy('patients') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) form = CaseForm() context['form'] = form return context wagtail_hooks.py from django.contrib.auth.models import Permission from wagtail import hooks @hooks.register('register_permissions') def view_restricted_page(): return Permission.objects.filter(codename="can_access_case") Then in the wagtail admin I have created a group 'case_access' and ticked the custom permissions to allow access. I have then made various users members of this group. However these users still get a '403 forbidden' screen, it is only superusers that can access the relevant pages. What else do I need to do? -
Having problem in rendering forms for each instance
I am creating a quiz website. Within the website there are multiple quiz topics, where each topic has a set of questions and each question has a set of answers as option. When i select a quiz topic I want it to show the questions and options. I tried doing the following. I created the following models difficulty_choices=(('easy','easy'),('hard','hard'),('medium','medium')) class Quiz(models.Model): name=models.CharField(max_length=200) topic=models.CharField(max_length=100) number_of_questions=models.IntegerField() difficulty=models.CharField(max_length=100,choices=difficulty_choices) TimeLimit=models.IntegerField(blank=True) def get_questions(self): return self.questions_set.all()[:self.number_of_questions] class Questions(models.Model): text=models.CharField(max_length=200) quiz=models.ForeignKey(Quiz,on_delete=models.CASCADE) correct=models.CharField(max_length=25) def __str__(self): return str(self.text) def get_answers(self): return self.answers_set.all() class Answers(models.Model): text = models.CharField(max_length=200) question = models.ForeignKey(Questions, on_delete=models.CASCADE) def __str__(self): return f"Question: {self.question.text}, Answer: {self.text}" class UserAnswer(models.Model): quiz=models.ForeignKey(Quiz,on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) question = models.ForeignKey(Questions, on_delete=models.CASCADE) answer = models.ForeignKey(Answers, on_delete=models.CASCADE,null=True,blank=True) and forms.py is class QuizForm(forms.ModelForm): class Meta: model = Quiz fields = ['text'] exclude = ["text"] # Add other fields as needed selected_answer = forms.ChoiceField( label="", choices=[], # We'll update choices dynamically widget=forms.RadioSelect ) def __init__(self, *args, **kwargs): super(QuizForm, self).__init__(*args, **kwargs) quiz_instance = kwargs.get('instance') questions = quiz_instance.get_questions() answer_choices = [] for question in questions: answers = question.get_answers() answer_choices=[(answer.id, answer.text) for answer in answers] self.fields["selected_answer"] = forms.ChoiceField( label='select the correct option', choices=answer_choices, widget=forms.RadioSelect ) Here in forms I have used the for loop to iterate through each question … -
how to send an email to a particular account wid user'contact when that particular user clicks on a button
when an user clicks on a specific button, I want that user's mobile number (that they entered when they registered for an account) to be sent to a particular email i tried using js code (addeventlistener). also im doing it in django and the mobile number field and the place where im using js are in two different apps. document.addEventListener('DOMContentLoaded', function() { document.getElementById('send-button').addEventListener('click', function (event) { event.preventDefault(); var mobileNumber = document.getElementById('mobile_number').value; // Send mobile number to Django view using AJAX var xhr = new XMLHttpRequest(); xhr.open('POST', '{% url "send_mobile_number" %}', true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onreadystatechange = function () { if (xhr.readyState === XMLHttpRequest.DONE) { if (xhr.status === 200) { alert('Mobile number sent successfully.'); } else { alert('Failed to send mobile number.'); } } }; xhr.send('mobile_number=' + encodeURIComponent(mobileNumber)); }); }); -
How to List Categories with Dropdown in Django
I would like to add a dropdown menu to my Django project that lists all categories from the database. The challenge I'm facing is that while I can get the categories listed on a single page (category), I would like them to be accessible throughout the entire website. I would really appreciate if someone helps. Thanks in advance. views.py #dropdown list of categories class CategoryListView(View): template_name = 'media/categories_dropdown.html' def get(self, request, *args, **kwargs): categories = Category.objects.all() return render(request, self.template_name, {'categories': categories}) urls.py path('category/', CategoryListView.as_view(), name='category-list'), media/categories_dropdown.html {% for category in categories %} <option value="{{ category.slug }}">{{ category.name }}</option> {% endfor %} -
how to access files in Views.py in django
I want to use an image that is in static folder/data/m.tif but I can't access that. here is my screenshot from pycharm. enter image description here and here is error: enter image description here get image path to pass in other function -
How to better structure variations for Ecommerce site
I am working on an e-commerce application in Django. It allows for product variations. My first impulse has been to go with multi-table inheritance, where variants have their own table different from the main product table. Both of these inherit an abstract table, so they share common properties. Then in the frontend, implicitly place the main product as the first variation in the variation list. The thing I am struggling with deciding whether to duplicate main product as variant like in the Amazon custom implementations of variations, as shown in this image: The primary main product always seems to be the first expected product. But clicking on that, you see that the circled label(color) in the above image, also changes, in this case 01-black. My question is, is Amazon duplicating the main product as a variation too? Which means, it will have it's specific features like the color name. That would mean duplication. If in case then that Amazon is implicitly displaying the main product as the first variation, how come it has unique property values like the color name ````01-black``? -
Django TypeError: Field.__init__() got an unexpected keyword argument 'id'
model.py from django.db import models class User(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255, null=True, default="") password = models.CharField(max_length=255) def __init__(self, name, password, *args, **kwargs): super().__init__(*args, **kwargs) self.id = id self.name = name self.password = password serializer.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'name', 'password') def __init__(self, name, password, *args, **kwargs): super().__init__(*args, **kwargs) self.id = id self.name = name self.password = password views.py def find_user(request): if request.method == 'GET': data = json.loads(request.body) id = data['id'] user = User.objects.get(id=id) user_serializer = UserSerializer(id=user.id, name=user.name, password=user.password) return HttpResponse(user_serializer.data) Why TypeError: Field.init() got an unexpected keyword argument 'id' ? I tried a lot of things ㅠㅠ -
Django REST API login give server error if i set cookie
I'm currently working on a Django web application that involves user authentication. However, I've encountered an issue where the user's login information gets lost whenever I refresh the browser. To address this problem, I decided to implement cookie-based authentication to allow the browser to remember the user's login status. Despite my efforts, I'm facing difficulties in getting this functionality to work correctly. i changed my code this,, class CustomUserRegistrationView(APIView): permission_classes = (AllowAny,) def post(self, request): serializer = CustomUserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() refresh = RefreshToken.for_user(user) response_data = { 'refresh': str(refresh), 'access': str(refresh.access_token), 'message': 'User registered successfully.' } return Response(response_data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class CustomUserLoginView(APIView): permission_classes = (AllowAny,) def post(self, request): if request.user.is_authenticated: return Response({"message": "You are already logged in"}, status=status.HTTP_400_BAD_REQUEST) mobile_number = request.data.get('mobile_number') password = request.data.get('password') if mobile_number is None or password is None: return Response({'error': 'Please provide both mobile number and password'}, status=status.HTTP_400_BAD_REQUEST) try: user = CustomUser.objects.get(mobile_number=mobile_number) except CustomUser.DoesNotExist: return Response({'message': 'Invalid mobile number or password.'}, status=status.HTTP_401_UNAUTHORIZED) if not user.check_password(password): return Response({'message': 'Invalid mobile number or password.'}, status=status.HTTP_401_UNAUTHORIZED) serializer = CustomUserLoginSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = authenticate( mobile_number=serializer.validated_data['mobile_number'], password=serializer.validated_data['password'] ) if user is None: return Response({"error": "Invalid login credentials"}, status=status.HTTP_400_BAD_REQUEST) if not user.is_active: return Response({'error': 'User account is disabled'}, … -
AxiosError (Request failed with status code 400)
I have been following a React-Django tutorial. In addition to tutorial I was trying to store image using a post request via axios but getting a axios error 400. Iam trying to make a post request using an action Add_lead() in my reducers. This is my front-end. import React, { Component } from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import { addLead } from '../../actions/leads'; class Form extends Component { //initial state state = { name: '', email: '', message: '', gender: '', image: null, }; static propTypes = { addLead: PropTypes.func.isRequired, }; onChange = (e) => { if (e.target.name === 'image') { this.setState({ [e.target.name]: e.target.files[0] }); // Handle file input } else { this.setState({ [e.target.name]: e.target.value }); } }; onSubmit = (e) => { e.preventDefault(); const { name, email, message, gender, image } = this.state; const lead = { name, email, message, gender, image }; this.props.addLead(lead); this.setState({ name: '', email: '', message: '', gender: '', image: null, }); alert('Form submitted.'); }; render(){ const { name, email, message, gender, image } = this.state; return ( <div className="card card-body mt-4 mb-4"> <h2>Add Lead</h2> <form onSubmit={this.onSubmit} encType="multipart/form-data"> <div className="form-group"> <label>Name</label> <input className="form-control" type="text" name="name" onChange={this.onChange} value={name} required … -
How a child serializer can access a respective field value from its parent serializer initalized with many=True?
In case we want to initialize the parent serializer with many=True, then how can the child serializer can access a respective field value from its parent serializer? class ChildSerializer(serializers.Serializer): field1 = serializers.CharField() def validate(self, data): # How to get the value of batch_key from the parent serializer (here self.batch_key)? if not self.batch_key == data['field1']: raise serializers.ValidationError('invalid field1') return data class ParentSerializer(serializers.Serializer): child = ChildSerializer(many=True) batch_key = serializers.CharField() class MyAPIView(APIView): def post(self, request): serializer = ParentSerializer(data=request.data, many=True) serializer.is_valid(raise_exception=True) return request data is as follows: [ { "batch_key":"batch_key_value_1", "child":[ { "field1":"value1" }, { "field1":"value2" }, { "field1":"value3" } ] }, { "batch_key":"batch_key_value_2", "child":[ { "field1":"value4" }, { "field1":"value5" }, { "field1":"value6" } ] } ] -
Nginx returns html instead of json in Django
I'm trying to deploy an Angluar and Django web site on an Nginx server. The frontend works properly, but when i make a call to the backend, Django returns me an html response instead of a json response. I searched online, but i can't came out with a solution. This is the nginx configuration: server { server_name sub.domain.net www.sub.domain.net; root /var/www/projectfolder/frontend; index index.html; # Handles proxying to Angular App location / { add_header Access-Control-Allow-Origin *; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'Access-Control-Allow-Origin, XMLHttpRequest, Accept, Authorization, Cache-Control, Content-Type, DNT, If-Modified-Since, Keep-Alive, Origin, User-Agent, X-Mx-ReqToken, X-Requested-With'; try_files $uri $uri/ /index.html; } # Handles proxying to Django API location ~* /api { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_http_version 1.1; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/sub.domain.net/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/sub.domain.net/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } This is the Django code: def get(self, request, format=None): news = News.objects.all().values().order_by('-date') return Response(news) To this endpoint: /getnews/ The server response is: Accept-Ranges: bytes Access-Control-Allow-Credentials: true Access-Control-Allow-Headers: Access-Control-Allow-Origin, XMLHttpRequest, Accept, Authorization, Cache-Control, Content-Type, DNT, If-Modified-Since, Keep-Alive, Origin, User-Agent, X-Mx-ReqToken, … -
Google Cloud Run Gunicorn Multi-Threaded Django Request Blocked on Cold Start
I have a Django application deployed on Google Cloud Run using a Gunicorn server. There is a daily task triggered by Google Cloud Scheduler. The task job involves patching a Microsoft subscription. For this patch to complete successfully, Microsoft makes a call to another API endpoint on the same Django application to validate a token. The Gunicorn server is running with multiple threads. When the task is triggered and the container has a cold start, the validation request is blocked, the patch request fails and the container only responds to it after the patch failure. However, if the container is warm, the task completes successfully and the additional thread is able to respond to the validation check. Any idea why this is occurring and how it can be addressed? This was working previously but started encountering this error in recent weeks. Have tried setting multiple workers and more threads on the Gunicorn server as well as enabling CPU boost on Cloud Run but neither of these worked. -
Is It Possible with Python creating Remote Control Desktop Which will work On Different Network?
There are online resources, GitHub repositories, and YouTube videos that can guide you in controlling a desktop (including screen sharing, system access, and interaction with different software) within the same network. However, is it feasible to use Python for controlling a desktop that is not on the same network, while minimizing networking adjustments? This implies achieving the goal without resorting to actions like port forwarding, firewall configuration, or the use of a VPN etc. Please share any insights. Thanks. -
Setup a Django in Anaconda environment
I am trying to setup a Django in Anaconda environment. I have created a new environment with the name Django2. After that, I was stuck, unable to move on. What are the actions that should be taken? Please offer some suggestions. enter image description here -
Conditional form according to choice of dropdown list
I need a form to be displayed depending on the option chosen in the dropdown list, which will be selected by the administrator when creating the new candidate. However, the problem is that even if you select any option in the dropdown list, form 2 corresponding to the else of the conditional is displayed. help please. models.py: Here the model is defined as well as functions to be able to rename the files when saving them cc= ( ('1','Quebrada Blanca'), ('2','Lo Pinto'), ('3','Oficina Central'), ('4','Carbonato'), ('5','Toconao'), ('6','Centinela'), ('7','Spence'), ('8','La Negra'), def create_path(instance, filename, file_type): ext = filename.split('.')[-1] new_filename = "DSR_%s_%s_%s_0.%s" % (instance.rut, instance.nombre, file_type, ext) return os.path.join('uploads',new_filename) def imagen_upload_path(instance, filename): return create_path(instance, filename, 'imagen') def certificado_antecedentes_upload_path(instance, filename): return create_path(instance, filename, 'certificado_antecedentes') def hoja_de_vida_conductor_upload_path(instance, filename): return create_path(instance, filename, 'hoja_de_vida_conductor') def certificado_residencia_upload_path(instance, filename): return create_path(instance, filename, 'certificado_residencia') def certificado_afiliacion_afp_upload_path(instance, filename): return create_path(instance, filename, 'certificado_afiliacion_afp') def certificado_afiliacion_salud_upload_path(instance, filename): return create_path(instance, filename, 'certificado_afiliacion_salud') def fotocopia_cedula_identidad_upload_path(instance, filename): return create_path(instance, filename, 'fotocopia_cedula_identidad') def fotocopia_licencia_conducir_upload_path(instance, filename): return create_path(instance, filename, 'fotocopia_licencia_conducir') class Candidato(models.Model): nombre = models.CharField(max_length = 70, null=True, blank=True) rut = models.CharField(max_length = 10, primary_key=True) correo = models.EmailField(null=True, blank=True) centro_de_costo =models.CharField(null=True, blank=True, max_length =30, choices = cc) estado = models.IntegerField(null=True, blank=True) imagen = models.ImageField(upload_to=imagen_upload_path, null=True, blank=True) certificado_antecedentes … -
update the 'div' after ajax request
This is my first project in django. I'm new to Django, ajax, javascript. I have to send the data to jinja template after making ajax request. My index.html is {% if data %} <p>{{data.title}}</p> <p>{{data.price}}</p> {% endif %} My javascript is <script> $.ajax({ type: "POST", url: "/", // Replace with the actual URL of your view data: { input_value: "test", csrfmiddlewaretoken: "{{ csrf_token }}" }, success: function(response) { title = response // after request, response be like { "data" : {"title":"t1", "price":20} } }, error: function() { console.log("Error") } }); <script> I don't know this is possible. Some using element.innerHTML to update, but i need to send to jinja format. Thanks -
How to get a value from the context dictionary without looping through it
I have to list the products belonging to a particular category and also above the products I want to display the name of the category (only once). I can get the name of category when iterating over products but I want to display it only once on the top. My models are follwing: class category(models.Model): title = models.CharField(max_length=30) image = models.ImageField(null=True, blank=True) def __str__(self): return self.title class product(models.Model): name = models.CharField(max_length=50, null=True, blank=True) slug = models.SlugField(null=True, blank=True) description = models.TextField(max_length=500,null=True, blank=True ) category = models.ForeignKey(category, on_delete=models.CASCADE) cost = models.PositiveIntegerField() image = models.ImageField(null=True, blank=True) def save(self, *args, **kwargs): # new self.slug = slugify(self.name) return super().save(*args, **kwargs) def __str__(self): return self.name and the view is: class ProductsListView(ListView): model = product template_name = 'products/productList.html' context_object_name = 'products' def get_queryset(self, *args, **kwargs): return ( super() .get_queryset(*args, **kwargs) .filter(category_id=self.kwargs['cat_id']) ) template code: {% extends 'products/base.html' %} {% load static %} {% block content %} <h1>Product PAGE!!</h1> <!-- I want to display the category name here --> {% for product in products %} <img src="{{ product.image.url }}" alt="{{ product.name }}" width="10%"> <h2>{{product.name}} </h2> <h2>{{product.cost}} </h2> <h2>{{product.description}} </h2> {% endfor %} {% endblock %} I tried it using the key method "products[category] but it doesn't work.