Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can use two types of queryset models override save method?
I have two types of queryset. one is featured=true second is featured=false. i want to ask you if i POST an article with featured=True then the old featured=true get transferred to featured=false queryset. i just want two [:2] values in featured=true queryset. here is the example there are two article in featured=true queryset which i want the second article automatically get updated to featured=false when i create new article. i also try this method that method get this output! models.py def save(self, *args, **kwargs): if self.featured == True: Article.objects.filter(pk__in=(Article.objects.filter(featured=True,).values_list('pk',flat=True)[:2])).update(featured=False) self.featured = True super(Article, self).save(*args, **kwargs) -
Django Postgres syntax error at or near "SEPARATOR"
I recently migrated from mysql to postgres, and now I'm trying to see the admin page for a model in my app. Django responds with ProgrammingError at /admin/app/model/ syntax error at or near "SEPARATOR" LINE 1: ..._CONCAT("app_model_relatedModel"."relatedModel_id" SEPARATOR ... Any clues as to why this is happening? I'm never directly executing sql in the app, it's all done through the ORM. -
Django Using multiple (two) user types extending AbstractUser
For our project, we have two user types: Donor and Hospital. So we use the User model, which extends the AbstractUser model. The Donor and Hospital models both have OneToOneField relationship with the User and it uses the default user authentication. Almost everything works fine. The Donor and Hospital creation works well, the instances are added to the database and we can log in. However, we need the Donor object and its fields in the view and in the template. We have the user contained in the request and the id of the user. donor = Donor.objects.get(pk=request.user.id) Or donor = Donor.objects.filter(donor=request.user).first() Should return the donor object, but it returns None. It works for Hospital. If we do Donor.objects.all() the newly created Donor is not in the list. However, created hospital is present in the list. We cannot figure out what is the problem, the ids for donor and user do not match. Thank you very much for your help! These are our models: class User(AbstractUser): is_donor = models.BooleanField(default=False) is_hospital = models.BooleanField(default=False) class Donor(models.Model): # username, pword, first+last name, email donor = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) # donor_id = models.IntegerField(auto_created=True, unique=True, null=False, primary_key=True) nickname = models.CharField(max_length=40, unique=True) phone = models.CharField(max_length=10) address = … -
Django channels process not sending data
I'm trying to create a Django Channels consumer which receives some data in real time from a RabbitMQ queue and then sends this data to a frontend, in order to let users have real-time data. Here is my basic consumer: class EchoConsumer(AsyncConsumer): async def websocket_connect(self, event): print("connected", event) connection = pika.BlockingConnection( pika.ConnectionParameters(host='localhost')) channel = connection.channel() channel.queue_declare(queue='Test') def callback(ch, method, properties, body): print(" [x] Received %r" % body) channel.basic_consume( queue='Test', on_message_callback=callback, auto_ack=True) print(' [*] Waiting for messages. To exit press CTRL+C') await self.send({ "type": "websocket.accept" }) await channel.start_consuming() async def websocket_receive(self, event): print("received", event) # Echo the same received payload async def websocket_disconnect(self, event): print("disconnected", event) And here is my Javascript code: <script> // websocket scripts var loc = window.location var wsStart = 'ws://' + window.location.host + window.location.pathname var endpoint = wsStart + loc.host + loc.pathname var socket = new WebSocket(endpoint) if (loc.protocol == 'https:'){ wsStart = 'wss://' } socket.onmessage = function(e){ console.log("message", e) } socket.onopen = function(e){ console.log("message", e) } socket.onerror = function(e){ console.log("message", e) } socket.onclose = function(e){ console.log("message", e) } </script> The problem with this code is that, altough in my console i will see the queue waiting for data, on my HTML page i won't see any … -
Django: How can i validate the combination existance of two fields
I'm using Django Model Form Can you help me validate those fields to get field error using clean()? Name cannot repeat on the same office, can only repeat on different office. class CreateSalesRepForm(forms.ModelForm): class Meta: model = CreateSalesRep fields = ['name', 'office'] widgets = { 'office': forms.Select(attrs={'class': 'form-control', 'placeholder': 'Enter Office'}), 'name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter Name'}) } -
Show TimeField value without seconds - Django
I'm displaying a selectbox with hours in it. This hours are fixed and coming from db. For this I used models.TimeField in models.py. Now in html page these hours are shown like 14:00:00. I want to remove seconds. Here are my codes: models.py: class MeetingHour(models.Model): hour = models.TimeField() def __str__(self): return str(self.hour) html: <select> {% for meetinghour in meetinghours %} <option value="{{meetinghour}}">{{meetinghour}}</option> {% endfor %} </select> -
Can't login to django admin account after creating super user
I created a project in django and the first thing I want to do is to create a superuser for admin account and then proceed with the django project but the problem is after creating a superuser account using pyhton manage.py createsuper and filling out the information the superuser gets created it says Superuser created successfully. But when I try to login with these credentials it says Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive. I am not sure if there is some other setting that I need to check out or I am doing something wrong. Please suggest me solution for that. -
MoviePy in Django: Failed to read the duration of the file
I'm trying to pass the video data pulled from a ModelsForm into a moviepy method, however the VideoFileClip() function is unable to read the duration of the file. I've checked the data I'm pulling in and it is the correct namem, currently the issue may be that I'm passing it in as a string. However, without this is errors back as 'endswith' is not a valid attribute. Please see the error and my code below. Thanks for your help! Code Models.py Error Message OSError at /highlights/ MoviePy error: failed to read the duration of file <highlights.splitter.Splitter object at 0x000001A82CE553D0>. Here are the file infos returned by ffmpeg: ffmpeg version 4.1 Copyright (c) 2000-2018 the FFmpeg developers built with gcc 8.2.1 (GCC) 20181017 configuration: --enable-gpl --enable-version3 --enable-sdl2 --enable-fontconfig --enable-gnutls --enable-iconv --enable-libass --enable-libbluray --enable-libfreetype --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libopus --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libtheora --enable-libtwolame --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libzimg --enable-lzma --enable-zlib --enable-gmp --enable-libvidstab --enable-libvorbis --enable-libvo-amrwbenc --enable-libmysofa --enable-libspeex --enable-libxvid --enable-libaom --enable-libmfx --enable-amf --enable-ffnvcodec --enable-cuvid --enable-d3d11va --enable-nvenc --enable-nvdec --enable-dxva2 --enable-avisynth libavutil 56. 22.100 / 56. 22.100 libavcodec 58. 35.100 / 58. 35.100 libavformat 58. 20.100 / 58. 20.100 libavdevice 58. 5.100 / 58. 5.100 libavfilter 7. 40.101 / 7. 40.101 libswscale 5. … -
Why serializing a QuerySet I iobtain a string?
I'm using a js function to obtain some data from my django models. Concretely, I want to obtain the last value from my sensors. I'm doing the following, from django.core import serializers def getData(request): ctx = {} if request.method == 'POST': select = int(request.POST['Select']) last_val = DevData.objects.order_by('dev_id','-data_timestamp').distinct('dev_id') data = serializers.serialize('json', last_val) print(data) print('****************') print(data[0]) # I just obtain a "[" then is a string not a list ctx = {'Select':data} return JsonResponse(ctx) My question is, why the output is a string? How can I convert it to a Json object and then pass it to my js function? Thank you very much!! -
Django Login POST hangs when i do HttpResponseRedirect (302)
I'm Juan Manuel and I have a problem with my Login page in Django 1.11 (Python 2.7). When I do "POST" of username/password Form (passes authenticate() and login() well) and have to redirect (HttpResponseRedirect) to my index page, the browser hangs waiting for a response (it stays in the login page). After POST it wants to redirect to to '/' with a HTTP 302 and stays like that. [01/Apr/2020 16:19:43] "POST /login/ HTTP/1.1" 302 0 I've noticed a few things: 1) It doesn't happend everytime. 2) On Chrome's developer mode with "Disable cache" mode on works fine. 3) On Firefox works fine. 4) With reverse() it's the same problem (internally calls HttpResponseRedirect()). 5) The problem exists on the Developing Server (Django) and in Production Server (Apache). When it's hanging like that, if I press F5 (reload), works fine and the redirection goes to the index. url.py: # -*- coding: utf-8 -*- from django.conf.urls import patterns, include, url from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns from .views import * admin.autodiscover() urlpatterns = patterns('', url(r'^', include('tadese.urls')), url(r'^login/$', login), url(r'^login_cuota/$', login_cuota), url(r'^logout/$', logout), url(r'^admin/', include(admin.site.urls)), )+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) if settings.DEBUG is False: #if DEBUG … -
How to add a share button in Django to share a post
I am relatively new to Django, I have a blog that I have been working on. However, I am having problem implementing a sharing button to share my posts on social media, with the title and thumbnail,specifically Facebook and WhatsApp.I have researched and googled all the possible solutions, but neither of them tends to solve my problem. Not many tutorials out here have covered this issue. I have used the social_share,django_addthis, and social_share_widgets but none of them seem to help. Here are my models and templates {% extends 'base.html' %} {% load static %} {% load social_share %} {% load blog_tags %} {% block content %} <p>{{post.content| safe}}</p> <div class="social-contact"> <a href="#" id="shown" style="background-color: red;"><i class="fa fa-share"></i> Share</a> <a id="hidden" href="https://facebook.com/share?url=http://devbrian.com{{ request.get_full_path|urlencode }}" class="facebook-link"><i class="fa fa-facebook"></i> Facebook</a> <a id="hidden" href="https://www.twitter.com/share?url=http://devbrian.com{{ request.get_full_path|urlencode }}" class="twitter-link"><i class="fa fa-twitter"></i> Twitter</a> <a id="hidden" href="https://www.instagram.com/share?url=http://devbrian.com{{ request.get_full_path|urlencode }}" class="instagram-link"><i class="fa fa-instagram"></i> Instagram</a> <a style="background-color: green;" href="https://api.whatsapp.com/send?+254799043853=+*YOURNUMBER*&text=%20*{{ request.get_full_path|urlencode }}&title=<your title>&summary=<your desc>&source=http://devbrian.com*" class="youtube-link"><i class="fa fa-whatsapp"></i> Whatsapp</a> </div> {% endblock content %} class Post(models.Model): author = models.ForeignKey(User,on_delete=models.CASCADE) title = models.CharField(max_length=200) slug = models.SlugField(max_length=200,blank=True,unique=True) thumbnail = models.ImageField() def get_absolute_url(self): return reverse('details', kwargs={'slug': self.slug}) I will appreciate your help -
Django-differnt models for specific group model choices Django
Could someone help me how to solve my question, What is an efficient and good way to write group model choices, I want multiple Django model values depends on choice field values! (Django rest framework)enter image description here For jobs it's giving different field and if you choose another option it displaying other options like below picture This is for cars..I would like to write code for this similar one -
HOW TO EDIT A RECORD BY USE DJANGO FORM INTO A TEMPLATE
I have two models that have relationship to each other which are a child and academy model which means that a child can have academic details,and then i pass a child ID into the template to edit academic details of child here is academy model #ACADEMY MODEL from child.models import Child_detail class Academic(models.Model): Student_name = models.ForeignKey(Child_detail,on_delete = models.CASCADE) Average_grade = models.CharField(max_length = 10) Overall_position = models.IntegerField() Total_number_in_class = models.IntegerField() def __str__(self): return str(self.Student_name) here is child model #CHILD MODEL from django.db import models class Child_detail(models.Model): Firstname = models.CharField(max_length = 50) Lastname = models.CharField(max_length = 50) Tribe = models.CharField(max_length = 50) Current_Address = models.CharField(max_length = 50) def __str__(self): return self.Firstname I come to the scenario that i want to edit academic details of a child by use django form to the template that i pass child ID def edit(request,pk): child=get_object_or_404(Child_detail,pk=pk) form=AcademicForm(request.POST or None,instance=child) if form.is_valid(): form.instance.Student_name=child form.save() return redirect('more',pk=pk) context={ 'form':form } return render(request,'functionality/more/academy/edit.html',context) And here is my form.py file class AcademicForm(forms.ModelForm): class Meta: model=Academic fields='Class','Date','Average_grade','Overall_position','Total_number_in_class' labels={ 'Average_grade':'Average Grade', 'Overall_position':'Overall Position', 'Total_number_in_class':'Total Number In Class' } Date = forms.DateField( widget=forms.TextInput( attrs={'type': 'date'} ) ) And also this is my template that pass child id <form action="" method="post" autocomplete="on"> {% csrf_token %} … -
meke tests with django inside innerHTML method
I am new in django and I faced a problem in my project.The problem is I want to put some tests inside innerHTML method like this: var level = document.getElementById('level'); selectElementM.innerHTML = ` <option value="">--select--</option> {% for module in modules %} {% ifequal module.level|lower ${level} %} <option value="{{ module.name}}">{{ module.name}}</option> {% endifequal %} {% endfor %} // here are other tests... `; I know it's not possible for doing it like this so I need another proper way -
Django username is empty in a GET request
In my views.py, I have a function which uses GET method as shown below. def status_codes(request): try: url = request.GET.get('url') urls = linksextraction(url) url_codes.objects.filter().delete() print(request.user.username) # prints empty string # do something return JsonResponse(url_final_data) except Exception: return JsonResponse({"message": "Invalid url"}) When i try to print the current logged in user, it prints an empty string. I have used the same in other functions which uses POST and it works fine there. Can someone please help me getting the username in such scenarios where it involves GET method? -
Django self referance filter for version
I have created different version of Template model using self reference field with one parent Template when user update any template i will create new version of previous template. Model class AppTemplate(models.Model): app = models.ForeignKey( Application, on_delete=models.CASCADE, related_name="apps" ) name = models.CharField(max_length=100, null=False) description = models.TextField(blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) version_ref = models.ForeignKey('self', null=True, blank=True, on_delete=models.SET_NULL) version = models.FloatField(default=1.0) Now i want to filter template for specific app if one template have multiple version display only latest template. I have done this using looping. templates = AppTemplate.objects.filter(app=app_id, version_ref__isnull=True) queryset = [] for template in templates: child_template = AppTemplate.objects.filter(version_ref=template).order_by('-created_at') if len(child_template) > 0: queryset.append(child_template.first()) else: queryset.append(template) How can i improve my queryset Filter ? -
is there any way to request for client zone base data retrieval from angular app to django?
while interacting from angular 8 app to django back end i want to retrieve data based on user timezone without doing any manual conversion between the timezone . Date being saved is in UTC format on backend. in which format date should be sent so that it automatically retrieve correct data for that zone. -
Convert postgres raw query to Django ORM query and group by
I have a raw Postgresql query which needs to be converted to Django ORM query. I was able to execute the query in Postgres and see the expected result. I'm getting 5 records for the raw query on postgres DB. But when I execute the Django ORM query, it's not giving the expected output. I'm getting 78 results for the ORM query in postgres. Please let me know where am I making mistake in Django ORM query. Raw postgres query: select customer_id, program_id, project_id, store_id, count(store_id) from public.alerts_alert where (customer_id=2 and program_id=134 and project_id=1364) group by customer_id, program_id, project_id, store_id Django ORM query: queryset = Alert.objects.filter(**filter_params).defer( 'unregistered_timestamp' ).annotate( customer_name=F('customer__name'), program_name=F('program__name'), project_name=F('project__name'), store_count=Count('store') ) **filter_params is where I'll be providing actual values as mentioned in raw queryset. -
Cannot get cookie value
I have a script that calls a prompt when I push a button and gets a number from the user. The number is stored in a cookie. Then that script loads a view that gets the number from the cookie and passes it to a form. Currently I have the cookie being saved; I can see it in the browser debugger. But when I try to get the cookie in my view it always returns null. Please I need help figuring out what the problem is. JavaScript $(document).ready(function() { $(document).off('click', '.order_button').on('click', '.order_button', function() { // $(".on_button").click(function() { var amount = prompt("Please enter amount of orders" ,"0") if (parseInt(amount) <= 0 /* || amount === null */) { alert("Please enter integer greater than 0") } else if (parseInt(amount) > 0) { document.cookie = "amount=" + amount; //+ ";max-age=60"; console.log(document.cookie) var link = $(this).find('a'); console.log(link.attr('href')); window.location.href=link.attr('href'); console.log("OK"); } return false; }); }); View def add_order(request, meal_slug, meal_restaurant): print("OK") amount = get_server_side_cookie(request, 'amount', '1') print(amount) # clear_amount_cookie(request) if amount is not None: meal = Meal.objects.get( slug=meal_slug, restaurant_slug=meal_restaurant) user = UserProfile.objects.get(user=request.user) order = Order.objects.create( meal=meal, customer=user, amount=amount, date=datetime.now()) order.save() # clear_amount_cookie(request) return redirect('food_cloud:index') Get cookie function def get_server_side_cookie(request, cookie, default_val=None): val = request.COOKIES.get(cookie) print(val) … -
How to create booking/reservation in Django
I created this Library website in Django, where I created 2 groups - Librarians and Library Members. Librarians are able to play with books and catalogs in library and it all works perfect, but I dont know how to make Library Members being able to book a book or catalog. Please any example of solution ? I am despred to figure out. Thanks. -
it is correct to use csrf token to protect django rest framework API? - I need protect to API (without user account authentication) from spammers
I know that django rest framework has an authentication system based in SessionAuthentication, TokenAuthentication, BasicAuthentication and others, and Third party packages: JSON Web Token Authentication, etc. But all are based in user account authentication and I need use my API with ajax from django template and only want that my application use the API without expose to spammers. That's what I've done: 1 - Custom authentication based to csrf token permission.py from django.middleware.csrf import get_token, _unsalt_cipher_token, _compare_salted_tokens from rest_framework.permissions import BasePermission class HasCsrfTokenValid(BasePermission): def has_permission(self, request, view): try: csrf_token = request.headers.get("api-csrftoken") # get token from ajax request csrf_cookie = request.META.get("CSRF_COOKIE")# get token from cookie token_valid = _compare_salted_tokens(csrf_token, csrf_cookie) # compare if is valid token except TypeError: token_valid = False return token_valid or bool(request.user and request.user.is_staff)#return True or False``` 2- protect view view.py from . permissions import HasCsrfTokenValid class SomeAPI(generics.RetrieveAPIView): queryset = Model.objects.all() serializer_class = SomeSerializer permission_classes = [HasCsrfTokenValid] authentication_classes = [SessionAuthentication, ] 3- Ajax Request index.html <script> $.ajax({ url:'http://localhost:8000/api', headers:{'api-csrftoken':'{{csrf_token}}'}, success:function(data){ console.log(data) }, error:function(error){ console.log(error) } }); </script> Note: Django REST Framework API Key is a powerful library to use authentication without user account but this key it would be expose in ajax request in frontend. Is it ok what … -
How to solve No Reverse Match error in django
I am getting this error and I could not solve it, "Reverse for 'post_task' with arguments '('',)' not found. 1 pattern(s) tried: ['post/ajax/task/(?P[0-9]+)$'] " I have a script on my main page, and when I am on the template page everything is ok. but when I go to any other page including the main page, I get this error. can you assist me? main.html <script> if ($('#task-form').length > 0) { // Exists. $("#task-form").submit(function (e) { // preventing from page reload and default actions e.preventDefault(); // serialize the data for sending the form data. var serializedData = $(this).serialize(); // make POST ajax call $.ajax({ type: 'POST', url: "{% url 'post_task' order.id %}", data: serializedData, success: function (response) { // on successfull creating object // 1. clear the form. $("#task-form").trigger('reset'); // 2. focus to nickname input $("#task").focus(); // display the newly friend to table. var instance = JSON.parse(response["instance"]); var fields = instance[0]["fields"]; $("#my_tasks tbody").prepend( `<tr> <td >${fields["task"] || ""}</td> </tr>` ) }, error: function (response) { // alert the error if any error occured alert(response["responseJSON"]["error"]); } }) }) } $("#service-form").submit(function (e) { // preventing from page reload and default actions e.preventDefault(); // serialize the data for sending the form data. var serializedData … -
How to add suggested post
how do I add a Suggested post after my first two post. For example, Post Post... Suggested post... Post Post. def home(request): all_images = Image objects.filter(imageuploader_profile=request.user, active=True) context={'all_images':all_images} #my post here {% for post in all_images %} {{ post.username }} {% if post.profile_pic %} <img src = "{{....}}"> {% endif %} {% endfor %} -
Add user to a group at signup in Django
New to Django here. There are three types of users: Bronze, Silver and Gold with different permissions. All users start out as Bronze when they sign up and then move upwards when they fulfill certain conditions. Therefore I tried to customize the User model using Django's tutorial. So far I have been able to create the users correctly. However, I want to now add these users to the Bronze group as soon as they sign up and am not sure where do I put that code. Here is my code. Its fairly straightforward. models.py # models.py from django.contrib.auth.models import AbstractUser, Group from django.db import models class CustomUser(AbstractUser): pass # add additional fields in here def __str__(self): return self.username forms.py from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class CustomUserCreationForm(UserCreationForm): class Meta: model = CustomUser fields = ('username', 'email') class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = ('username', 'email') views.py from django.shortcuts import render from django.urls import reverse_lazy from django.views.generic.edit import CreateView from .forms import CustomUserCreationForm # Create your views here. class SignUpView(CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy('login') template_name = 'signup.html' admin.py from django.contrib import admin # Register your models here. from django.contrib.auth import … -
Using Google Firestore with Django
Hi so i was wondering if its possible to use Google Firestore with Django. I don see why i couldn't but i cant find anywhere explain how to integrate it. I know in the Django Settings it gives a database option and it starts out using SQLite3. Is this where i change it or do i write specific code where i have to add every entry manually like i saw in one video. If anyone has any sample videos that wold be greatly appericated. Im reading the google firestore Doc and its just showing me how to manually enter the data.