Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to handle simultaneous requests in Django?
I have a standard function-based view in Django which receives some parameters via POST after the user has clicked a button, computes something and then returns a template with context. @csrf_exempt def myview(request, param1, param2): if request.method == 'POST': return HttpResponseRedirect(reverse("app1:view_name", args=[param1, param2])) '''Calculate and database r/w''' template = loader.get_template('showData.html') return HttpResponse(template.render(context, request)) It works with no problem as long as one request is processed at the time (tested both with runserver and in an Apache server). However, when I use two devices and click on the button simultaneously in each, both requests are mixed up, run simultaneously, and the website ends up trowing a 500 error, or 404 or sometimes success but cannot GET static files.. (again, tested both with runserver and Apache). How can I force Django to finish the execution of the current request before starting the next? Or is there a better way to tackle this? Any light on this will be appreciated. Thanks! -
Async Django view
I am curious about if I can use Async views for returning dynamic objects for my list view which has filtering. So view will update the list of objects shown in HTML without page refresh when user filters the list. Can I do it without ajax? Any explanation will help me. -
Problem in creating delete button in django
I am trying to build delete button and currently stuck. I am new to django and need help. Thank You This is my models.py:- from django.db import models from django.contrib.auth import get_user_model from django.db import models from django.urls import reverse # Create your models here. class simpleList(models.Model): title = models.CharField(max_length=250) def __str__(self): return self.title This is my views.py:- from django.shortcuts import render, get_object_or_404 from .models import simpleList from django.views.generic import ListView, DeleteView from django.urls import reverse_lazy from django.contrib.messages.views import SuccessMessageMixin # Create your views here. class ListListView(ListView): model = simpleList template_name = 'list_list.html' class DeleteList(SuccessMessageMixin, DeleteView): model = simpleList success_url = '/' success_message = "deleted..." def delete(self, request, *args, **kwargs): self.object = self.get_object() name = self.object.title # name will be change according to your need request.session['title'] = title message = request.session['title'] + ' deleted successfully' messages.success(self.request, message) return super(DeleteView, self).delete(request, *args, **kwargs) This is my urls.py:- from django.urls import path from .views import ListListView, DeleteList from django.conf.urls import url from . import views urlpatterns = [ path('', ListListView.as_view(), name='list_list'), path('<int:pk>/', DeleteList.as_view(), name='delete_view'), ] This is my home.html:- {% extends 'base.html' %} {% block title %}Home{% endblock title %} {% block content %} <div> {% if user.is_authenticated %} <button type="button" class="btn … -
How compare field of two different models in Django
One of the main goals of project is control users done visits to customers. Available Customers, Employees and Appointment models. Make appointment to Customer and assign it to Employee on any future date. Employee can see appointment assigned to him and make visits. Need somehow see are appointments to customers done or not. See customers on custom date with made visits and not visited. Need to see it in Django Admin. model.py class Customer(models.Model): name = models.CharField(max_length=255,blank=True, null=True) ...... class Emplyee(models.Model): name = models.CharField(max_length=255,blank=True, null=True) ...... class Visit(models.Model): employee_name = models.ForeignKey(Employee, on_delete=models.CASCADE) customer_name = models.ForeignKey(Customer, on_delete=models.CASCADE) visit_time = models.TimeField() visit_date = models.DateTimeField(auto_now_add=True) note = models.TextField(blank=True, null=True) ...... class Appointment(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) appointment_date = models.DateTimeField(auto_now_add=True) note = models.TextField(blank=True, null=True) admin.py class VisitAdmin(admin.ModelAdmin): list_display = ('employee_name', 'customer_name','visit_time','visit_date') admin.site.register(Visit, VisitAdmin) ...... class AppointmentAdmin(admin.ModelAdmin): list_display = ('employee_name', 'customer_name','appointment_date','visit_done') admin.site.register(Appointment, AppointmentAdmin) // Need to write some def visit_done as a Boolean for example True/False that the visit to exact this Customer and Date and Employee was done or Not. -
Django-templated-email not connecting to my template file
I am sure that i have set up everything correctly and my template file welcome.email is in right folder but somehow when sending email, it is not showing as my template has been connected. Here is my view for django-template-email: def send(request, pk): if request.method == "POST": data = json.loads(request.body) trainingtitle = data['trainingtitle'] name = data['name'] email = data['email'] send_templated_mail( template_name='welcome', from_email='austin.roose1@gmail.com', recipient_list=['austin.roose1@gmail.com'], context={ 'email': email, 'name': name, 'trainingtitle': trainingtitle, }, ) return redirect('/api/') And i have also in my settings.py file: TEMPLATES = [ { 'DIRS': [os.path.join(BASE_DIR, 'templates')], My welcome.email file looks like: {% block html %} <p>Hi {{name}},</p> <p>You just signed up for my website, using: <dl> <dt>username</dt><dd>{{name}}</dd> <dt>join date</dt><dd>{{email}}</dd> </dl> </p> <p>Thanks, you rock!</p> {% endblock %} But my sent email looks like: screenshot of email As you can see it shows 'username' and 'full name' in there although i don't have them in my template. What should i change? -
Passing image file from React to Django backend
I am trying to upload a file on the frontend in React and pass that image file to the backend in django to run some code on the image. Right now, the data from React is being passed as a bytes array but when I reconstruct the image in the Django backend the image data is completely corrupt. I dont know what I am doing wrong here. The image is in the form of a InMemoryUploadedFile object in Django. HTML: <label onChange = {handleFileUpload} className = "custom-file-upload"> <input type = "file" name = "image" /> Upload Image </label> AJAX call to Django: I can confirm the correct data is being passed from the frontend to the backend const data = new FormData(); data.append('image', files[0]) fetch('/api/itot/', { method: 'POST', body:data }) .then(response => response.json()) .then(data => console.log(data["text"])) Django View: img = request.FILES["image"] # img is InMemoryUploadedFile object # I have tried .open() and .read() but that does not seem to work I dont know why the file is being corrupted. -
Cloudflare SSL not working even though it worked before
Cloudflare SSL is not working on my website (made with Django, hosted on heroku). I used GoDaddy but then transferred the Nameserver stuff to Cloudflare to get SSL. It worked yesterday, but now for some reason, it isn't. On Cloudflare I have the setting set to: "Your SSL/TLS encryption mode is Full". -
Why don't Django HTML tags work in strings?
Lets say I have an image source as such: <img src="{% static 'images/category1.png' %}"> This works completely fine - it finds the image and displays it properly. However, its in a for-loop, so I'm going to have different images for each element (in this case, a different image for each category) For some reason, this doesn't work: {% for cat in category %} ... <img src="{% static 'images/{{cat.category_slug}}.png' %}"> ... {% endfor %} I'm positive that the {{cat.category_slug}} variable has the correct name as my image, as this: <p>{{cat.category_slug}}</p> shows 'category1' on my site, which is correct. -
Mariadb at synology refusing connection
I'm trying to connect from my django project to mariadb hosted on my synology nas. When I try to make migrations, the shell returns that connection was refused all time. I added a file my.cnf with this: synology instructions for custom settings [mysqld] skip-networking=0 bind-address=0.0.0.0 Also created a user with different hosts, including: %, ip of web server, localhost, nas network name,... Also checked NAS firewall. I created a rule to allow all connections from web server ip. If I disable it a get a time out error, so it seems to work. My project settings are these: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': "db_name, 'USER': 'user', 'PASSWORD': 'pwd', 'HOST': 'nas ip', 'DATABASE_PORT':'3307', } } Any clues? I'm lost... Thank you in advance -
Django NoReverseMatch Error during Template Rendering
I am setting up a simple blog site with Django, and run into this error when trying to link to a page that allows users to edit existing blog posts. Reverse for 'edit_post' with arguments '('',)' not found. 1 pattern(s) tried: ['edit_post/(?P<title_id>[0-9]+)/$'] If I understand this error correctly, it means that Django can't find a urlpattern that matches the url being requested. To my eyes I have the urlpattern set up correctly, but I still get the error. The link in question appears on the text.html template, which is the template that displays the text of a particular blog post. Here is the relevant code: urls.py """Defines URL patterns for blogs.""" from django.urls import path from . import views app_name = 'blogs' urlpatterns = [ # Home page, shows all posts in chronological order. path('', views.index, name='index'), # A page to show the text of a specific post. path('text/<int:title_id>/', views.text, name='text'), # Page for adding a new post. path('new_post/', views.new_post, name='new_post'), # Page for editing a post. path('edit_post/<int:title_id>/', views.edit_post, name='edit_post'), ] views.py from django.shortcuts import render, redirect from .models import BlogPost from .forms import BlogPostForm def index(request): """The home page for blogs, shows all posts.""" titles = BlogPost.objects.order_by('date_added') context = … -
Is there a way to call update_or_create and not update a field if it's already populated?
I know the logic for Django's update_or_create is mostly meant to create a record if a matching record isn't found, so in the instance when update is being run, can I avoid updating a particular field if it's already populated? Basically, I want to update a timestamp field (first_updated) to track when the record was first updated. The record would keep on updating other fields, but I want this first_updated timestamp field updated once and never again. Does update_or_create allow this logic natively, or what are some ways to do this? Would I need to check the table to see if this record's first_updated is populated and if so, run update_or_create without first_updated? Any functions in Django that would make this a bit easier to implement? -
Django ModelForm - Widget rendered with required attribute when forms.Field specifies it as not required
I am having an issue where my django.forms.ModelForm is rendering the widget of a field that is not required with the required HTML attribute when rendering the form after an error. class VerificationForm(forms.ModelForm): manual_verification = forms.BooleanField(required=False, widget=forms.CheckboxInput(), label='My checkbox') def __init__(self, *args, **kwargs): super(AddressForm, self).__init__(*args, **kwargs) self.fields['manual_verification'].required = False My code in the views.py file: def save_data(self, request): ... validation_form = ValidationForm(instance=existing_verification_instance, data=request.POST) if validation_form.is_valid() # is False # save logic else: context['validation_form'] = validation_form return render(request, 'my_template.html', context) And in my_template.html: {{ form.manual_verification }} <label></label> {{ form.manual_verification.widget.attrs }} which produces the following mark-up: <input type="checkbox" name="manual_verification" id="id_manual_verification" required="true"><label>My checkbox</label> {'required': False} The application uses Python 2.7 and Django 1.11. So my question is this: Why is this checkbox being made required, when in both the field and in the ModelForm.__init__ constructor, I have ensured that the field is not required? And how do I make sure that the form field is not rendered with the required HTML attribute? NOTE: This only occurs when the form has been submitted and was not valid, which is why I only included the code for rendering it after submission. -
Boolean Field in Form Not Recognizing False as Answer in Django ModelForm
I've got a Django model form where I'm setting the Yes/No radio buttons to be a group-toggle Bootstrap4 button group. It's a super basic form - nothing wild. The issue comes when I submit the form - it says "This field is required." I didn't used to have this issue until I made the fields required. By default if they weren't answered they would be given a "False" value. But I'm trying to ensure that a person has to select the answer to the question - so I made them required. But now it says it's not being answered. My form looks like this: BOOL_CHOICES = (( True, 'YES'), (False, 'NO')) class CheckInForm(forms.ModelForm): """Form definition for a CheckIn.""" def __init__(self, *args, **kwargs): super(CheckInForm, self).__init__(*args, **kwargs) self.fields['question_one'].required = True self.fields['question_one'].widget.attrs = { 'class': 'form-control' } self.fields['question_two'].required = True self.fields['question_two'].widget.attrs = { 'class': 'form-control' } self.fields['question_three'].required = True self.fields['question_three'].widget.attrs = { 'class': 'form-control' } self.fields['question_four'].required = True self.fields['question_four'].widget.attrs = { 'class': 'form-control' } class Meta: """Meta definition for CheckInform.""" model = CheckIn fields = ( 'question_one', 'question_two', 'question_three', 'question_four', ) labels = { "question_one": """ Are you alive? """, "question_two": """ Do you like sunsets? """, "question_three": """ Enjoy Fishing? """, "question_four": … -
Activation email is invalid django
Email Activation link is invalid! how to make user active? this is my activation views class VerificationView(View): def get(self, request, uidb64, token): try: id = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=id) if not token_generator.check_token(user, token): return redirect('pengurusan/signin'+'?message'+'User already activated') if user.is_active: return redirect('pengurusan/signin') user.is_active = True user.save() messages.success(request, 'Account activated successfully') return redirect('pengurusan/signin') except Exception as ex: pass return HttpResponse('Activation link is invalid!') this is my utils.py from django.contrib.auth.tokens import PasswordResetTokenGenerator from six import text_type class AppTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return (text_type(user.is_active)+text_type(user.pk)+text_type(timestamp)) token_generator = AppTokenGenerator() -
How To get the information at the top of website for which user searched for?
I am designing a webpage which is also a home page of my website on which I have to put some question and answers, so what I want to do is that for example a user searched a question on google which is on my webpage and then user clicked on my web page so I want to bring that question at the top of my web page. (I am using Django framework for building my website in case this info is needed.) NOTE: Im new on stackoverflow pls forgive if question is not proper -
Session variables not saving outside views
I am trying to update session instance outside of views. Basically I want to pass session into external object, modify it and save. I want to use existing session in the object and return it modified back to the view. Unfortunately it is not updating, I'm passing session key to the object. I tried both self.session.modified = True and self.session.save(), but it is not updating. I was able to verify that session_key is the same in both places. My view: from order import price def order_view(request, cat_id=None, *args, **kwargs): if not request.session.exists(request.session.session_key): request.session.create() price_obj = price.Price(current_session=request.session.session_key) The object: from django.contrib.sessions.backends.db import SessionStore class Price(): def __init__(self, *args, **kwargs): try: self.session = SessionStore(session_key=kwargs["current_session"]) except KeyError: log.error("Session error") def structure_session_pricing(self): if "pricing" in self.session: del self.session["pricing"] self.session["pricing"] = {} self.session["pricing"]["Subject"] = 0 # self.session.modified = True self.session.save() I do not understand why it is not working. The code above is just part of the whole thing that I have there to better illustrate the problem, let me know if something is missing/I omitted too much - I will post missing pieces. Thank you for help! -
How to use Django Sessions Framework in generic views to send data to another
In my Django application, I am trying to use sessions to store a variable in my class view and later use it to send it to a function view. In the past I have used sessions on function views and now I am trying to use it on a class view. class someView(CreateView): form_class = myForm template_name = 'myTemplate.html' ... ... def get_context_data(self, **kwargs): request.session['my_var'] = '1234' return context Than I am trying to capture the session variable in another view like this: def fnView(request): data = {} new_var = request.session['my_var'] data = {'key1': new_var} return render(request, 'fnVwTemplt.html', data) And in the template I am trying to display the variable like this: {{ key1 }} However I am coming up with the following message in the browser: KeyError at ... 'my_var' It is evident that the variable is not getting stored in the session variable. What I am doing wrong? PS. Apologies, if my query is not lucid enough. -
(13)Permission denied django apache server
hi i tried to upload my django project (apache2 + ubuntu server) , this is my config file <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog /var/log/apache2/error.log CustomLog /var/log/apache2/access.log combined <Directory /home/my_user/project_name/project_name/> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess django_proj python-path=/home/my_user/project_name python-home=/home/my_user/project_name/venv WSGIProcessGroup django_proj WSGIScriptAlias / /home/my_user/project_name/project_name/wsgi.py </VirtualHost> but raised this error when i type sudo cat /var/log/apache2/error.log: [core:error] [pid 20884:tid 140074095675136] (13)Permission denied: [client some number] AH00035: access to /favicon.ico denied (filesystem path '/home/my_user/project_name/project_name/wsgi.py') because search permissions are missing on a component of the path, referer: http://my-ip-address/ and on my browser i get this error : Forbidden You don't have permission to access this resource. i much appreciate your helps , i searched alot , but i didnt find a solution -
Sending json to mySQL from angular frontend
I'm trying to make a form in angular that sends the answers as json to mysql database. I'm using a Django backend and gcloud mysql. Any tips of projects which this type of implementation or links to guide / documentation? Currently to create accounts (adding to the mysql) a shell script is ran on directly to container running the app. -
Change BooleanField value based on ForeignKey's BooleanField
Is there a way to change the BooleanField of a model based on a change in the BooleanField of a ForeignKey Model it's linked to? For instance: In models.py class Project(models.Model): ... complete = models.BooleanField(default=False) ... class Task(models.Model): ... project = models.ForeignKey(Project, on_delete=models.CASCADE) complete = models.BooleanField(default=False) ... If the user submits a form changing project.complete = True, is there a way I can automatically have all tasks connected to that project have task.complete = True? I have tried overriding the form_valid function in my views.py for when the project.complete value is changed: class ProjectCompleteView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Project fields = [] def form_valid(self, form): form.instance.complete = not form.instance.complete tasks = form.instance.task_set.all() for task in tasks: task.complete = True return super().form_valid(form) Which didn't change the task.complete value as it's still False when I reload the page. I'm new to django, so if anyone has any insight on what I can do/how this works it would be greatly appreciated! -
Pagination and querysets
I have a page formatted with a ListTemplate. By default, all the items are ordered a certain way. I've set up an HTML Select element and when you change the select option a request is sent at a certain URL and the View will produce another queryset depending on the request. <form id="sort_form" method="GET" action="/home/" name="sort_options"> <label for="order">Order by:</label> <select name="sort_options" id="sort_options" onChange="saveSelection();this.form.submit();"> <option value="most-recent" selected="selected">Most Recent First</option> <option value="least-recent">Least Recent First</option> <option value="most-comments">Most Comments</option> <option value="least-comments">Least Comments</option> </select> <br><br> I'm using some Javascript with SessionStorage to save the selected option so that the form remains changed to that option (it would still send the request and the queryset would get produced and a page sent back, but the Select element would appear set to the default option, even though the ordering is done according to the option that was selected) - this is all unimportant to the problem I'm having though). When I select, for example, order by 'least recent', this request is sent out: http://localhost:8000/home/?sort_options=least-comments And the page gets reordered correctly as a new queryset is produced. But my problem is that I also have pagination. But the next/previous links for the next/previous page produce a URL like … -
Handling exceptions when accessing multiple resources in Django API
I am a beginner in Python and Django. I am writing an API which accesses an external API, MongoDB and AWS in this sequence. I wanted to know if this structure of exception handling is correct. My API is like this. It calls two other functions to access external API and AWS. @api_view['POST'] def processData(request): try: externate_api_data = callExternalApi(data) // func to access external API // process data try: // mongoDb query except pymongo.errors.PyMongoError as e: raise ValueError(e) storeDataInAws(data); // func to access AWS except ValueError as e: print(e.args) response_object = { 'statusCode': *ERROR_CODE*, 'errorMessage': 'Failed to process data' } response_object = { 'statusCode': *SUCCESS_CODE*, 'processedData': data } return Response(data=json.dumps(response_object), status=status.HTTP_200_OK, content_type='application/json') Function to call External API. def callExternateApi(data): try: // code to call external API using urllib except urllib.error.URLError as e: error_messagae = ** construct error message ** raise ValueError(e) return api_data Function to access AWS. def storeDataInAws(data): try: // code to store data in AWS using boto3 client except botocore.exceptions.ClientError as e: raise ValueError(e) return If you find any other mistakes or bad code practices, please do let me know. -
How to connect a django app to a dockerized postgres db, both from a dockerized django and non-dockerized django using same DATABASE_HOST
I have a postgres container, docker-compose.yml: services: db: container_name: db expose: - "5432" ports: - 5432:5432 volumes: - postgres_data:/var/lib/postgresql/data/ And a django project with settings.py: DATABASES = { 'default': { 'HOST': os.environ.get('POSTGRES_HOST', '127.0.0.1') # etc } } .env POSTGRES_HOST_DJANGO=db When I run my django app locally with manage.py runserver 0.0.0.0:8000 it connects fine, using the default POSTGRES_HOST=127.0.0.1, because .env isn't loaded. I also run my django app in a container sometimes: docker-compose.yml: web: #restart: unless-stopped build: . env_file: .env command: bash -c "cd /app/src/ && python manage.py runserver 0.0.0.0:8000 volumes: - .:/app ports: - 8000:8000 links: - db:db However it uses the .env file and connects with POSTGRES_HOST=db If I try to connect the locally run django app with POSTGRES_HOST=db it fails: django.db.utils.OperationalError: could not translate host name "db" to address: Name or service not known And if I try to run the django app in a container with POSTGRES_HOST=127.0.0.1, it fails in the same way. How can I get them to use the same POSTGRES_HOST? -
django python encode produce strange output
i generate a string with html code. These string i insert in a template like this: header = render_to_string('header.html', {'content': header_content}) The template looks like this: ... {% autoescape off %} {{ content }} {% endautoescape %} </body> ... Now i have a string variable named "header". I would like to store these string as a html file in my storage (AWS S3). I try to create a temporary file with django contentfile. For this i must encode the string. It looks like this: self.export_settings.header.save("header.html", ContentFile(header.encode())) Now i have a html file in my s3 storage but sometimes with strange content. For example i have a table with an empty column. Before i call header.encode() it looks like this: <tbody> <tr> <td style="width: 32.1574%;">Test</td> <td style="width: 32.237%;"> </td> <td style="width: 32.237%; text-align: right;">Site <span class="page"> of <span class="topage"></td> </tr> </tbody> </table> </body> But after i call .encode() and save it to storage, the html file shows this in the second column: Why? That is not what i want. I would like to store my string that represents html code as a html file without convert the content to strange characters. I have read that the utf-8 encoding may the reason … -
trying to download json file but i am receving error
HTTPError Traceback (most recent call last) ` in 1 import urllib.request ----> 2 source= urllib.request.urlopen("http://finance.yahoo.com/webservice/v1/symbols/allcurries/quote?format=json") 3 pis = source.read() 4 print(pis) ~\anaconda3\lib\urllib\request.py in urlopen(url, data, timeout, cafile, capath, cadefault, context) 220 else: 221 opener = _opener --> 222 return opener.open(url, data, timeout) 223 224 def install_opener(opener): ~\anaconda3\lib\urllib\request.py in open(self, fullurl, data, timeout) 529 for processor in self.process_response.get(protocol, []): 530 meth = getattr(processor, meth_name) --> 531 response = meth(req, response) 532 533 return response ~\anaconda3\lib\urllib\request.py in http_response(self, request, response) 639 if not (200 <= code < 300): 640 response = self.parent.error( --> 641 'http', request, response, code, msg, hdrs) 642 643 return response ~\anaconda3\lib\urllib\request.py in error(self, proto, *args) 561 http_err = 0 562 args = (dict, proto, meth_name) + args --> 563 result = self._call_chain(*args) 564 if result: 565 return result ~\anaconda3\lib\urllib\request.py in _call_chain(self, chain, kind, meth_name, *args) 501 for handler in handlers: 502 func = getattr(handler, meth_name) --> 503 result = func(*args) 504 if result is not None: 505 return result ~\anaconda3\lib\urllib\request.py in http_error_302(self, req, fp, code, msg, headers) 753 fp.close() 754 --> 755 return self.parent.open(new, timeout=req.timeout) 756 757 http_error_301 = http_error_303 = http_error_307 = http_error_302 ~\anaconda3\lib\urllib\request.py in open(self, fullurl, data, timeout) 529 for processor in self.process_response.get(protocol[]): 530 meth = …