Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it forbidden to use `timezone.now()` in django model helper methods?
I have a Django model that is responsible for storing verification tokens for the user's cell phone verification. The method below is part of that model which later I use in the view functions to restrict users. (They're allowed to ask for a new token every 2 minutes.) however, it doesn't work very well and on some occasions returns true even after hours. finally, I got suspicious about that, is this right to implement such a method in Django models? what about other places I used timezone.now() in the model? for example where I call that to set a field value? def token_is_generated_recently(self): """ Checks whether the verification token is generated during last 2 minutes or not """ return (self.token_created_time > timezone.now() - timedelta(minutes=2)) -
Django FilterSet field lookup dictionary format
I am learning Django, and started creating a web app, and trying to use django_filters with django_tables2, to filter on the columns in the table. What I am tyrying to change is the default 'exact' lookup method, according to the django_filters instructions. This is the example they show at FilterSet Options class UserFilter(django_filters.FilterSet): class Meta: model = User fields = { 'username': ['exact', 'contains'], 'last_login': ['exact', 'year__gt'], } What happens is that if I don't include 'exact' in the list of lookups (like for the shop__shop field below), the field is not rendered on the page. class ReceiptFilter(django_filters.FilterSet): class Meta: model = expenses fields = { 'purchase_date': ['exact'], 'shop__shop': ['iexact'], 'payment_method__payment_method': ['exact'], } Please, click here to see the web page rendered If I leave 'exact' in front of the lookup I want to add (as in the instructions), it doesn't seem to have any effect, the filter works like it was an 'exact' lookup. What am I doing wrong? Thanks, Miki. -
Error filtering a ForeignKey with UUID as pk
I'm using django-filters to filter data and display it in a table. One of the values is a ForeignKey that has as pk an UUID. When I use lookup_expr='icontains' then I get the following error: "Related Field got invalid lookup: icontains" How can I use lookup_expr='icontains' for a ForeignKey with a UUID pk? Thank you in advance. models: class Data(models.Model): data_id = models.UUIDField(primary_key=True, default=uuid.uuid4) data_device_id = models.ForeignKey(Device, models.SET_NULL, blank=True, null=True) class Device(models.Model): device_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True) device_name = models.CharField(max_length=64) Filter: class DataFilter(django_filters.FilterSet): data_id = django_filters.CharFilter(label='Data id', lookup_expr='icontains') data_device_id = django_filters.CharFilter(label='Device id', lookup_expr='icontains') #ERROR HERE class Meta: model = Data fields = {'data_id','data_device_id'} -
desc="No web processes running" heroku project
I have a Django app which works when I run it locally heroku local. When I push my code to heroku git push heroku main it pushes without any problem, but when I opening my site it showes an 503 error in console 1 GET https://XXX.herokuapp.com/ 503 (Service Unavailable) inside my logs I get this at=error code=H14 desc="No web processes running" method=GET path="/" host=omylibrary.herokuapp.com request_id=lotofnumbers fwd="somenumbers" dyno= connect= service= status=503 bytes= protocol=https from this question I assume that the problem is in ProcFile if more precisely in web. My Procfile looks like this web: gunicorn --chdir ./Lib library.wsgi --log-file - I also tried this heroku ps:scale web=1 from previous answer. What Is wrong here ? -
Group name not showing on production
Im using Wagtail and i want to display the user group name in the admin. On local server everything works fine and the group name is displayed as expected. I tried adding this to the template but none work on production all worked local: {{ user.groups.all }} {{ user.groups.all.0 }} {{ request.user.groups.all }} {{ request.user.groups.all.0 }} -
Use cbv vIews in other place
Hello i wrote a simple login view (for example) like it: class SingInView(LoginView): template_name = 'account/auth/login.html' redirect_authenticated_user = True form_class = LoginForm and i wanna know it possible to use it in another place like: SignUpView.as_view(username="example", password="exampleStrong") there are any way?? -
How can I convert string of datetTime to dateTime
from django.urls import path from Reservations import views urlpatterns = [ path('rent/<takeDate>/<returnDate>/<id>', views.rent, name='rent'), ] def rent(request, takeDate, returnDate,id): print(takeDate) # take date is (Dec. 23, 2020, 8:23 p.m.) , i want to change it to datetime return render(request, 'reservations/rent.html') -
How can we show success message on signup page of verify gmail account in django and bootstrap?
Here i'm able to successfully register account from django but i'm having issue with showing success messages to verify the email account. I am using django and bootstrap. So tell me how to show and style those messages. accounts/views.py class SignUp(CreateView,SuccessMessageMixin): form_class = UserCreateForm template_name = 'accounts/signup.html' def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False # Deactivate account till it is confirmed user.save() current_site = get_current_site(request) subject = 'Activate Your Believer Account' message = render_to_string('accounts/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) success_registered_message = "You're register successfully" verify_message = "Please verify your account from gmail" return success_registered_message,verify_message return render(request, self.template_name, {'form': form}) templates/accounts/signup.html {% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %} if more details are require then tell in a comments. I'll update my question with that information. Thank you. -
Is there a way that Users can have options to disable comments on their Blog Post?
I am going through a Django tutorial and I am making a personal blog app , like users can create blogs and comment on it. Question I have built the comment system and Now i think, what if a user don't want to let other users make comments on his/her blog. I mean , Is there a function of code in django ? , that users can decide they want comments on blog post or NOT. I have searched it but i found nothing. So if you know this function then Please tell me. I will really appreciate your Help -
Calculate the sum and multiply with the quantity to get the total in django
I have the code which calculates the sum just fine, now my question is it possible to multiple each price by quantity and then get the total sum after that in a cart on my website. I have tried with all of my logic but i have failed. The idea is to get the price of an item added to cart and multiply it by quantity and then get the total. Here is my cart mode. models.py: #cart model class Cart(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) number_of_items = models.IntegerField(default=0) user = models.ForeignKey(User, on_delete=models.CASCADE) added_datetime = models.DateTimeField(auto_now_add=True) def __str__(self): return self.item.name #Item model class Item(models.Model): CONDITION = ( ('new', 'new'), ('used', 'used'), ('not applicable', 'not applicable'), ) name = models.CharField(max_length=250) owner = models.CharField(max_length=250, default='Ludocs-emark') category = models.ForeignKey(ItemCategories, on_delete=models.CASCADE) sub_category = models.ForeignKey(SubCategory, on_delete=models.CASCADE) tag = models.ForeignKey(Tag, on_delete=models.CASCADE) Condition = models.CharField(max_length=250, null=True, choices=CONDITION) price= models.IntegerField(default=0) number_of_items = models.IntegerField(blank=True) specification_one = models.CharField(max_length=250, blank=True) specification_two = models.CharField(max_length=250, blank=True) specification_three = models.CharField(max_length=250, blank=True) specification_four = models.CharField(max_length=250, blank=True) specification_five = models.CharField(max_length=250, blank=True) specification_six = models.CharField(max_length=250, blank=True) available_colors = models.CharField(max_length=250, blank=True) description = RichTextField() thumbnail = models.ImageField(default='default.png', upload_to='images/') image_one = models.ImageField(upload_to='images/') image_two = models.ImageField(upload_to='images/') image_three = models.ImageField(upload_to='images/') image_four = models.ImageField(upload_to='images/') added_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name views.py file … -
django and "more information" forms
I have a form that, on submit, displays a form asking for more info. I'm sure this is easy if I could name it, but it's not quite obvious to me. I have a form that looks like this: class QuickMailingListSignupForm(ModelForm): class Meta: model = User fields = ('email',) labels = { 'email': "Adresse mél", } I stick it on various pages so people can enter an email address and sign up for my newsletter. On submit (to a different path/page), I ask you for a captcha. class MailingListSignupForm(ModelForm): captcha = CaptchaField( label="Je suis humain", help_text="...", error_messages=dict(invalid="captcha incorrect, ...")) ... class Meta: model = User ... The first form, which just gets the email, forwards to this view, whose job is to manage the remainder of the interaction: class QuickMailingListSignup(FormView): template_name = 'mailing_list/quick_signup.html' form_class = MailingListSignupForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['...'] = ... return context def form_valid(self, form): # ?? So my problem is that I'll never get to that # ??: the first form is submitting a QuickMailingListSignupForm and the second should either process a MailingListSignupForm or else extract the email address from the QuickMailingListSignupForm, push it into a MailingListSignupForm, and then go on to manage that … -
Django version of request.args.get() function in Flask
I am migrating my code from Flask to Django and this line from Flask doesn't seem to work in Django auth_token = request.args['code'] I googled a lot but can't seem to find the correct parameter to request the authorization token! -
Django gives "502 Bad Gateway" error on Google App Engine
I'm trying to deploy a Django application on Google App Engine in the Standard Python3.8 environment. I followed all the steps in this document. App runs fine on my local with google cloud database. However I receive 502 Bad Gateway error visiting Web Url. I found a lot of different questions but technology is changing a lot, and none of them helped so far. Lastly, I came across this question today, but it says create a gcloud.py file that I never seen in google documents that's why I haven't applied that solution but decided to ask you. I get this error when visiting page Traceback (most recent call last): _find_and_load (<frozen importlib._bootstrap>) And this is the stack trace from the error: File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked: ModuleNotFoundError: No module named 'main' at _find_and_load (<frozen importlib._bootstrap>:991) at _gcd_import (<frozen importlib._bootstrap>:1014) at import_module (/opt/python3.8/lib/python3.8/importlib/__init__.py:127) at import_app (/layers/google.python.pip/pip/lib/python3.8/site-packages/gunicorn/util.py:358) at load_wsgiapp (/layers/google.python.pip/pip/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py:39) at load (/layers/google.python.pip/pip/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py:49) at wsgi (/layers/google.python.pip/pip/lib/python3.8/site-packages/gunicorn/app/base.py:67) at load_wsgi (/layers/google.python.pip/pip/lib/python3.8/site-packages/gunicorn/workers/base.py:144) at init_process (/layers/google.python.pip/pip/lib/python3.8/site-packages/gunicorn/workers/base.py:119) at init_process (/layers/google.python.pip/pip/lib/python3.8/site-packages/gunicorn/workers/gthread.py:92) at spawn_worker (/layers/google.python.pip/pip/lib/python3.8/site-packages/gunicorn/arbiter.py:583) my_site/wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_site.settings") application = get_wsgi_application() This is my app.yaml runtime: python38 handlers: # This configures Google App Engine to serve the files in the app's … -
How to tie id of question field to answer filed in formset ? django
When I am trying to choose an answer for the second question, the radio selected from the first question shifts to the second one. Am I going the right way? if not, then what is the best way to do this? index.html <form action="{% url 'index'%}" method="POST"> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} {{ form.teacher }} {{ form.department }} {% for question in question %} {{ question }} {{ form.answer }} {% endfor %} {% endfor %} <input type="submit" value="Vote"> models.py class Student_Answer(models.Model): teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) department = models.ForeignKey(Department, on_delete=models.CASCADE) answer = models.SmallIntegerField(choices=RATING_CHOICES, default=1) views.py def index(request): question = Question.objects.all() AnswerFormset = formset_factory(AnswerForm) if request.method == "POST": formset = AnswerFormset(request.POST) if formset.is_valid(): for form in formset: form.cleaned_data form.save() return HttpResponseRedirect('/submit/') else: formset = AnswerFormset() context = { 'formset': formset, 'question': question } return render(request, 'index.html', context) -
Django - 'elif'. Did you forget to register or load this tag?
I am developing a simple Django app. Is the piece of code below even valid? My code : {% if request.session.role is "Manager" %} {% extends 'manager_base_nav.html' %} {% elif request.session.role is "Agent" %} {% extends 'agent_base_nav.html' %} {% else %} {% extends 'customer_base_nav.html' %} {% endif %} -
{% include %} tag does not appear Django
I am trying to make include {% include %} in Django. But I face some trouble This is the base form.html file that I trying to inherit: <form class = 'form' method = 'POST' action = ""> {% csrf_token %} {{form.as_p}} <input type= "submit" value = "{{ btn_title }}" /> </form> and this is the inherited create.html: **{% include "form.html" with form=form btn_title = "Tweet" %} But Actually I have this error:- TemplateSyntaxError at /tweets/2/update Unknown argument for 'include' tag: 'input|btn_title'. Request Method: GET Request URL: http://localhost:8000/tweets/2/update Django Version: 3.0.6 Exception Type: TemplateSyntaxError Exception Value: Unknown argument for 'include' tag: 'input|btn_title'. Exception Location: C:\Python\lib\site-packages\django\template\loader_tags.py in do_include, line 311 Python Executable: C:\Python\python.exe Python Version: 3.6.8 Python Path: ['D:\From Torrents\Web , flask , django from torrent\[FreeCourseSite.com] ' 'Udemy - Tweetme Build a Twitter-like app step by step with Django\src', 'C:\Python\python36.zip', 'C:\Python\DLLs', 'C:\Python\lib', 'C:\Python', 'C:\Users\pc\AppData\Roaming\Python\Python36\site-packages', 'C:\Users\pc\AppData\Roaming\Python\Python36\site-packages\win32', 'C:\Users\pc\AppData\Roaming\Python\Python36\site-packages\win32\lib', 'C:\Users\pc\AppData\Roaming\Python\Python36\site-packages\Pythonwin', 'C:\Python\lib\site-packages'] Server time: Mon, 21 Dec 2020 16:35:25 +0000 -
How to access data from a webpage using Django?
I am new to Django. I am trying to access this webpage's data and store it in some database (like sqlite). But I couldn't fetch the data. I am not sure whether this task requires the use of IMDB API or if it's possible without the use of it. This is what I have tried: # view.py from django.shortcuts import render import requests from django.http import HttpResponse import urllib.request, json def index(request): r = requests.get('https://www.imdb.com/chart/top?ref_=nv_mv_250').json() d = {'v': r} return render(request, 'index.html', context = d) I am getting this error by running the above code: JSONDecodeError at / Expecting value: line 4 column 1 (char 3) It would be great if someone can help me out. -
Add arguments from strings to a python function
I want to create a method, which can dynamically add keyword arguments to another function that I intend to call within this method, something like: def func(query1: str, query2: str): func2(query1, query2) where, the query1, query2 in the func are strings of the type "a=3", "b=4", the func should essentially take these strings and then call them in a keyword argument way like: func2(a=3, b=4) I want to know if this kind of implementation is even possible or if there are any workarounds for achieving the same goal. The reason why I want this is because I have a django application in which I want to create a model where I can store some filter rules and apply them each time that view is called, so I want to allow the user to select a bunch of filters and then I want to store them in the database and call those rules to get a queryset specific to that user's preferences. def some_view(request): # Get the filter rule strings from the model queryset = some_model.objects.filter(<Pass all the rules here from those strings>) return Response edit: Add more details on the use case -
How can I modify exisitng pdf?
how can I add text over different PDF templates, I want create Automate application to fill existing pdf with different layout, The issue i need to import pdf and automated fill it from model using django admin, there any way to do that, i searched in many pkg all library using to convert form template to pdf or only extract text from pdf! -
How can i use MultiSelectField in drf patch?
i have MultiSelectField in model field.when i want to use field in drf patch, i get this error: ''' rest_framework.exceptions.ValidationError: {'visit_type': [ErrorDetail(string='"[0]" is not a valid choice.', code='invalid_choice')], 'visit_method': [ErrorDetail(string='"[]" is not a valid choice.', code='invalid_choice')], 'visit_duration_plan': [ErrorDetail(string='"[]" is not a valid choice.', code='invalid_choice')]} ''' -
how to render image and remove the html tags in content from django ck editor in django template
I tried so many times , but i didn't get any solution for rendering image and content without html tags , i used {{content|safe}} for rendering content on template and i tried strip_tags for html tags removal but it didn't work well for url's , can anyone suggest me why i am getting html tags while rendering in templates. Models.py class Product(models.Model): name = models.RichTextUploadingField(max_length="125") description = models.RichTextUploadingField() views.py def poll(): context = questions.object.all() return render(request, 'quiz.html', context) template: <html> <body> {% for q in context %} <div id="section{{forloop.counter}}"> <script type="text/javascript"> marks.push(Number("{{marks}}")); neg_marks.push(Number("{{neg_marks}}")); </script> <p id="{{forloop.counter}}"><span>{{forloop.counter}}.{{q.question|linebreaks}} </span></p> {% if q.figure %} <img src="{{q.figure.url}}" alt="image" class="img-fluid" width="200px" height="200px"><br><br> {% endif %} <input type="radio" id="{{forloop.counter}}option1" name="{{forloop.counter}}" value="1"> <label for="{{forloop.counter}}option1">{{q.option_1|safe }}</label><br> <input type="radio" id="{{forloop.counter}}option2" name="{{forloop.counter}}" value="2"> <label for="{{forloop.counter}}option2">{{q.option_2|safe}}</label><br> {% if q.option_3 != "" %} <input type="radio" id="{{forloop.counter}}option3" name="{{forloop.counter}}" value="3"> <label for="{{forloop.counter}}option3">{{q.option_3|safe}}</label><br> {% endif %} {% if q.option_4 != "" %} <input type="radio" id="{{forloop.counter}}option4" name="{{forloop.counter}}" value="4"> <label for="{{forloop.counter}}option4">{{q.option_4|safe}}</label><br> {% endif %} {% if q.option_5 != "" %} <input type="radio" id="{{forloop.counter}}option5" name="{{forloop.counter}}" value="5"> <label for="{{forloop.counter}}option5">{{q.option_5|safe }}</label><br> {% endif %} {% if forloop.first %} <p role="button" class="btn btn-warning" id="next{{forloop.counter}}" onclick="next_section(this.id)" style="float: right;">Next</p> {% elif forloop.last %} <p role="button" class="btn btn-warning" id="prev{{forloop.counter}}" onclick="prev_section(this.id)" style="float:left;">Previous</p> {% else %} … -
GET and POST from Chrome Extension to Django Server
I am trying to get information from a view I created in Django (using Django as a REST API) by calling it from my Chrome Extension, having the view perform a quick calculation and then posting that result to the chrome extension. I am not able to successfully get any data from the view, but the view is working and running just fine. What should my .js file look like to send a GET request to the Django view? Here is the .js (NOTE: to test I am simply trying to get the ip address to show the connectivity works): fetch("http://127.0.0.1:8000/") .then(function (response) { return response.json(); }) .then(function (myJson) { document.getElementById("place").innerHTML = myJson.ip; }) .catch(function (error) { console.log("Error: " + error); }); -
Oracle backend does not support timezone-aware datetimes when USE_TZ is False
I am saving date-time value in oracle using Djanog. My model has last_updated_at = DateTimeField(). This date-time value will be displayed by other application that is not developed in Django. I set last_updated_at with date-time which is not in UTC but it's always saving it in UTC timezone. When I set USE_TZ = False it gives error Oracle backend does not support timezone-aware datetimes when USE_TZ is False I also tried TIME_ZONE = 'Asia/Karachi' in settings.py but still date is saved in UTC. Any who can help please??, Thanks -
Please I have been encountering this problem over a week
Anytime I run my login url ,it runs twice in the terminal the first being "GET / login". Then it prints some things from the view. "POST / login". Unknown The post / login always return unknown Please I need help -
how to create a button or an option to connect to Data in Django web app
I wanted to create a Web app(basic analytics app) using Django,in which there should be a option to connect to databases or connect to CSV e.t.c, and that data needs to be populated on the screen(app). Iam just a beginner,Please help me with any necessary code or requirements. Thanks in advance for any help or advice.