Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 = … -
Celery randomly fails silently when handling tasks
I have a Django project that uses Celery to run background tasks and scheduled tasks (via Celery Beat). It runs fine locally but has some intermittent problems in production. This is the difficult part, 50% of the time the task completes as expected but the other 50%, it 'fails' silently. The numerous scheduled tasks complete without issue. Version details django = "==2.2.4" celery = "==4.4.6" python_version = "3.6" Here's a simplified example of the code: models.py class Task(models.Model): is_actioned = models.BooleanField(default=False...) # Other fields... def create_lead(self): Lead.objects.create(....) def create_something_else(self): # Add M2M records, for example: lead.add(obj) def handle_task(self): self.create_lead() self.create_something_else() # Make various API calls def action(self): self.handle_task() self.is_actioned = True self.save() tasks.py @shared_task def action_task(task_id): tasks = Task.objects.get(id=task_id) task.action() views.py # Call the task action_task.delay(task.id) Procfile web: daphne -b 0.0.0.0 -p 5000 myproj.asgi:application worker: celery worker --app=myproj.celery -l debug beat: celery beat --app=myproj.celery -l info When viewing the logs a failed task does not appear to be received by the worker. The strange part is Celery seems to 'select' which methods to fail/skip. For example, Task.create_lead will be called successfully but Task.create_something_else will not be called. However, self.is_actioned = True will always run without fail. I would expect this … -
HTTPSConnectionPool(host='localhost', port=8000): Max retries exceeded with url:/index
I am using Django 2.2.10 I have written an authentication app, with view function that returns JSON data as ff: def foobar(request): data = { 'param1': "foo bar" } return JsonResponse(data) I am calling this function in the parent project as follows: def index(request): scheme_domain_port = request.build_absolute_uri()[:-1] myauth_login_links_url=f"{scheme_domain_port}{reverse('myauth:login_links')}" print(myauth_login_links_url) data = requests.get(myauth_login_links_url).json() print(data) When I navigate to https://localhost:8000myproj/index, I see that the correct URL is printed in the console, followed by multiple errors, culminating in the error shown in the title of this question: HTTPSConnectionPool(host='localhost', port=8000): Max retries exceeded with url:/index (Caused by SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:852)'),)) How do I fix this issue? -
How do i use pagination pagination in django when i apply filters in class based view. the url always keeps changing how can i track the url
How do I use pagination in Django when I apply filters in a class-based view. the URL always keeps changing how can I track the URL to go to the next page. can anyone help me -
How to store one of three forms or formsets in Django?
It will remain the owner of the copyright application. The owner may again be private or joint or institutional. How can this problem be solved once? Thanks! -
Uable to get the product name from the model
I've create 3 models for the Order processing. However, I couldn't show the product name on template for every single order. Does my for loop logic or 'get' method go wrong? models.py: class Product(models.Model): product_name = models.CharField(max_length=200) price = models.DecimalField(decimal_places=2, max_digits=10, blank=True) created = models.DateTimeField(auto_now=True) slug = models.SlugField(max_length=255, unique=True) def __str__(self): return self.product_name class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) item = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) ordered = models.BooleanField(default=False) def __str__(self): return f"{self.quantity} of {self.item.product_name}" class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) ordered = models.BooleanField(default=False) def __str__(self): return self.user.username view.py: def user_info(request): orders = Order.objects.filter(user=request.user, ordered=True).order_by('-start_date') context = { 'orders': orders, } return render(request, 'home.html', context) home.html: {% for order_item in orders.items.all %} <p>{{ order_item.item.product_name }}</p> {% endfor %} -
Unable to create meeting with Zoom API (response code 200)
I'm using the zoomus(https://github.com/prschmid/zoomus/) Python module to create a Zoom meeting via the Zoom API. However, I did notice that when using client.meeting.create(), I'm getting an http response code of 200 (not 201) which I think means the response is successful but the meeting isn't created. The call I'm making in my django app: # create Zoom meeting client = ZoomClient('xxx', 'xxxx') zoom_format = Event.start_date.strftime("%Y-%m-%dT%H:%M:%SZ") zoom_meeting = client.meeting.create(topic="Meeting", type=2, start_time=str(zoom_format), duration=30, userId=str(updatedEvent.user.email), agenda="", host_id=str(updatedEvent.mentor_user.email)) print(zoom_meeting) The response I'm getting is a 200, but it needs to be 201 in order to actually create the meeting: { "endpoint": "https://api.zoom.us/v2/users/xxx/meetings", "response_headers": [ "Set-Cookie: zm_aid=""; Domain=.zoom.us; Expires=Thu, 01-Jan-1970 00:00:10 GMT; Path=/; Secure; HttpOnly" ], "date_time": "2020-07-28 06:52:33", "method": "GET", "request_body": "N/A", "response": { "page_size": 30, "total_records": 0, "next_page_token": "", "meetings": [ ] }, "request_headers": [ "accept-encoding: gzip, deflate", "accept: */*", "authorization: ******", "connection: close", "user-agent: python-requests/2.24.0" ], "request_params": [ "user_id: xxx" ], "http_status": "200" } Any ideas as to what I'm doing wrong? It looks like the only required information is the date and the userID which I did supply. Thanks for your time.