Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pop up warning message of inactivity in django
I have managed to log a user (who is defined under the admin group 'customer') out of their session and managed to return them to the login page using the SESSION_COOKIE_AGE functionality in my settings.py. But i want to create a pop up warning message to the user after a X amount of time of inactivity. I did some research and i found SESSION_SECURITY_WARN_AFTER option but i think this requires javascript which i am unfamiliar with. Is there another way? Below is my code: views.py: @allowed_users(allowed_roles=['customer']) def home_view(request): # forms context = {#keys} return render(request,"home.html",context) decorator.py: def allowed_users(allowed_roles=[]): def decorator(view_func): def wrapper_func(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group in allowed_roles: return view_func(request, *args, **kwargs) else: messages.info(request, 'Your session has expired!') return redirect('login')` return wrapper_func return decorator settings.py: #SESSION SECURITY SETTINGS SESSION_EXPIRE_AT_BROWSER_CLOSE = True SESSION_COOKIE_AGE = 10 # Low time for testing SESSION_SAVE_EVERY_REQUEST = True -
Try to test views that use request.session[key] in dajngo
I made an attempt to test on a views.py in which the file has one line using request.session['key'] values. def updateaccout(request): username = request.session['username'] profile = Account.objects.get(username=username) return render(request, "user/profile .html",profile ) At the test.py file I have tried sets. def test_updateaccout(self): self.client.login(username='john', password='johnpassword') session = self.client.session session['username'] = 'john' session.save() c = Client() data = {'username' : 'john'} response = c.post('/account', data,follow=True) self.assertEqual(response.status_code,200) ERROR: test_updateaccout (user.tests.UsersTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/ubuntu/cn331project/user/tests.py", line 57, in test_updateaccout response = c.post('/login/account', data,follow=True) File "/home/ubuntu/.venv/lib/python3.7/site-packages/django/test/client.py", line 741, in post response = super().post(path, data=data, content_type=content_type, secure=secure, **extra) File "/home/ubuntu/.venv/lib/python3.7/site-packages/django/test/client.py", line 405, in post secure=secure, **extra) File "/home/ubuntu/.venv/lib/python3.7/site-packages/django/test/client.py", line 470, in generic return self.request(**r) File "/home/ubuntu/.venv/lib/python3.7/site-packages/django/test/client.py", line 709, in request self.check_exception(response) File "/home/ubuntu/.venv/lib/python3.7/site-packages/django/test/client.py", line 571, in check_exception raise exc_value File "/home/ubuntu/.venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/ubuntu/.venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ubuntu/cn331project/user/views.py", line 50, in updateaccout username = request.session['username'] File "/home/ubuntu/.venv/lib/python3.7/site-packages/django/contrib/sessions/backends/base.py", line 65, in __getitem__ return self._session[key] KeyError: 'username' Another one that I tried to set is to add self._session ['username'] = 'john' but it says AttributeError: 'UsersTestCase' object has no attribute '_session' how can I do to solve it? thank you -
django channels works locally but fails on server
Django channels fails to connect in production i'm working on a chat application using django Channels and reconnecting-web-socket the app works fine locally but when deployed to heroku the site works fine but the web socket closes before connection is established and sometimes it works fine. it tries to connect and says websocket open and established 2020-11-21T11:45:14.483101+00:00 app[web.1]: 10.38.231.42:12792 - - [21/Nov/2020:11:45:14] "WSCONNECTING /ws/chat/" - - 2020-11-21T11:45:14.483267+00:00 app[web.1]: 2020-11-21 11:45:14,483 DEBUG Upgraded connection ['10.38.231.42', 12792] to WebSocket 2020-11-21T11:45:14.486434+00:00 app[web.1]: 2020-11-21 11:45:14.486 UTC [24] LOG C-0x5564d6f000a0: db1/kutxkggzwbkjsp@127.0.0.1:35034 login attempt: db=db1 user=kutxkggzwbkjsp tls=no 2020-11-21T11:45:14.493134+00:00 app[web.1]: 2020-11-21 11:45:14,492 DEBUG WebSocket ['10.38.231.42', 12792] open and established 2020-11-21T11:45:14.493228+00:00 app[web.1]: 10.38.231.42:12792 - - [21/Nov/2020:11:45:14] "WSCONNECT /ws/chat/" - - 2020-11-21T11:45:14.493405+00:00 app[web.1]: 2020-11-21 11:45:14,493 DEBUG WebSocket ['10.38.231.42', 12792] accepted by application then it tries to connect to the redis db 2020-11-21T11:45:14.494880+00:00 app[web.1]: 2020-11-21 11:45:14,494 DEBUG Parsed Redis URI ('redis-10596.c8.us-east-1-2.ec2.cloud.redislabs.com', 10596) 2020-11-21T11:45:14.495020+00:00 app[web.1]: 2020-11-21 11:45:14,494 DEBUG Creating tcp connection to ('redis-10596.c8.us-east-1-2.ec2.cloud.redislabs.com', 10596) but right after that the socket closes 2020-11-21T11:45:17.133433+00:00 heroku[router]: at=info method=GET path="/ws/chat/" host=tolk-project.herokuapp.com request_id=41ed7690-5f91-4238-9792-01f52c5f65a1 fwd="102.143.218.204" dyno=web.1 connect=0ms service=2654ms status=101 bytes=145 protocol=http 2020-11-21T11:45:17.134597+00:00 app[web.1]: 2020-11-21 11:45:17,134 DEBUG WebSocket closed for ['10.38.231.42', 12792] 2020-11-21T11:45:17.135119+00:00 app[web.1]: 10.38.231.42:12792 - - [21/Nov/2020:11:45:17] "WSDISCONNECT /ws/chat/" - - 2020-11-21T11:45:17.419219+00:00 app[web.1]: 2020-11-21 11:45:17,419 DEBUG Cancelling … -
realtime video feed processing using server client architecture for multi-user setup
I created a flutter app that sends frames to Django server where it gets processed and sent back. How do i make this work for multiple users? The computation is done on GPU so it's heavy image processing on server but its real time. what do i need to do in order to achieve a. multiple users use the app and send realtime video to server b. make sure processed video feed isn't sent to wrong user c. balance the load when multiple people stream at once, i only have 16 gigs of VRAM on server. what technology should i use? i came across kafka. would that solve the problem? Please help! i have a critical deadline :'( -
TypeError: update() takes 2 positional arguments but 3 were given : Python
I'm getting TypeError: update() takes 2 positional arguments but 3 were given. I have no idea about why this error occurs. if anybody could figure out where i'm doing thing wrong then would be much appreciated. thank you so much in advance. serializers.py : class ShopOwnerOrderManageSerializer(Serializer): invoice_no = CharField(read_only=True) shopowner_expected_date = CharField(allow_blank=True) shopowner_estimated_time = CharField(allow_blank=True) status = CharField(allow_blank=True) class Meta: model = CarOwnerShopConfirm fields= ['shopowner_expected_date','shopowner_estimated_time','status'] def update(self,validated_data): shopowner_expected_date = validated_data['shopowner_expected_date'] shopowner_estimated_time = validated_data['shopowner_estimated_time'] status = validated_data['status'] shopconfirm_obj = CarOwnerShopConfirm.objects.update( shopowner_expected_date = shopowner_expected_date, shopowner_estimated_time = shopowner_estimated_time, status = status ) shopconfirm_obj.save() return validated_data -
Securely post data with Python Requests to a Django Website
I am wanting to post data from another computer (a Raspberry Pi) to my Django website so that I can use that data to create an entry in the website's database. The following code signs me in to the website and sends the POST data successfully, so that I am able to create a database entry with the POST data, although I am concerned about security. # Imports import requests # Constants LOGIN_URL = "http://127.0.0.1:8000/login/" SAVE_DATA_URL = "http://127.0.0.1:8000/save_data/" login_data = { "username": "Test", "password": "test_password123", "next": "/" } data_package = { "title": "Testing POST", "contents": "Lorem ipsum dolor sit." } with requests.Session() as s: # --- Start Login --- # # Get login page CSRF Token and add it to the login data r = s.get(LOGIN_URL) csrf_token = r.cookies["csrftoken"] login_data["csrfmiddlewaretoken"] = csrf_token # Post login data to login to the website r = s.post(LOGIN_URL, data=login_data, headers=dict(Referer=LOGIN_URL)) # --- End Login --- # # --- Start POST Data --- # # Get save data page CSRF Token and add it to the data package r = s.get(SAVE_DATA_URL) csrf_token = r.cookies["csrftoken"] data_package["csrfmiddlewaretoken"] = csrf_token # Post error data to the website r = s.post(SAVE_DATA_URL, data=data_package) # --- End POST Data --- # … -
I want to generate bill of restaurant by multiplying quantity and price how to do this
In my code of invoice food name and food price both are showing food name on localhost portal so look into my foreign keys And also guide how to multiply product price and quantity. I am showing you both add product table and invoice table and their forms also look out and guide me for this models.py class AddFood(models.Model): food_name = models.CharField(max_length=20) food_price = models.PositiveIntegerField() company = models.ForeignKey(CompRegister, on_delete=models.CASCADE) res = models.ForeignKey(ResRegister, on_delete=models.CASCADE) def __str__(self): return self.food_name class GenerateInvoice(models.Model): foods_name = models.ForeignKey(AddFood, null=True, on_delete=models.CASCADE, related_name='food_n') foods_price = models.ForeignKey(AddFood, null=True, on_delete=models.CASCADE, related_name='food_p') quantity = models.PositiveIntegerField() company = models.ForeignKey(CompRegister, on_delete=models.CASCADE) res = models.ForeignKey(ResRegister, null=True, on_delete=models.CASCADE) start_date = models.DateTimeField(auto_now_add=True) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def __str__(self): return self.res, self.foods_name def total_price(self): return AddFood.food_price * self.quantity forms.py class FoodForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super(FoodForm, self).__init__(*args, **kwargs) self.fields['res'].queryset = ResRegister.objects.filter(res=True, company__user_id=user) class Meta: model = AddFood exclude = ['company','price','food'] fields = '__all__' class InvoiceForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super(InvoiceForm, self).__init__(*args, **kwargs) self.fields['foods_name'].queryset = AddFood.objects.filter(company__user_id=user) self.fields['foods_price'].queryset = AddFood.objects.filter(company__user_id=user) class Meta: model = GenerateInvoice exclude = ['company','res','start_date',] fields = '__all__' views.py def generate_invoice(request): u = CompRegister.objects.get(user_id=request.user) if request.method == 'POST': form = InvoiceForm(request.user, request.POST) if form.is_valid(): form_r = form.save(commit=False) form_r.company = u form_r.save() return … -
Error "write EPIPE" while pushing Heroku PostgreSQL database
An error "write EPIPE" occurred while loading Heroku PostgreSQL database from the local database. heroku addons:create heroku-postgresql:hobby-dev heroku pg:push postgres://localhost:5432/design-sa-1 DATABASE_URL --app design-sa screenshot Appeared only recently, before this was not. My system Windows 10, local databases v.11 or v.12 - the result is one - this error. I have already tried it on two old applications - the result is one – this error. The applications themselves (Django 3.0/ Python 3.7) are deployed on Heroku without errors. Local python manage.py dumpdata > db.json works perfect. -
Store a tree with labelled edges and labelled nodes in Django
So I need to store a questionnaire, which has a lot of branches based on the options. This diagram will give you an idea: I have already gone through these: Making a tree structure in django models? https://github.com/django-mptt/django-mptt/ These do not fit my use case, because my structure somewhere violates the idea of a tree (single parent property). Also, djang-mptt doesn't support labelled edges. I will have to create a Node class, and tell it if it is going to act like a Question or an Option. I tried to create the structure myself using Question and Option model class, having Foreign key in appropriate places (so that the structure below an option or question is deleted (models.CASCADE). But the problem there was to present it in such a way in the admin site, so that modification of the tree was a bit easier than treating the Questions and Options as yet another ordinary classes with foreign key references in them. Finally, I had the idea of moving to PostgreSQL as it supports storage of JSON data, hence representing everything in a single Python dictionary. I want some suggestions on how to go around modelling this. -
Add multisple select dropdown in django using javascript / bootstrap
Can anyone please tell me how to make a multiple select dropdown using javascript or bootstrap in django ? I've seen many posts for adding this feature on here as well as many other site but none worked... can you please send me a full working code ? This is the link I used -
How to add a value to the serializer that is not in the Model?
t when requesting films, it would return in the form movie id and number of comments, my model: class Movie(models.Model): Title = models.CharField(max_length=200) Year = models.CharField(max_length=25, blank=True) Rated = models.CharField(max_length=10, blank=True) class Comment(models.Model): comment_text = models.CharField(max_length=200) movie_id = models.ForeignKey( Movie, on_delete=models.CASCADE, related_name='Comments') how to add number of comments to output like { "movie_id": 2 "comment_count":3 }, { "movie_id": 1 "comment_count":2 } ] my View: class MoviesTop(APIView): def get(self, request): topMovie = Movie.objects.annotate( num_comments=Count('Comments')).order_by('-num_comments') serializer = MoviesTopSerializator(topMovie,many=True) return Response(serializer.data) -
How to send data to perticular user using server sent events on django?
I am new to server sent event please guide me. How can i send data from server to perticular client/user when change happen in database without reloading page. Also guid me if it is good to use server sent event or i should use websocket for this. -
django-modeltranslation: Why to I have 3 columns for two translations in database
Here is the relevant section of my settings.py LANGUAGE_CODE = "de" gettext = lambda s: s LANGUAGES = [ ("de", gettext("German")), ("en", gettext("English")), ] TIME_ZONE = "UTC" USE_I18N = True USE_L10N = True USE_TZ = True And I have this translation.py file in my awards app: from modeltranslation.translator import TranslationOptions, translator from .models import Award class AwardTranslationOptions(TranslationOptions): fields = ("title", "text") But in the database I get 3 columns for title: title title_en title_de And when I assign 1,2,3 to these three fields in the same order and save in admin I get the values: title: 2 title_en: 2 title_de: 3 It seems like title is always equal to title_en. Also, in the admin, the title field is required and the title_en and title_de are not required. What I had expected was to get only two fields, title_en and title_de of which title_de should be required since it is the default language. Can someone explain to me what is going on here? -
How to store selected values of the template in Django
I have searched a lot about how to store choices and dropdown list, but I could not find a solution for my situation. Here I have three classes with rating choices. models.py RATING_CHOICES = ((1, "Weak"), (2, "Average"), (3, "Good"), (4, "Excellent")) class Question(models.Model): text = models.CharField(max_length=100) def __str__(self): return self.text class Teacher(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Answer(models.Model): teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) answer = models.IntegerField(choices=RATING_CHOICES, default=1) views.py Here I want to know how to write my function to store data. from django.shortcuts import render from .models import Question, RATING_CHOICES, Teacher def index(request): context = {'questions': Question.objects.all(), 'rating_choices': RATING_CHOICES, 'teacher': Teacher.objects.all()} return render(request, 'index.html', context) index.html <form action=""> <select name="teacher" id=""> {% for teacher in teacher %} <option value="{{teacher}}">{{teacher}}</option> {% endfor %} </select> {% for question in questions %} <ol>{{ question.text }}</ol> {% for choice in rating_choices %} <input type="radio" name="question_{{question.id}}" value="{{choice.0}}">{{choice.1}} {% endfor %} {% endfor %} <br> <input type="submit" value="Vote"> </form> I want to store selected values similar to the admin when you simply select your options and save the results. -
Updating a Boolean field with detail View
I want to believe you all are doing fine. i've a little issue I've been thinking my head out about. I've a class detail view that displays my model class object, which works perfectly fine. i want to create a functionality for one of the objects in my models paper = models.BooleanField(default=True, blank=True). in my template, i created a link so were a user clicks on the link, the link will update the Boolean field to be true. now my question is, in my def paper_frame(request,pk) (the code is below) how can i add it to the class BusinessDetailView(DetailView), so it stands as just one functionality. class BusinessDetailView(DetailView): model = Item template_name = 'business/detail_view.html' context_object_name='items' def paper_frame(request,pk): paper = Item.objects.get(pk=pk) paper.paper = True paper.save() return redirect("???")``` -
I cannot have “skip to” functionality inspite of adding controls to my django .html file video tag. How do I resolve that?
<video class="video" controls src="{{post.clip.url}}" type="video/mp4"></video> To get "skip to particular time", what do I need to do? -
i want to edit my restaurant data but i got this"The view company.views.edit_res didn't return an HttpResponse object. It returned None instead."
ValueError at /company/edit_res/1/ i got this error on " F:\restaurant\venv\lib\site-packages\django\core\handlers\base.py, line 307, in check_response" this location please guide me for successful edit this is my first learig project views.py def edit_res(request, id): if request.method == 'POST': pi = ResRegister.objects.get(pk=id) fm = CompRegisterForm(request.POST, instance=pi) if fm.is_valid(): fm.save() else: pi = User.objects.get(pk=id) fm = CompRegisterForm(instance=pi) return render(request, 'comp/edit.html', {'form': fm}) urls.py from django.urls import path from . import views from django.conf.urls.static import static from django.conf import settings app_name = 'company' urlpatterns = [ path('res_list/', views.res_list, name='res_list'), path('food_list/', views.food_list, name='food_list'), path('remove_res/<int:id>/', views.remove_res, name='remove_res'), path('remove_food/<int:id>/', views.remove_food, name='remove_food'), path('edit_res/<int:id>/', views.edit_res, name='edit_res'), path('edit_food/<int:pd>/', views.edit_food, name='edit_food'), path('add_food/', views.add_food, name='add_food'), path('cart_page/', views.cart_page, name='cart_page'), path('generate_invoice/', views.generate_invoice, name='generate_invoice'), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) edit.html <!doctype html> {% extends 'Comp_base.html' %} {% block body %} {% load static %} <br><br> <div class="container"> <h1>Update Information</h1><br> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit" name="register" class="btn btn-primary btn-lg btn-block">Update</button><br> </form> </div> {% endblock %} -
Creating Text Editior in Django
I want to create a notes app in django and want a text editor which helps user to add bullets and bold text and more functionalities. How can i do this in the template in django? I am a newbie in django so please suggest me some ways to do that. -
python convert string to content of the string
What I get: names = """[{"lname": "HORJLAND", "fname": "Birger"}, {"lname": "LAMERS", "fname": "Edmund"}]""" What I want: names_list = [{"lname": "HORJLAND", "fname": "Birger"}, {"lname": "LAMERS", "fname": "Edmund"} How can I get names_list from names? I get the names variable from a django template and I want to parse it in a template tags by looping over it and get name['fname'] and name['lname'] like: for name in names: print(name['fname']) TypeError: string indices must be integers But since I get names and not names_list my loop is looping over each character of names! for name in names: print(name) [ { " l n a ... Quite stupid but I can't figure out how to do it... -
How Can I increase Django search performance?
I have 100 million contents in boards and show with paigination. But when a user search, query counts the number of contents having a keyword and make pagination. It's big query so I want to increase the performance. -
django rest framework social oauth2 with google
I am total noob to django and programming as whole, so excuse me, if the question seems silly to you, but the last couple of days I've been struggling with the task of implementing social authentication with django rest framework social oauth2 library. I followed this https://chrisbartos.com/articles/how-to-implement-oauth2-using-django-rest-framework/ tutorial for the local authentication and so far it is working. The unclear process for me is the social authentication itself. My questions are as follows: When I am building the application from the admin panel what should be the value of Authorization grant type? How should look like the Postman request, so I can receive the Authorization code for the particular user? Even though I've watched couple of videos about Oauth2 so I understand the idea behind the process, I can't figure it out for how to make it work for me. Any suggestion and guidance would be appreciated. Thank you. -
Django: how to annotate a comparison as an expression?
I have a model including these two fields in my models.py: class Dummy(models.Model): timestamp1 = models.DateTimeField() timestamp2 = models.DateTimeField() Now I want to list all values including the fact, if timestamp1 is greater than timestamp2. Instead of figuring that out in the template, I thought the right way would be to annotate this in the views.py. Unfortunately this does not work: from .models import Dummy dummy = Dummy.objects.annotate(is_newer=timestamp1 > timestamp2) I get the error: QuerySet.annotate() received non-expression(s): False. OK, annotate needs an expression, so I tried using When: from .models import Dummy from django.db.models import When dummy = Dummy.objects.annotate(is_newer=When(timestamp1__gt=timestamp2, then=True) This leads to the following error message: name 'timestamp2' is not defined Now I am out of ideas. What should I do? -
Convert the name of image file automatically when i use Python for loop in HTML(Django)
I'm Trying to make my own blog for practice Django. In index page, There are several images. and those image's name is 'image1.jpg. / 'image2.jpg' / 'image3.jpg' ....... I want to use for loop in html to show those images. This is my code and It does not working. (I use forloop.counter) Do you have some Ideas? Thanks (Sorry for my English...) {% for post in lastest_post %} {% if forloop.first %} <div class="col-md-12"> <div class="single-post-big"> <div class="big-image"> <img src="{% static 'img/post-image{{ forloop.counter }}.jpg' %}" alt=""> </div> <div class="big-text"> <h3><a href="{{ post.get_absoulte_url }}">{{ post.title }}</a></h3> <p> {% if post.is_content_more320 %} {{ post.get_content_320 }} {% else %} {{ post.content }} {% endif %} </p> <h4><span class="date">25 February 2017</span><span class="author">Category <span class="author-name"> {% for c in post.category.all %} {{ c }} {% if not forloop.last %} , {% endif %} {% endfor %} </span> </span> </h4> </div> </div> </div> {% else %} -
How to hide dropdown when another dropdown is clicked
I have two dropdown lists in same class: HTML <li class="menu"><a href="#" onclick="studentDrop()">Studenci</a></li> <div class="dropdown-content" id="subDrop"> test </div> <li class="menu"><a href="#" onclick="subjectDrop()">Przedmioty</a></li> <div class="dropdown-content" id="subjectcont"> {% for subject in subjects %} {{ subject.subject_name }} {% endfor %} </div> CSS .dropdown-content { display: none; position: absolute; background-color: #f9f9f9; min-width: 160px; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); padding: 12px 16px; z-index: 1; } .show { display: block; } Javascript function subjectDrop() { document.getElementById("subjectcont").classList.toggle("show"); window.onclick() } function studentDrop() { document.getElementById("subDrop").classList.toggle("show"); window.onclick() } window.onclick = function(event) { if (!event.target.matches('.column-left a')) { var dropdowns = document.getElementsByClassName("dropdown-content"); var i; for (i = 0; i < dropdowns.length; i++) { var openDropdown = dropdowns[i]; if (openDropdown.classList.contains('show')) { openDropdown.classList.remove('show'); } } } } window.onclick hides all dropdowns when clicked outside. However, I can't figure out how to hide one dropdown when another is clicked. When I click one after another, two dropdowns are shown at once. -
The view company.views.edit_res didn't return an HttpResponse object. It returned None instead
ValueError at /company/edit_res/1/ see my code and help to resolve it views.py def edit_res(request, id): if request.method == 'POST': pi = ResRegister.objects.get(pk=id) fm = CompRegisterForm(request.POST, instance=pi) if fm.is_valid(): fm.save() else: pi = User.objects.get(pk=id) fm = CompRegisterForm(instance=pi) return render(request, 'comp/edit.html', {'form': fm}) <!doctype html> {% extends 'Comp_base.html' %} {% block body %} {% load static %} <div class="container"> <h1>Update Information</h1><br> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit" name="register" class="btn btn-primary btn-lg btn-block">Update</button> </form> </div> {% endblock %} what would i do now any suggestios?