Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Submitting multiple Django forms from duplicated fields in template
I know there are many related questions to this one, but everything I am trying seems to fail. I am attempting to create a form where the user can record the games they have played and record who won and what points they got. This would mean a certain portion of the form could be dynamic to add as many players as the user wants but the game and team would always remain the same. So I was looking for a form like this: form I was thinking that formsets might be the answer but it looks like that copys the whole form multiple times. Also anytime I make a formset I have trouble passing the user to the form. Heres what I have so far: view.py def test(request): AwardFormSet = formset_factory(TestAwardForm, extra=2) form_class = AwardFormSet() if request.POST: form = form_class(request.user, request.POST) if request.method == 'POST': if form.is_valid(): obj = Award() obj.player_gameboard_id = PlayerGameboard.objects.get(player_id=form.cleaned_data['player'], gameboard_id=form.cleaned_data['gameboard']) obj.position = form.cleaned_data['position'] obj.points_awarded = form.cleaned_data['points_awarded'] obj.team_game = form.cleaned_data['team_game'] obj.game_name = form.cleaned_data['game_name'] obj.save() return HttpResponseRedirect(reverse('gameboard')) else: form = form_class(request.user) return render(request, "awards/test.html", {'form': form}) forms.py class TestAwardForm(forms.Form): gameboard = forms.ModelChoiceField(queryset=Gameboard.objects.none(), label='Gameboard') player = forms.ModelChoiceField(queryset=User.objects.all(), label='Player') game_name = forms.CharField(label='Game Name', max_length=200) position = forms.IntegerField(label='Place') team_game = … -
Bootstrap4 table in django
I am a beginner to both Django and Python and have been working through a simplified example table for a future project idea, using a bootstrapped ver. 4 (sb-admin template style) connected to my model, which, for the most part shows correctly except for one aspect. I have set my table class to: table table-bordered table-hover table-striped I have also added coloured emphasis arguments for one column of data and emphasis colour to another to show that it is calculated and that is working as expected. However, when I attempt to change the table head row class to dark (which I think looks nicer), I lose the striped and hover formatting table elements I mentioned above. In addition, I lose my emphasis colour functionality (except on hover), if I attempt to change the table class to table-sm in order to make things smaller and more compact. Any ideas for someone that wants it all? Is this just a limitation to the free bootstrap style? -
How do I edit my axios post request so that I successfully send a put request?
As far as I'm aware I should be using an axios .put request to send an update to my backend/database which is a Django REST framework. I have been using .get, .post, and .delete successfully by following a guide. I've been getting conflicting messages from online resources about how to do a .put request successfully. Some resources say that the url in my path should be something like '/path/in/urls/:id' where id is the thing I want to update. Other resources have shown that my inputs to .put should have an identical format to my .post. For my .post I've been using the path '/path/in/urls/ and then the second argument is an object. For all of these requests the final argument is always a type of token. In the code I use it looks something like: tokenConfig(getState), but this value is equal to, for example: { headers: { Authorization: "Token 032b2f569037f0125753ef8f67e7774d34a756646ae28cefd54eb1c54bd0b149" Content-type: "application/json" } } I need some clarification on what is wrong with my .put request. Here is an example of how I do a .post request, where eventdefinition is what I'm posting: // ADD EVENT DEFINITION export const addEventDefinition = (eventdefinition) => (dispatch, getState) => { axios .post("/api/eventdefinitions/", eventdefinition, … -
DRF JSON API - Update M2M relationship not persisting
I'm trying to update a resource in a PATCH. The resource is updated fine, but the resources in the M2M table don't change. Models class StatementOfAdvice(Model): id = HashidUnsignedAutoField(primary_key=True, salt="StatementOfAdvice", min_length=15) loan_purposes = ManyToManyField( to=StaticLoanPurpose, through=StatementOfAdviceLoanPurpose, related_name="loan_purposes" ) class StaticLoanPurpose(Model): id = CharField(db_column="loan_purpose_id", primary_key=True, max_length=150) value = CharField(max_length=150, unique=True) class StatementOfAdviceLoanPurpose(Model): id = HashidUnsignedAutoField(primary_key=True, salt="StatementOfAdviceLoanPurpose", min_length=15) statement_of_advice = ForeignKey(to="StatementOfAdvice", on_delete=DO_NOTHING) loan_purpose = ForeignKey(to="StaticLoanPurpose", on_delete=DO_NOTHING) Serializers class StatementOfAdviceSerializer(Serializer): included_serializers = {"client_account": ClientAccountSerializer, "loan_purpose": StaticLoanPurposeSerializer} loan_purposes = ResourceRelatedField(many=True, read_only=False, queryset=StaticLoanPurpose) class Meta(BaseSerializer.Meta): model = StatementOfAdvice fields = "_all_" class StaticLoanPurposeSerializer(Serializer): class Meta(BaseSerializer.Meta): model = StaticLoanPurpose fields = "_all_" My PATCH request: http://localhost:8000/statements_of_advice/zELX1KdyZjgQGkp/ Payload: { "data": { "type": "StatementOfAdvice", "attributes": {}, "relationships": { "loan_purposes": { "data": [ { "type": "StaticLoanPurpose", "id": "construct_io" }, { "type": "StaticLoanPurpose", "id": "other_purpose" }, { "type": "StaticLoanPurpose", "id": "purchase_io" } ] } }, "id": "zELX1KdyZjgQGkp" } } The result I expect from this PATCH request is 3 records in the linking table StatementOfAdviceLoanPurpose. But I get none. If anyone could help me here I would greatly appreciate it. -
Django - Left joning two queryset from different database
I have two models from different database and server: # This is from server A, database A1 class employee_info(models.Model): emp_id = models.AutoField(db_column='id', primary_key=True) first_name = models.CharField(db_column='First_name', max_length=255) # This is from server B, database B1 class vehicles(models.Model): vehicle_id = models.AutoField(db_column='id', primary_key=True) vehicle_type = models.CharField(db_column='vehicle_type', max_length=255) emp_id= models.IntegerField(db_column='emp_id') # No Foreign Key Constaints This is my querying def getinfo(): vehicles = vehicles.objects.using('ServerA').all() emp_info = employee_info.objects.using('ServerB').all() # How do I do a left join on vehicles with emp_info base on 'emp_id' column of both queryset? vehicle_with_emp_info = ??? # vehicles LEFT JOIN emp_info ON vehicles.emp_id = emp_info.emp_id, but how? return vehicle_with_emp_info How should I go about joining the two query set? Is there a way to do this? If there is no solution, is there an alternative? Thanks -
Get input number from HTML and use it in Python external script (Django)
my HTML form code <form action="submit/" method="POST"> {% csrf_token %} <div class="tweets"> <input type="number" name="data_num" min="1" max="1000" placeholder="Jumlah Data" required> <input class="btn_unduh" type="submit" value="UNDUH"> <span style="position: absolute; left: 85%; top: 5%;">Total Tweets: {{count_tdata}}</span> </div> </form> i want to get the input from data_num and use it in my external Python script in .items(x) for tweet in tweepy.Cursor(api.search, q="kuliah online -filter:retweets", lang="id", tweet_mode='extended').items(x): my views.py code def submit(request): out = run( [sys.executable, 'C:\\Users\\alessandro\\Documents\\Django\\myweb\\tweets\\crawling.py'], shell=False) out2 = run( [sys.executable, 'C:\\Users\\alessandro\\Documents\\Django\\myweb\\tweets\\import.py'], shell=False) view_tweet = tdata.objects.all().order_by('-date') count_tweet = tdata.objects.count() context = { 'title': 'Tweets | PPL', 'heading': 'Halaman Tweets', 'subheading': 'Analisis Sentimen Twitter', 'db_tdata': view_tweet, 'count_tdata': count_tweet, } return render(request, 'tweets2.html', context) -
Use AJAX to update Django Model
I am trying to understand how to update a Django model using AJAX without loading a new page or explicitly having the user press a save button. I have found many tutorials that deal with getting results from Django models using AJAX but I haven't found any that deal with updating models using AJAX. Here is what I have so far I have the following Django model: #models.py class Upload(models.Model): email = models.EmailField() title = models.CharField(max_length=100) language = models.ForeignKey('about.channel', on_delete=models.CASCADE, default='Other') date = models.DateField(auto_now_add=True) file = models.FileField() completed = models.BooleanField(default=False) I am accepting those uploads through a form, all is well. I am then displaying those on a page through the following view: #views.py def submissions(request): context = { 'uploads': Upload.objects.all().order_by('-completed', '-date') } return render(request, 'content/submissions.html', context) The template for this page: #submissions.html <div class="row row-cols-1 row-cols-md-3"> {% for upload in uploads %} <div class="col mb-4"> <div class="card"> <div class="card-body"> <h5 class="card-title"> {{ upload.title }} </h5> <h6 class="card-subtitle"> {{upload.language}} </h6> <a href="{{ upload.file.url }}" class="channel-link card-link" download> Download </a> {% if upload.completed %} <div class="form-check"> <input class="form-check-input" type="checkbox" value="" data-id="{{ upload.id }}" checked> <label class="form-check-label" for="{{ upload.id }}"> Completed </label> </div> {% else %} <div class="form-check"> <input class="form-check-input" type="checkbox" value="" … -
ModuleNotFoundError: No module named 'secondpage.forms'
from django.shortcuts import render from secondpage.forms import NewUserForm def index(request): return render(request, 'secondpage/index.html') def users(request): form = NewUserForm() if request.method == "POST": form = NewUserForm(request.POST) if form.is_valid(): form.save(commit=True) return index(request) else: print("Error form invalid") return render(request,'secondpage/users.html',{'form':form}) I have init.py file in the apps directory and I am in the correct path. I also have the app in installed apps in settings.py but the terminal is throwing the same error. Any help is greatly appreciated since I've browsed SO for hours now. Thank you. -
When does Django's CSRF middleware set the csrftoken cookie?
I have a React application served using a Django class-based view: class FrontendView(TemplateView): template_name = 'index.html' def get(self, request): return render(request, self.template_name) I am using Django's CsrfViewMiddleware, and when I visit ANY other page in my app, a cookie is immediately created in the browser called csrftoken. However, when I visit the page output by the view above, the csrftoken cookie is not added. At what point does the middleware set the cookie? Is there a way to spy on when/where it is set? NOTE: I am not referring to forms, or POST'ing - if I visit ANY page on the site the cookie is set, and on this one page it is not. I would like to understand why. -
Data processing before save in django model
I want to make an automated site in Django model, As an automated if user input unit and quantity it is not good to input also total, I think you understand what I mean it would be. my models looks like this model.py: unit_price = models.FloatField(max_length=24) quantity = models.FloatField(max_length=24) total_price = models.FloatField(max_length=24) view.py: posted = dataForm(request.POST) if posted.is_valid(): posted.save() what I want is that user input Quantity and unit price only and total_price = quantity * unit_price So how can I do it -
JQuery, how to pass the slug variable
I'd like to know how I can pass the slug variable into JQuery/javascript. I have a data-table with items, on each row there are two buttons, one (1) is using Django to create a product, the other (2) is supposed to use JQuery / JS to create a product. To create a product with button 1 I find being straight forward and well explained. I'd like to perform the same action on button 2, using JQeury/JS. button 1 <a href="{% url 'products-create' object.products_uid %}"><button type="button" class="btn btn-secondary"><i class="fa fa-pencil"></i></button></a> with urls path: path("products/<uuid:slug>/create/", ProductsCreateView.as_view(), name="products-create"), views.py class ProductsCreateView(CreateView): model = Products template_name = "products_create.html" slug_field = "products_uid" button 2 <button class="btn btn-secondary js-create-button" data-url="{% url 'api-products-create' object.products_uid %}" type="button"><span class="fa fa-pencil"></span></button> with urls path: path('api/products/<uuid:slug>/create/', ProductsCreateView.as_view(), name="api-products-create"), with js (truncated function) $(function () { var createProduct = function() { var slug = '{{ $slug }}'; /* some code/function that gets hold of the slug */ const url = `/api/v1/products/${slug}/create/`; $.get(url) .done(function pollAsyncResults(data) { // bind pollAsyncResults to itself to avoid clashing with // the prior get request context: this // see the URL setup for where this url came from const pollAsyncUrl = `/api/products/poll_async_results/${data.task_id}`; }) }; $(".js-create-button").click(createProduct); }); -
IP camera webstream with openCV django hosted by Raspberry
I'm wokring on streaming IP cams using django. Backend is hosted on Raspberry Pi 4. Code is running perfectly fine on Windows, or Ubuntu but it seems to be too hard for raspberry hardware. My question, is there any way to optimize this camera streams? It's working fine for like few minutes, after that it get's laggy and finally dead. I've added threading and gzip, but it's not helping much. Here is my VideoCamera class: class VideoCamera(object): """ Class to handle IP cameras with opencv """ def __init__(self, ip): """ Init the camera with provided IP address, /mjpeg stands for url address, which is hosted by ESP camera :param ip: """ self.cam = 'rtsp://' + str(ip) + ':8554/mjpeg/1' self.video = cv2.VideoCapture(self.cam) (self.grabbed, self.frame) = self.video.read() self.started = False self.read_lock = Lock() def start(self): if self.started: return None self.started = True self.thread = Thread(target=self.update, args=()) self.thread.start() return self def update(self): while self.started: (grabbed, frame) = self.video.read() self.read_lock.acquire() self.grabbed, self.frame = grabbed, frame self.read_lock.release() def read(self): self.read_lock.acquire() frame = self.frame.copy() self.read_lock.release() return frame def stop(self): self.started = False self.thread.join() def __exit__(self, exc_type, exc_value, traceback): self.video.release() and here is my views: def index(request): return render(request, 'cameras/home.html') def gen_frame(cap): """ Function for rendering camera … -
Making a survey that tells the user their college major match. Using django and python
First, the project I am doing is supposed to give the user a multiple choice quiz/survey to give them what college major best suits them, and based off the answers he/she chooses. My problem is mainly how would I go about making the answers and majors connected so when the user finishes the major is chosen. If there is any problem understanding what I trying to explain just let me know. All advice and critiques are welcome I really wanna get better with my programming. I am basically trying to make my program do this in the link. https://www.luc.edu/undergrad/academiclife/whatsmymajorquiz/ class User(models.Model): first_name = models.CharField(max_length=25) last_name = models.CharField(max_length=25) #password = models.CharField(max_length=25) email = models.EmailField(max_length=10) class Quiz(models.Model): name = models.CharField(max_length=200) NOQ = models.IntegerField(default=1) class Meta: verbose_name = "Quiz" verbose_name_plural = "Quizzes" def __str__(self): return self.name #number Of Questions class Major(models.Model): major = models.CharField(max_length=200) majorData = models.IntegerField(default=0) def __str__(self): return self.major class Question(models.Model): question_text = models.CharField(max_length=400) quiz = models.ForeignKey("Quiz", on_delete=models.CASCADE, null=True) def __str__(self): return self.question_text class Answer(models.Model): question = models.ForeignKey('Question', on_delete=models.CASCADE, null=True) answer_text = models.CharField(max_length=200) def __str__(self): return self.answer_text class QuizTaker(models.Model): user = models.ForeignKey("User", on_delete=models.CASCADE) quiz = models.ForeignKey("Quiz", on_delete=models.CASCADE) completed = models.BooleanField(default=False) def __str__(self): return self.user views.py def index(request): return render(request,"JSUMA/JSUMA.html",) def register(response): … -
How to export the DB from Django Heroku and restore(push) that to Heroku again?
I want to update the DB from online admin page of my Django app and export that DB into local environment. And I want to update that data in local environmental as well and update(push) to Heroku again. -
I deployed my django app successfully without any error but when I went to the website, I saw application error, I don't understand
I deployed my django app successfully without any error but when I went to the website, I saw application error, I don't understand. There's no error message on my console, I don't even know what to do or how to debug the problem. I used this heroku logs --tail --app -code to find the code below but i can't make any sense from it. Please I need your to help solve this problem. 2020-11-19T21:35:35.731246+00:00 heroku[web.1]: State changed from crashed to starting 2020-11-19T21:35:46.000000+00:00 app[api]: Build succeeded 2020-11-19T21:35:52.203195+00:00 heroku[web.1]: Starting process with command `gunicorn startingOver.wsgi --log-file` 2020-11-19T21:35:55.795727+00:00 app[web.1]: usage: gunicorn [OPTIONS] [APP_MODULE] 2020-11-19T21:35:55.795976+00:00 app[web.1]: gunicorn: error: argument --error-logfile/--log-file: expected one argument 2020-11-19T21:35:55.876242+00:00 heroku[web.1]: Process exited with status 2 2020-11-19T21:35:55.926887+00:00 heroku[web.1]: State changed from starting to crashed 2020-11-19T21:36:26.125774+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=sover.herokuapp.com request_id=7afeb4a7-f1a4-4579-a2a2-84856e17aa89 fwd="129.205.124.165" dyno= connect= service= status=503 bytes= protocol=https 2020-11-19T21:36:27.625586+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=sover.herokuapp.com request_id=a0a558ad-fba2-40b6-8cc7-8a6fd2f25eb1 fwd="129.205.124.165" dyno= connect= service= status=503 bytes= protocol=https 2020-11-19T21:37:39.186291+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=sover.herokuapp.com request_id=afd20739-1ee9-4593-9a58-260e1bf653d7 fwd="129.205.124.165" dyno= connect= service= status=503 bytes= protocol=https 2020-11-19T21:37:39.848587+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=sover.herokuapp.com request_id=eeeaa0d2-49ef-4dbe-9062-81203f672fe5 fwd="129.205.124.165" dyno= connect= service= status=503 bytes= protocol=https 2020-11-19T21:37:46.266626+00:00 heroku[web.1]: State changed from crashed to starting … -
django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty :import model
CODE: https://github.com/Strzelba2/STOCK/blob/main/STOCK/WIG/WIG_scrap.py When i try import my model to WIG_scrap.py from .models import CompanyData , Quotes I get the error : django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty but without importing the model, everything works fine. Can someone please explain to me why this is happening -
'tuple' object has no attribute 'ordered' on UpdateView
It gives me this error and for the life of me i cannot understand why: I have a form extended from django-allauth SignupForm... class LearnerSignupForm(SignupForm): first_name = forms.CharField(max_length=40, required=True) last_name = forms.CharField(max_length=40, required=True) The form is called in the allauth signup view... class LearnerSignupView(SignupView): form_class = LearnerSignupForm success_url = reverse_lazy('users:redirect_profile_mixin') The view redirects to a mixin(that extends RedirectView that gets the autheticated user from the request and redirects the connection to an UpdateView passing the parameter user.id.. class LearnerUpdateView(UpdateView): model = User form_class = UserForm formset_Class = LearnerFormSet template_name = "formset_edit_learner.html" success_url = "home" def get_context_data(self, **kwargs): context = super(LearnerUpdateView, self).get_context_data(**kwargs) qs = Learner.objects.get_or_create(user=self.request.user) formset = LearnerFormSet(queryset=qs) context["learner_formset"] = formset return context And then finally to the UpdateView. And it's at this point that i get the error 'tuple' object has no attribute 'ordered' and Exception Location: C:\Users\aless.virtualenvs\hs_03-LQeWV4ia\lib\site-packages\django\forms\models.py, line 639, in get_queryset I know that i'm probably doing something really stupid but i just can't see it. I thank in advance whoever can offer some advice! -
Django Postgresql reset pk/id field
I am using Django with Postgresql. With sqlite, when I delete all the objects, and insert new ones, pk is reset to 1. However, with Postgresql, pk keeps adding up. I came across to this post (1). The accepted answer calls for: python manage.py sqlsequencereset myapp1 myapp2 myapp3| psql My app is products. But I don't know what to write on the right side of the pipe. Here is what I tried: # products is my app name python manage.py sqlsequencereset products The following message appeared: BEGIN; SELECT setval(pg_get_serial_sequence('"products_category"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "products_category"; SELECT setval(pg_get_serial_sequence('"products_product_categories"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "products_product_categories"; SELECT setval(pg_get_serial_sequence('"products_product"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "products_product"; COMMIT; I then tried: python manage.py sqlsequencereset products | psql Here is the error message: -bash: psql: command not found Exception ignored in: <_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'> BrokenPipeError: [Errno 32] Broken pipe What should I put after the | ? -
Add rows in many-to-many injected table
Is it possible to insert some data in a injected table (auto created by Django to handle many to many relationship)? I've searched to this question for about 5 hours, and i've found no answer. -
Using historical exchange rates in django money to convert money based on a user inputted date
I am building a personal finance Django app and have been using django-money to automatically convert values based on the current exchange rate using convert_money(). I would like to add a feature where the values are converted based on the exchange rate of a user-specified date, instead of always using the current rate. Is there a way to customize convert_money() to convert based off of an inputted date instead of just the current rate of your last update_rates()? -
How to make Django tries multiple realms in Keycloak using openid connect?
Synopsis We have a web app that allows internal users and external users to login, we would like to split the 2 groups of users in Keycloak with different realms, for instance, internal realm and external realm. Our ideal authentication method is OpenID Connect. Problem Most Django OIDC libraries allows to specify one OIDC client configuration in Django settings. However given how OIDC works one client configuration only works with one realm, because a client is configured inside a realm. I have come across this library django-keycloak which seems to be able to configure client configurations in a database and I need to implement my own middleware to dynamically route the request to a corresponding realm, see this pdf on page 12. Unfortunately this library has not been updated for 2 years and seems not maintained anymore. Question Is there an up-to-date library that has similar functionality in django-keycloak? (I will raise an issue in the repo to enquire the project status) Apart from the multi-client configuration approach, is there a better alternative? -
How do I set the width of a HTML element with a Django variable?
Right now, I have a dictionary, where I have each element and the width of it stored. I'm passing that with Django to an HTML template, where I'm rendering each of the dict objects with a for loop. However, I need to be able to set the width of a 'div' using what is in the Django template. So basically, if I have "100%" in the dict, then I want the corresponding div to also have a width of 100%. The code I tried is below, but it isn't working, and in the console, it says "invalid property value". Python code: dict={"key": "100%", "key2": "90%"} return render(request, "website/updates.html", { "dict": dict }) website/updates.html {% for item, width in dict.items %} <div style="width: {{width}}"> Other irrelevant code here </div> {% endfor %} -
Django authenticate keeps returning None
I'm using Django 3.1.8 with the django debug toolbar on. The "authenticate()" function from django.contrib.auth keeps returning "None" for an unknown reason. I have created a superuser and the login was perfectly working before I installed the debug toolbar. Any advice ? My views.py : def login(request): if request.method == 'GET': return render(request, 'website/login.html') elif request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None : django_login(request, user) return HttpResponseRedirect(reverse("website-home")) else: return HttpResponseRedirect(reverse("website-about")) ` -
Is it possibl to use one broker for two django project?
I have two project with two celery ,but i used one Redis broker ,does it have problem?i think it has problem,because i have problem in run task,and sometimes tasks do not run. -
django text area tag: input cursor does not begin at the start
I created a text area tag , and for some reason the cursor starts at the top middle instead of the top left(which is the standard). I want the input cursor to start at the very beginning of the box. Any help would be helpful :)