Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to populate fields that are programmatically added in the Django Form class?
I have a Form with overridden init() because I programmatically create fields based of the models that have another model as foreign key. My form class looks like this: class ProductSpecForm(forms.Form): def __init__(self, *args, **kwargs): category = kwargs.pop('category', None) super(ProductSpecForm, self).__init__(*args, **kwargs) specs = category.categoryspec_set.all() for spec in specs: value = None self.fields[spec.name] = forms.CharField( max_length=50, required=True, label=spec.label(), initial=value ) It works fine when I render it in the template. The problem is when I validate it. It shows me that fields are empty even though I initialize it with request.POST in my view: if request.method == 'POST': spec_form = ProductSpecForm(request.POST, category=category) if spec_form.is_valid(): ... else: print(spec_form.errors) In my opinion, it doesn't work to populate the fields because when I initialize the object with the super().init(), the added fields does not exist yet. When I call the super().init() at the bottom of my overridden init() it does not even work in the template because it does not read the fields at all. Can I somehow call the method that only populates the form object after I initialize all my fields in my init()? -
How can accept and reject order in Django
I want to accept and reject the order. If order will accept it show be saved in db, if order is rejected it show be del, but i am trying but nothing happened View.py class OrderDecision_View(TemplateView): template_name = 'purchase/allOrders.html' def get(self, request, *args, **kwargs): allOrders = Order.objects.all() args = {'allOrders': allOrders} return render(request, self.template_name, args) def post(self, request): orderId = self.request.GET.get('order_id') statusAccept = self.request.GET.get('acceptButton') statusReject = self.request.GET.get('rejectButton') if statusAccept: try: orderDecision = OrderRequest( order_id=orderId, order_status=statusAccept, ) orderDecision.save() return redirect('orderDecision') except Exception as e: return HttpResponse('failed{}'.format(e)) if statusReject: remove = Order.objects.get(pk=statusReject.id) delete(remove) Template {% block content %} {% for allorder in allOrders %} {{ allorder.id }} {{ allorder.orderProduct.product.name }} {{ allorder.orderProduct.quantity }} <button type="submit" name="acceptButton" value="accept"><a href="{% url 'orderDecision' %}?order_id={{ allorder.id }}">Accept</a></button> <button type="submit" name="rejectButton" value="reject"><a href="{% url 'orderDecision'%}?order_id={{ allorder.id }}"> Reject</a></button> {% endfor %} {% endblock % } -
Django Api Json format change
I have my json output in the given format the main body of the article is inside one key only. what i want to do is separate out them based on diffrent paragraphs Current output Output i Want Not exactly in the same format but in a way it can atleast separate out between tags -
django switch Language doesn't work (i18n)
I follow the teaching on the internet . Why do I always fail to translate successfully? Please help me see where I am missing. My {% trans "test" %} never translates. Then I click on other languages in html and it will go to http://127.0.0.1:8000/i18n/setlang/. I don't know where i went wrong . Django ver 3.2 settings.py MIDDLEWARE = [ ... 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ... ] TEMPLATES = [ { ... 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.i18n', ... ], }, }, ] LANGUAGES = ( ('en-us', 'English (United States)',), ('zh-tw', '繁體中文(台灣)') ) LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True LOCALE_PATHS = [Path(BASE_DIR, "locale")] USE_TZ = True projects.urls.py urlpatterns = [ path('i18n/', include('django.conf.urls.i18n')), ] urlpatterns += i18n_patterns( path('', include('App.urls', namespace='app')), ) App.urls.py app_name = 'App' urlpatterns = [ path('index/', views.I18_Test.as_view(), name='index'), ] locale en_us #: templates/hello.html:12 msgid "test" msgstr "EEE" #: templates/hello.html:19 msgid "Language" msgstr "En" zh_tw #: templates/hello.html:12 msgid "test" msgstr "TTT" #: templates/hello.html:19 msgid "Language" msgstr "TW" html {% load i18n %} <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> </head> <body> {% trans "test" %} <nav class="navbar navbar-expand-lg navbar-light navbar-suspend" id="base-navbar"> <div class="container"> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item … -
How does Django find if i a user is authenticated?
I'm building a SPA that uses Django on the backend for authentication, and i'm using Session Authentication. In order to check if a user is authenticated, the SPA sends Django a standard request to an endpoint that will simply return request.user.is_authenticated. This works because the sessionid cookie is always sent from the client to the Django app. In another part of the SPA app, for some reason the cookie is not being sent with the request, so Django always returns False even when the user is logged in. The solution i found is to send the sessionid cookie in the POST request body, but this will still return False. Since that didn't work either, i had this idea: if the sessionid cookie is not in the cookies but it is in the request's body, set the cookie manually from the view: def checkAuth(request): if request.method == 'POST': session_cookies = json.loads(request.body.decode('utf-8')) request.COOKIES['sessionid'] = session_cookies['sessionid'] request.COOKIES['csrftoken'] = session_cookies['csrftoken'] print(request.COOKIES) response = {'state': str(request.user.is_authenticated), 'username': str(request.user)} return JsonResponse(response, safe=False) Here i see the cookies being set in the view: {'sessionid': 'somecookie', 'csrftoken': 'sometoken'} But request.user.is_authenticated still returns False. Why is that? Is there any way i can solve this? -
How to make django project licensable?
I have a django project that is deployed at the customer site and managed by their employees. This on-premise installation consist of various components like nginx, uwsgi, postgres, task schedulers, etc which are packaged and deployed on a server within customer's VPC. The entire project is an enterprise edition consisting of complex workflows and features specific to the business use-case. Now, my task is to make this piece of software licensable by pricing certain pages, reports, features, modules etc as per the agreement with the client. The project contains role based access control as well as a provision to turn features on/off based upon some config settings in the django project. I wish to make this project licensable by allowing customer to subscribe for the features they required and provide them with some sort of activation/license key that they can add it to their deployed project. The challenge is that the code is exposed to the customer since it is deployed at their site and someone can crack the code to turn on unpaid features. Can anyone please guide me on best practices for the same? Reagrds -
Django deployment error deango.core.exceptions.ImproperlyConfigured
Hey i have an django application which is working fine locally but its not working when it is hosted on a web showing below error django.core.exceptions.ImproperlyConfigured: Error loading pyodbc module: /lib/x86_64-linux-gnu/libm.so.6: version `GLIBC_2.29' not found (required by /home/site/wwwroot/antenv/lib/python3.7/site-packages/pyodbc.cpython-37m-x86_64-linux-gnu.so) Did i miss anything at the time of hosting? -
How to use the form values inside form_valid function in django
I would like to know how to use the inputted values into a form in the form_valid function in my view. First of all, here is the view: class OrganisorStudentUpdateView(OrganisorAndLoginRequiredMixin, generic.UpdateView): # some code form_class = OrganisorStudentUpdateModelForm # some code def form_valid(self, form, *args, **kwargs): # some variables from form print(form.instance.weekday.all()) # some extra mathematical code using the values of form.instance.weekday.all() # update some of the other form fields print(form.instance.weekday.all()) return super().form_valid(form, *args, **kwargs) weekday in form.instance.weekday.all() is a many to many field in the form that is linked to another model. The problem is that I need to click the update button twice in order to do the mathematical code with the values from weekday. Here is a simple example. My current values for the weekday form field is the "Monday", "Wednesday", "Friday" checkboxes checked. When I update the form without changing anything, the following is printed: <QuerySet [<Weekday: Monday>, <Weekday: Wednesday>, <Weekday: Friday>]> <QuerySet [<Weekday: Monday>, <Weekday: Wednesday>, <Weekday: Friday>]> Then, I will change my values for weekday to "Tuesday" and "Thursday". I updated. I got this: <QuerySet [<Weekday: Monday>, <Weekday: Wednesday>, <Weekday: Friday>]> <QuerySet [<Weekday: Monday>, <Weekday: Wednesday>, <Weekday: Friday>]> This is not what I want, as … -
C++ server and django as client connection
I have wanted to make my a socket connection between my django client and c++ server.As press button on my django webpage it will reflect in my client -
HTML page running in Django does not look the same on two different machines
I am not very experienced (read as: next to no experience) with Django and HTML, but I am trying to make a web page with some buttons and CSS animations. I am working together with a partner, and while working together, we noticed that the elements positioned around on the page appear in very different positions between the two of us. What shows up on my end: What shows up on their end (which is what we are trying to get at, positioning the images over the bubbles correctly): I am mostly interested on why it happens that we have the exact same files but our pages, both opened in Chrome, same screen ratios etc, look different. Also why it happens that I make changes to the CSS file and the page does not change at all; and I'm talking changes such as removing all positioning of the images, which should align them to the up left corner, but they sit in place(yes I did save, reload the page, restart the server etc). -
Django - querying multiple values using foreign keys
I am new to Django and trying to understand the model relationships. I have two models: class Author(models.Model): author_name = models.Charfield(max_length = 15) class Books(models.Model): book_name = models.CharField(max_length = 15) authors = models.ForeignKey(Author) In my views.py I am accessing the records like this: class BooksViewSet(APIView): def get(self, request): data = Books.objects.all() Now suppose I have multiple books with multiple authors, how do I create an API which would include all the authors of the books? I think I need to filter out the values but am not exactly sure how it is done. Currently, I get only one author using the above views.py. Sorry if I missed the obvious. Thanks for your time in advance. -
How to insert an image in a specific area in a bootstrap crad?
I am trying a attach an image in a specific area in a card, but I don't know how to. I am sorry if it's a silly question, I am a beginner in terms of html. So can anyone please show me how to do it? I am using Django. For example, If I want to add an image in that specific blue outlined area, what should I do? My code {% for fixture in fixtures %} <div class="card bg-light"> <div class="card-header" style="color:red;" > Featured </div> <div class="card-body"> <h5 class="card-title" style="color:black;">{{ fixture.home_team }} vs {{ fixture.away_team }}</h5> <p class="card-text" style="color:black;">{{ fixture.description }}</p> <form style="color:black;"> <h5><label for="watching">Watching?</label> <input type="checkbox" id="watching" name="watching" value="watching"> </h5> </form> </div> </div> {% endfor %} -
Input fields are makred always RED in Djano UserRegistrationForm
I am creating a User authentication system in Django. The first page I set is to Register a new user. For that, my views.py is below: views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from .forms import UserRegisterForm from django.contrib import messages # To give an alert when a valid data is received # Create your views here. def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created!') return redirect('login') else: form = UserRegisterForm(request.POST) return render(request, 'Agent/register.html', {'form': form}) and the html file is given below: register.html {% extends "client_management_system/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Join Today</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Sign Up</button> </div> </form> <div class="border-top pt-3"> <small class="text-muted "> Already Have An Account? <a class="ml-2" href="{% url 'login' %}">Sign In</a> </small> </div> </div> {% endblock content %} and the URL pattern for register page is given below: from django.contrib import admin from django.urls import path, include from django.contrib.auth import views as auth_views from Agent import views as agent_views urlpatterns = [ path('admin/', admin.site.urls), path('', include('client_management_system.urls')), … -
How to fix Django Duplicate key form from being valid and saved?
This is my views.py file and Im getting this message DETAIL: Key (member_id, match_id)=(4, 20) already exists. However is see that Valid is printing so its obvious the is_valid() method doesnt catch this duplicate key. def update_batter_form(request, match_id, batting_id): """Edit existing batter form view.""" obj = Batting.objects.get(pk=batting_id) form = BattingForm(instance=obj) batting_list_bn = Batting.objects.order_by('batter_number') \ .filter(match_id=match_id) match = Match.objects.get(pk=match_id) if request.method == 'POST': print("Printing POST") form = BattingForm(request.POST, instance=obj) print(obj) if form.is_valid(): print("Valid") form.save() return redirect('/club/match/'+match_id+'/batter/'+batting_id) else: print(form.errors) return redirect('/club/match/' + match_id + '/batter/' + batting_id) context = { 'form': form, 'batting_list_bn': batting_list_bn, 'match': match } return render(request, 'club/batter_update.html', context) How is it I catch this issue? -
Django unit test failing, but if I manually test a view in browser it works
I am working on a page to create an order when a customer post address details. When I test the view in the browser it works. I want to test if an order was created. I submit a form with address details, After submiting the data the order is created. I check in the admin site to verify the order has been created. I find it has been created. When I run python manage.py test order it fails. No order is found when I make a query for that recently created order. Below is the code for the order_create view. from django.shortcuts import render, redirect from django.urls import reverse from django.conf import settings from .forms import AddressForm from users.models import Customer from .models import Delivery, Order, OrderItem, Address from cart.cart import Cart from django.utils.translation import ugettext_lazy as _ from django.core.exceptions import ValidationError from django.conf import settings # Create your views here. def order_create(request): form = AddressForm() # Get the cart from the session cart = Cart(request) for item in cart: print(item) # If the cart does not exist then redirect to shops so the # user can start shopping if not cart: return redirect(reverse("core:product_list")) # Check if it is POST … -
How do I run Django Management > Commands as cron jobs in Elastic Beanstalk running nginx
I'm upgrading a Django application from Elastic Beanstalk Python 3.6 running on 64bit Amazon Linux to Python 3.8 running on 64bit Amazon Linux 2 and moving from the Apache server to Nginx. I'm trying to set up the cron jobs. On Linux 1 I had 03_files.config container_commands: ... 02_cron_job: command: "cp .ebextensions/crontab.txt /etc/cron.d/autumna_cron_jobs && chmod 644 /etc/cron.d/autumna_cron_jobs" #leader_only: true ... with crontab.txt # Set the cron to run with utf8 encoding PYTHONIOENCODING=utf8 ... 30 0 * * * root source /opt/python/current/env && nice /opt/python/current/app/src/manage.py test_cron ... # this file needs a blank space as the last line otherwise it will fail I've converted this to 03_cron.config container_commands: 01_cron_job: command: "cp .ebextensions/crontab.txt /etc/cron.d/autumna_cron_jobs && chmod 644 /etc/cron.d/autumna_cron_jobs" #leader_only: true with crontab.txt # Set the cron to run with utf8 encoding PYTHONIOENCODING=utf8 ... 30 0 * * * root source /var/app/venv/staging-LQM1lest/bin/activate && nice /var/app/current/manage.py test_cron ... # this file needs a blank space as the last line otherwise it will fail I've actually got it running every 10 minutes to try and understand what is happening. When I look in the logs, withing \var\log\cron I have: Apr 9 09:10:01 ip-172-31-41-78 CROND[22745]: (root) CMD (source /var/app/venv/staging-LQM1lest/bin/activate && nice /var/app/current/manage.py test_cron >> /var/log/test_cron.log.log 2>&1) … -
for loop is showing single object in javascript
I am building a Social media webapp. AND i am stuck on a Problem. What i am trying to do :- I build story feature in webapp ( like instagram stories ). The Problem is :- When two different users post images in stories then images are showing in single story BUT i am trying to show if two users post two images in stories then show in different stories.- There are two stories posted by different users BUT they both are showing in one story. I think loop is not working correctly.I tried many time but nothing worked for me. <script> var currentSkin = getCurrentSkin(); var stories = new Zuck('stories', { backNative: true, previousTap: true, skin: currentSkin['name'], autoFullScreen: currentSkin['params']['autoFullScreen'], avatars: currentSkin['params']['avatars'], paginationArrows: currentSkin['params']['paginationArrows'], list: currentSkin['params']['list'], cubeEffect: currentSkin['params']['cubeEffect'], localStorage: true, stories: [ // {% for story in stories %} Zuck.buildTimelineItem( 'ramon', '{{ user.profile.file.url }}', '{{ story.user }}', 'https://ramon.codes', timestamp(), [ [ 'ramon-1', 'photo', 3, // '{% for img in story.images.all %}' '{{ img.img.url }}', '{{ img.img.url }}', // '{% endfor %}' '', false, false, timestamp(), ], ] ), // {% endfor %} ], }); </script> I have no idea what to do. Any help would be Appreciated. Thank You in … -
Django .query attribute behavior
I have been trying to see raw SQL queries, which Django ORM makes and here is a problem. When I am typing print(User.objects.filter(username='adm').query), I get SQL query, but if I type previous statement without print function, I get <django.db.models.sql.query.Query object at 0x000002AA92E6DB88>. I can suppose, it happens because .query attribute mutates Django ORM query into just query object (how we can see above). So, is there one, who can tell me what happens under the hood? -
How to debug Python Django Errno 54 'Connection reset by peer'
I am doing a successful ajax call and then refresh the page (using window.location.reload()) to show the changes made in the database. Doing this throws an error: Exception happened during processing of request from ('127.0.0.1', 49257) Traceback (most recent call last): File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/socketserver.py", line 720, in __init__ self.handle() File "4_Code/Floq_Django/venv/lib/python3.8/site-packages/django/core/servers/basehttp.py", line 174, in handle self.handle_one_request() File "4_Code/Floq_Django/venv/lib/python3.8/site-packages/django/core/servers/basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/socket.py", line 669, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 54] Connection reset by peer I am a bit lost, why this is happening?! As soon as I remove window.location.reload() and only do the ajax call I do not get any errors... Any suggestions/hints/tipps? Thanks a lot. -
Django, how to hold different time in database (not UTC)
I have a working website made in django that contains models with DateTimeField, it's a simple timestamp holding time of creation, it looks like this: timestamp = models.DateTimeField(auto_now=True) And also DateTimeField that I update later on: **MODEL.PY** data_zal = models.DateTimeField() **VIEWS.PY** t = Zam(data_zal=timezone.now()) t.save() My settings are as follows: TIME_ZONE = 'Europe/Warsaw' USE_I18N = True USE_L10N = True USE_TZ = True Everything works perfectly, time is displayed correctly (UTC+2). But in database (I checked sqlite and mysql- development/production) it is seen as UTC. Thanks to SELECT now(); I can see the UTC+2 time. It wouldn't be a problem but I have a program that connects to my database and fetches data to process it further. It is starting to cause some problems coz of the mismatch of what client sees and what program sees. Is there any way I can format time in database to correct value (UTC+2)? -
How can I add data to each entry of a ManyToMany field in an object?
I'm kind of new to Django and databases. I'm working on a database that will save the type and mass of meals in a tray, in public restauration. For instance, a tray will be linked to a specific service and could contain 100g pasta and 80g cake. I'd like a model "MenuItems", storing various informations on each recipe, this is pretty easy, it works fine. Then I created "Service", which stores the date of a service, and a ManyToManyField registering the menu, that is to say the MenuItems that were offered on that date. This works fine too. But the tricky part for me is this: In a third model, called "Trays", I'd like to: -first, choose the Service this tray was taken from (ex: 09/04/2021) -then choose the MenuItems that were in this specific tray, among those on the menu for that service (ex: say on that service there was pasta, cake, meat and fruits, I'd like not to be suggested any other item) -and finally, for each of the MenuItems in the tray, add the mass of each item. (ex: if there was only meat and cake in this specific tray, I'd like to add pasta and fruits … -
jAutoCalc wildcard for element name with number index
So I want to use jAutoCalc for my website that will do a calculation for some of its elements. The jAutoCalc do the calculation by inserting an element with some formula, for ex: <input type="text" name="item_total" value="" jAutoCalc="{qty} * {price}"> Here, the formula is the jAutoCalc="{qty} * {price} part In my case, I'm using Django Framework that creates a table automatically that will gives number index to each of it item elements based on the row of the table, for ex: FormName-1-FieldName1 | FormName-1-FieldName2 FormName-2-FieldName1 | FormName-2-FieldName2 FormName-3-FieldName1 | FormName-3-FieldName2 FormName-4-FieldName1 | FormName-4-FieldName2 Now is there any method that I can do to iterate the multiplication based on the index of the element? For example how to do a multiplication based on the index number of the element? I'm thinking of using a wildcard to iterate through the elements that I want to calculate but is it possible to put it inside the name in the formula -
Django-q how to delete scheduled tasks
I'm using django-q to schedule monthly event for sending emails. After several testing runs, I realized that each time I execute the: Schedule.objects.create(func='app.email.send_monthly_email',schedule_type=Schedule.MONTHLY,repeats=-1) this schedule event is cached and it will run the next time I start qcluster. How to I delete all the scheduled tasks in django-q? Or how can I have a clean start every time I run qcluster? -
How to get the url parameters and display it in the template file?
For instance my url ../home/regular will return a list of all accounts that are of regular accounts. How can I include the "regular" into the context data that is returned to my template file from my get_queryset? Alternatively I tried to use the request.path like from this post in my template file but I don't know how to get only the last last parameter. **Note that the url might not include the 'home/regular' and I have set the default to "regular" accounts. -
results_picker returning none when input is incorrect and then corrected
import random def user_input_checker(data): if data not in ["rock","paper","scissors"]: print("something went wrong...") user_input_da() else: return data def user_input_da(): user_data = input("Please enter either rock,paper or scissors") user_input = user_input_checker(user_data) return user_input def computer_input(): computer_choices = ["rock","paper","scissors"] computer_picks = random.choice(computer_choices) # picking random value from array return computer_picks def results_picker(): user = user_input_da() comp = computer_input() if user == comp: print("The game is a draw") else: print("One of yous won ou said =>",user,"\n""The computer said =>",comp)`enter code here` Hi i am new to the python program language. The issue I am facing is that when I run the program with the correct input the programs works fine, but when I run the program with an incorrect input in the firsttime and reenter the new the new value it returns none How do I solve this please?