Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 :) -
assertRedirect not working. Getting 302 != 201 error
I have two tests: def test_view_exists_at_desired_location(self): note_id = 1 login = self.client.login(username='Name', password='password') response = self.client.get(f'/{ note_id }/edit/') self.assertEqual(response.status_code, 200) def test_view_redirects_if_not_logged_in(self): note_id = 1 response = self.client.get(f'/{ note_id }/edit/') self.assertRedirects(response, f'/accounts/login/?next=/{ note_id }/edit/') in my urls.py I have: urlpatterns = [ ... path('<int:note_id>/edit/', login_required(views.edit), name='edit'), ] The first test, test_view_exists_at_desired_location runs fine, ensuring that a Note with note_id=1 exists. However, the other test fails and tells me: Traceback (most recent call last): File "/home/MyName/Documents/Projects/ProjectName/notes/tests/test_views.py", line 119, in test_view_redirects_if_not_logged_in self.assertEqual(response.status_code, 201) AssertionError: 302 != 201 When I visit /1/edit/ while not logged in on my browser I am redirected to /accounts/login/?next=/1/edit/. I don't think it matters, but here is view.edit: def edit(request, note_id): note = get_object_or_404(Note, pk=note_id) if request.POST: form = NoteForm(request.POST) if form.is_valid(): date = datetime.date.today() title = form.cleaned_data['title'] body = form.cleaned_data['body'] is_private = form.cleaned_data['is_private'] note.title = title note.body = body note.is_private = is_private note.edit_date = date note.save() return HttpResponseRedirect(reverse('notes:mynotes')) # get or any other method. Return create page else: form = NoteForm(instance=note) return render(request, "notes/editor.html", {'form': form, 'note_id': note_id}) -
Django sessions - reliability issues - must keep logging in
I have 2 reliability issue with Django sessions. The goal I am trying to achieve is if I use the account at least once a month, I don't even have to log in. 1. The quantity of sessions I am working on the website, I am the only one using it, and Django keeps creating sessions. I have 30 sessions for just myself today (I cleaned out all the sessions at the start of the day). 2. I have to keep logging in I find every now and then I have to log in again (e.g. come back the next day), or after a reboot. My Current Setup: # Set to 1 months of inactivity SESSION_COOKIE_AGE = 31 * 24 * 3600 # After every request store SESSION_SAVE_EVERY_REQUEST = True SESSION_ENGINE = 'django.contrib.sessions.backends.db' # This is the default I used to use cached DB session engine, but with SESSION_SAVE_EVERY_REQUEST i figure its pointless, as it will be a miss every time. I also thought the default DB session engine maybe more reliable (maybe be more reliable or might just be grasping at straws). For the messages storage I use Session storage. I used to use the default FallbackStorage but figure … -
Consuming JSON API data with Django
From a Django app, I am able to consume data from a separate Restful API, but what about filtering? Below returns all books and its data. But what if I want to grab only books by an author, date, etc.? I want to pass an author's name parameter, e.g. .../authors-name or /?author=name and return only those in the json response. Is this possible? views.py def get_books(request): response = requests.get('http://localhost:8090/book/list/').json() return render(request, 'books.html', {'response':response}) So is there a way to filter like a model object? -
How to POST nested Data that contains a File with Django Rest Framework?
I've been trying to post a nested object with one file and some data via django drf for a few days now. The goal is to create a story together with some images, one of these images being the title image of the story. Basically, I am able to post the story successfully with postman (see picture below). However, when I use my react js frontend for sending, I am not able to create the form data in a way that Django understands it. Django always returns the error story_media field is required. I suppose this is because Django does not understand the incoming data correctly. class Story (models.Model): title = models.CharField(max_length=100,blank=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) class Story_Media (models.Model): story = models.ForeignKey(Story,on_delete=models.CASCADE, null=True, related_name = 'story_media', related_query_name = 'story_media') file = models.FileField(upload_to='story_media/', null=True) isTitlePicture = models.BooleanField(blank=False, null=True) # Story Story Media Serializer class Story_Media_Serializer (serializers.ModelSerializer): class Meta: model = Story_Media fields = ('id','file','isTitlePicture',) # Story Serializer class StoryCreateUpdateSerializer (serializers.ModelSerializer): story_media = Story_Media_Serializer(many=True) class Meta: model = Story fields = ('title','story_media',) def create(self, validated_data): current_user = self.context["request"].user story_media = validated_data.pop('story_media') story_instance = Story.objects.create(author=current_user, **validated_data) for story_media_data in story_media: Story_Media.objects.create(**story_media_data, story=story_instance) # Story Create View Set class StoryCreateUpdateViewSet(viewsets.ModelViewSet): serializer_class = StoryCreateUpdateSerializer … -
Django elasticsearch dsl completion field issue
I am trying to implement search suggestions using django-elasticsearch-dsl-drf for streets. This is documents.py: class StreetDocument(Document): id = fields.IntegerField() name_ru = StringField( fields={ 'raw': KeywordField(), 'suggest': fields.CompletionField(), } ) ... # same for name_uz and name_oz tags_ru = fields.CompletionField() ... # same for tags_uz and tags_oz class Django: model = Street fields = ( 'code', 'street_type' ) in views.py I have this: from django_elasticsearch_dsl_drf.constants import SUGGESTER_COMPLETION from django_elasticsearch_dsl_drf.filter_backends import SuggesterFilterBackend from django_elasticsearch_dsl_drf.viewsets import DocumentViewSet class SuggestionListAPI(DocumentViewSet): document = StreetDocument serializer_class = StreetDocumentSerializer filter_backends = [ CompoundSearchFilterBackend, SuggesterFilterBackend, ] search_fields = ( 'code', 'name_ru', 'name_uz', 'name_oz', 'tags_ru', 'tags_uz', 'tags_oz' ) suggester_fields = { 'name_ru_suggest': { 'field': 'name_ru.suggest', 'suggesters': [ SUGGESTER_COMPLETION, ], }, ... # same for name_uz and name_oz 'tags_ru': { 'field': 'tags_ru', 'suggesters': [ SUGGESTER_COMPLETION, ], }, ... # same for tags_uz and tags_oz } Request to /suggestions?name_ru_suggest__completion=tolstoy does nothing, just receiving all streets unfiltered. Request to /suggestions?search=tolstoy works great, but I need autocompletion. Where did I go wrong? And that will be great if it's possible to use two fields for suggestion at once. Thanks for your time and help.