Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django View Skipping a return statement
def blockdata(request,districtid): #in the template, we already passed the districtid from index view to form and back here. if request.method=="POST" and 'send' in request.POST: blockid=request.POST.get('selected','') elif request.method=="POST" and 'search' in request.POST: **print('hey i got your request.')** return HttpResponseRedirect(reverse('drilldown')) else: blockid=request.session['blockid'] total_population=Population.objects.filter(districtname=districtid,talukname=blockid).count()#population of district total_males=Population.objects.filter(districtname=districtid,talukname=blockid,gender='M').count()#males in district malestopop=total_males/total_population total_females=Population.objects.filter(districtname=districtid,talukname=blockid,gender='F').count()#females in district femalestopop=total_females/total_population total_vulnerable=Population.objects.filter(districtname=districtid,talukname=blockid,total__gt=0).count()#total vulnerable in district vultopop=total_vulnerable/total_population total_over_60=Population.objects.filter(districtname=districtid,talukname=blockid,age__gte=60).count()#population of district >=60 over60topop=total_over_60/total_population total_over_60_vul=Population.objects.filter(districtname=districtid,talukname=blockid,age__gte=60,total__gt=0).count()#population of district >=60 & vulnerable over60andvul=total_over_60_vul/total_over_60 total_over_60_vul_male=Population.objects.filter(districtname=districtid,talukname=blockid,age__gte=60,total__gt=0,gender='M').count()#population of district >=60 & vulnerable & male over60malevul=total_over_60_vul_male/total_over_60 total_over_60_vul_female=Population.objects.filter(districtname=districtid,talukname=blockid,age__gte=60,total__gt=0,gender='F').count()#population of district >=60 & vulnerable & female over60femalevul=total_over_60_vul_female/total_over_60 phcs=Population.objects.filter(districtname=districtid,talukname=blockid).values_list('phcname',flat=True).distinct()#unique taluks context={'blockid':blockid, 'districtid':districtid, 'total_pop': total_population, 'male_pop': round((malestopop*100)), 'female_pop': round((femalestopop*100)), 'total_vul': round((vultopop*100)), 'over60': round((over60topop*100)), 'over60vul':round((over60andvul*100)), 'over60vul_male':round((over60malevul*100)), 'over60vul_female':round((over60femalevul*100)), 'blocks':phcs} return render(request,'ashadrill/base.html',context) Above is a view function. Below is my app's urls.py urlpatterns = [ path('',views.index,name='index'), path('<slug:districtid>/',views.blockdata,name='blockdata'), path('<slug:districtid>/<slug:blockid>/',views.phcdata,name='phcdata'), path('<slug:districtid>/<slug:blockid>/<slug:phcid>/',views.centerdata,name='centerdata'), path(r'<slug:districtid>/<slug:blockid>/<slug:phcid>/(?P<centerid>[-\w.]+)/$',views.villagedata,name='villagedata'), path('drilldown/',views.drilldown,name='drilldown') In the above view function called blockdata, when my condition is true, it does print the print statement. But instead of return a reverse('drilldown') function, it ignores the return statement and just carries on with the rest of the code as if there is no return statement. I do have a view called 'drilldown' def drilldown(request): return HttpResponse(200) I am not sure why it is skipping the return of redirect. I have also tried with … -
getting problem in importing libraries in Django
I'm getting this error even tho I have installed pylint in the environment it still showing this error -
what does it take to upload a large file on heroku?
I am trying to upload a video on a Django server hosted on heroku; it is not working but when uploading a picture it works. I am also using AWS to store my files. Is that i am using heroku free? -
How to add actions to admin page with non-ascii charecters
I have this code which works fine in Django admin page, but is there a way to keep action name in Russian but function name in English? actions = ["Отправить_сообщение"] # add action to list page def Отправить_сообщение(self, request, queryset): pass cheers -
How can i handle multiple form classes in a single page in django?
I basically need to design a web page that takes in multiple input (split into different classes) from a user and submit it and redirect to next page,(i.e 5 classes in a single page with only 1 submit button). How do i approach this in django models forms and views ? -
Django - Field 'id' expected a number but got 'WUIbt'
I'm working on an online quiz. I don't want my users to be able to access questions by typing "/questions/1" so I need random ID. I created a function that returns a random string (eg 'WUIbt'): def random_id(): char = "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJQLMNOPQRSTUVWXY" id_len = 5 question_id = "".join(random.sample(char, id_len)) return question_id Then I use it in my question model : class Question_Num(models.Model): num_question = models.IntegerField(default=0) question = models.TextField(max_length=1000, unique=True) reponse = models.IntegerField(default=0) id = models.AutoField(primary_key=True, default=random_id, editable=False, max_length=5) class Meta: verbose_name = 'Question' verbose_name_plural = 'Questions' def __str__(self): return f'Question n°{self.num_question}' But when I create a question, I have a Field 'id' expected a number but got 'WUIbt' error. Here is the form, in case you need it : class Form_Creation_Question(forms.ModelForm): num_question = forms.IntegerField(label='Numéro de la question') class Meta: model = Question_Num fields = ['num_question', 'question', 'reponse'] Should I generate a random number that I transform in hexadecimal or is it possible to create a string id ? -
Shopify Django App: printf: warning: ignoring excess arguments, starting with ‚;‘
Used python version: 3.7 and 3.8 I am trying to follow the official instruction from Shopify (in readme.md) to start a Django Shopify App: https://github.com/Shopify/shopify_django_app By step 2 in „Setup environment „, what look like that: Generate a secret key and add it to .env by running the following in the command line: printf 'DJANGO_SECRET=' >> .env; python -c 'import random; print("".join([random.choice("abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)") for i in range(50)]))' >> .env I am getting a warning: printf: warning: ignoring excess arguments, starting with ‚;‘ After running the command my .env file look like that: SHOPIFY_API_KEY=“1111111111111111” SHOPIFY_API_SECRET=“11111111111111”DJANGO_SECRET= if course that generate me any key, what follow an error by trying to start a server on the next step from the instruction. What I am doing wrong and why is not generating the key for me. Thank you in advance -
Can we use class as view in django?
view.py class myapp(): def index(self): return redirect(someusrl) def productview(self): return redirect(someusrl) urls.py path('', myapp.index, name="home"), path('product', myapp.productview, name="Product_page") like this way thanks in advance :) -
django + chart.js: page language switch button mess up the charts. What?
I am having a super strange issue in my django app that renders graphs with chart js. I used i18n to handle the translation but after spending hours trying to fix my charts, I found out that when language is english the chart work well but when another language is selected, then it either dont work or show messed up values. I don't even know what code to include since I can't figure out how lanaguage and the chart.js are related. Has someone had the same issue before? Or any clue how this could come from? -
ModelForm is not being saved, database fields are empty
i made ModelForm for booking. When i pass the data to the form, no errors are being shown and i think it is being executed successfully. But when i check the database nothing is being saved. here is my code. models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Post(models.Model): choice_field = ("site 1", "site 1"), ("site 2", "site 2"), ("site 3", "site 3") visitdate = models.DateTimeField(default=timezone.now) visittime = models.TimeField(default=timezone.now) reason = models.TextField() poc = models.CharField(max_length=50) site = models.CharField(max_length=6, choices=choice_field) slug = models.SlugField(unique_for_date=timezone.now) form.py class booking(forms.ModelForm): choice_field = ("site 1", "site 1"), ("site 2", "site 2"), ("site 3", "site 3") visitdate = forms.DateTimeField(required=True) visittime = forms.TimeField(required=True) reason = forms.CharField(widget=forms.Textarea, required=True) poc = forms.CharField(max_length=50) site = forms.MultipleChoiceField(choices=choice_field, widget=forms.NullBooleanSelect) class Meta: model = Post fields = ("visitdate", "visittime", "reason", "poc", "site",) views.py @login_required def dashboard(request): lu = request.user form = booking() if request.method == "POST": form = booking(request.POST) if form.is_valid(): post = form.save(commit=False) post.user = request.user post.save() return render(request, 'account/dashboard.html', {'lu':lu, 'booking': form}) dashboard.html <form method="POST"> {%csrf_token%} <div class="ff"> <div align='center'> <select class="selector" {{booking.site}}</select> </div> <br> <div align='center'> <input type="date" class="datetime" placeholder="Date" {{booking.visitdate}} <input type="time" class="datetime" placeholder="Time" {{booking.visittime}} </div> <br> <input type="text" class="credentials" placeholder="Point of Contact" {{booking.poc}} … -
format method does not assign values to a string when importing as global variable
I defined some variables inside a file named queries.py and import them inside another file named views.py. The problem is python format does not assign values of each variable to the corresponding placeholder. Consider following lines of code : queries.py main_where_query = ''' where users.deleted_account is null and length(users.phone_number) > 2 and length(users.phone_number) < 20 and users.phone_number not like '+98888888%' ''' messages_where_query = """{0} and messages.date>'{1}' and messages.date<'{2}' """ views.py from .queries import * def get_activity(request): global main_where_query global messages_where_query messages_where_query.format(main_where_query, str(start_date), str(end_date)) .... and the output is : select count(messages.message_id) from messages join users on users.id = messages.sender {0} and messages.date>'{1}' and messages.date<'{2}' and messages.media_type = 0 As you can see all the placeholders are untouched like {0} {1} {2}.I'm sure that those variables are not empty and imported correctly. -
Django rest framework filter not working. Always giving full queryset or data on any filrer query
I making a filter API but no matter what filter I apply it doesn't give me any result. class filter_dataset(ListCreateAPIView): filter_class = ProductFilter serializer_class = AdjustDatasetSerializers filter_backends = (filters.DjangoFilterBackend,) filter_fields = ('revenue', 'spend', 'OS', 'date') def get_queryset(self): dataset = Dataset.objects.all() return dataset def get(self, request): dataset = self.get_queryset() serializer = self.serializer_class(dataset, many=True) return Response(serializer.data, status=status.HTTP_200_OK) models: from django.db import models class Dataset(models.Model): date = models.DateTimeField(max_length=255,auto_now_add=True) channel = models.CharField(max_length=255,null=True, blank=True) OS = models.CharField(max_length=255,null=True, blank=True) impressions = models.CharField(max_length=255,null=True, blank=True) clicks = models.CharField(max_length=255,null=True, blank=True) installs = models.CharField(max_length=255,null=True, blank=True) spend = models.CharField(max_length=255,null=True, blank=True) revenue = models.CharField(max_length=255,null=True, blank=True) Filter class: class ProductFilter(filters.FilterSet): revenue = filters.NumberFilter(field_name="revenue") spend = filters.NumberFilter(field_name="spend") OS = filters.CharFilter(field_name='OS', lookup_expr='OS__exact') date = filters.DateFromToRangeFilter(field_name='date') class Meta: model = Dataset fields = ['revenue', 'spend', 'OS', 'date'] On django rest framework filter fields are showing but no matter what you enter in field this is not giving any results. All was all the data is shown. I'm stuck on this, any help would be needful. -
Class XXX missing "Meta.model" attribute
I Trying get list of objects using DRF, But Getting Error like "missing "Meta.model attribute" Serialzers.py from rest_framework import serializers from .models import Car class CarSerializer(serializers.ModelSerializer): class Meta: model: Car fields=['brand_name','model_name','car_color'] Views.py Code Below: from app2.serializers import CarSerializer from rest_framework import generics class BrandList(generics.ListCreateAPIView): queryset = Brand.objects.all() serializer_class = CarSerializer URLS.py: from app2.views import ,BrandList path("BrandList/", BrandList.as_view(), name="BrandList"), Please someone get out from this -
In what order does celery process tasks when it is configured to use multiple queues?
If I run celery so that it consumes from multiple queues, what order will it process tasks? Given the following startup: celery worker -A app --concurrency=4 --pool=prefork -Ofair --queues=default,lowpriority,highpriority If 1000 tasks get added to the default queue, then 1000 tasks are added to the lowpriority queue, then 1000 tasks are added to the highpriority, in what order are those tasks processed? I think they will be processed in an approximate arrival order: 1000 from default, then 1000 from lowpriority, then 1000 from highpriority. What I would like to happen is a round robin processing style: 1 from default, 1 from lowpriority, 1 from highpriority ... I am aware of Task Priorities but would prefer to avoid them at this stage, because that is a larger migration that requires more planning. Can I get celery to process tasks from multiple queues in a round-robin style? -
Django ORM group by calculation should return data if the foreign have no related data too
This is my models: class Purchase(models.Model): amount = models.DecimalField( max_digits=6, decimal_places=2, default=0.00 ) entry_for = models.ForeignKey( User, on_delete=models.CASCADE, related_name='ledger_entry_for', ) For example, i have 400+ users but only 50 users have purchased multiple time So i want total purchase amount user by user. so this is my query is below: purchase_user_wise = Purchase.objects.values( 'entry_for' ).annotate( total_purchase=Sum('amount') ) Above query works nice and I return total amount user by user but the problem is: it only return those users calculation who have purchased at least one time or more than one time. and this query not returning all 400 users data. I want, if any of the users don't have any purchase entry, it should return 0 and rest of the calculation should be works that way. Can anyone help me how can i do it? -
What is the most efficient way to create a lobby django
I am trying to create a lobby that would be accessible by a link game/gameID. What i have is just a simple field in my db playerNumber = models.IntegerField(default =0). When user is connected i increment playerNumber by 1. When the player number is 2 i just render error page. But when user closes game page by some mistake, someone else can join instead of him. How would i make this page IP specific or somehow reserve the page for only 2 users and make them able to come back if they left. -
How to change the default zoom level of a map in Geodjango's admin?
I've been looking into GeoDjango recently, I'm struggling to customize the default zoom level of the openstreet map displaying in my admin section. Below is what I have tried but with no effect, please assist. from django.contrib import admin from django.contrib.gis import admin class LocationAdmin(admin.OSMGeoAdmin): default_zoom = 5 -
Django - Redirect uppercase urls to lowercase
In my Django apps, I have many urls including /(?P<project_name>[_\w]+)/. The project_name is defined by users and it is an attribute of the Project model. I've added a validator on the project_name to check if it's lowercase. So new names are all lowercase but some old names include uppercase characters. I would like to change all the names stored to make them lowercase but at the same time, I don't want users to get an error when trying to access to one of the url with the old project name including uppercase characters. As I have many urls and many views, I don't want to update each to manually .lower() the project_name. Is there a way to redirect all urls including /<project_NAME>/ to /<project_name>/? -
How to use Prepend_WWW in DJango
I am facing issues in a project, my site opens with www, but doesn't load if that part is missing. I read about PREPEND_WWW= True (since if user types just domain, redirect to www.domain.com which works) in settings.py on django, but that just doesn't work. I have enabled CommonMiddleware too. Any other thing that can be done to solve?. Please help -
How to change a form dynamically?
I have two models, Company andEmployee. I would like that when the user selected the company, the employee data would be set dynamically in the employee form because both forms will be shown on the same page. So initially on the page I have the form to select the company and immediately after the selection the data of the employees linked to the company appear to the user. I made the forms like this: class CompanyForm(ModelForm): class Meta: model = Company fields = ['nome'] class EmployeeForm(ModelForm): class Meta: model = Employee fields = ['nome'] def __init__(self, *args, **kwargs): super(EmployeeForm, self).__init__(*args, **kwargs) self.fields['nome'].queryset = Employee.objects.filter(company = CompanyForm.cleaned_data.get('nome')) But I get the following error: 'CompanyForm' object has no attribute 'get' Is it possible to change one form immediately when the other is changed (on the same page) without submitting to Django? -
Http request between two containers
I am creating a web service which uses react for the frontend and django REST for the backend. Both are running in separate docker containers. My docker-compose file looks like this. services: db: image: postgres volumes: - ./config/load.sql:/docker-entrypoint-initdb.d/init.sql environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: build: . image: gudmundurorri4/hoss-web command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code stdin_open: true ports: - "8000:8000" depends_on: - db frontend: image: gudmundurorri4/hoss-frontend stdin_open: true ports: - "3000:3000" depends_on: - "web" Both the web and frontend containers work fine. The backend works when I open it in the browser and when I execute a get request to http://web:8000 from within the frontend container I get the correct response. However when I execute a GET request from my react app using the same address (http://web:8000) it always fails with the error net::ERR_NAME_NOT_RESOLVED -
pyttsx3 in Django
This code works on python shell but doesn't work on localhost The main purpose of code is, to make application say 'hi' every second in python from time import sleep import pyttsx3 engine = pyttsx3.init() def say(text): engine.say(text) engine.runAndWait() def runAfter(function): def wrapper(): while True: function() sleep(1) return wrapper @runAfter def sayHi(): arg = 'hi' print(f'say({arg})') say(arg) sayHi() in django @runAfter def sayHi(): arg = 'hi' print(f'say({arg})') say(arg) def test(responce): sayHi() return HttpResponse('<h1>test</h1>') in django it says 'hi' once -
Django give Error 500 for all static files like CSS and Images, when DUGUB is FLASE
I've tried different solutions already posted by users, but they didn't work for me. settings.py of Project BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = False ALLOWED_HOSTS = ["*"] STATIC_URL = '/static/' STATICFILES_DIRS=[ os.path.join(BASE_DIR,'static') ] STATIC_ROOT=os.path.join(BASE_DIR,'assets') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') All my CSS files are in style folder inside the static folder. And all images are in the media folder. Browser Consol Logs Refused to apply style from 'http://127.0.0.1:8000/static/styles/LandingPage_CSS.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. icons8-user-48.png:1 Failed to load resource: the server responded with a status of 500 (Internal Server Error) Doorakart%20icon.png:1 Failed to load resource: the server responded with a status of 500 (Internal Server Error) apple.jpg:1 Failed to load resource: the server responded with a status of 500 (Internal Server Error) banana.jpg:1 Failed to load resource: the server responded with a status of 500 (Internal Server Error) watermelon.jpg:1 . . . Failed to load resource: the server responded with a status of 500 (Internal Server Error) Refused to apply style from 'http://127.0.0.1:8000/static/styles/LandingPage_CSS.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. Example of HTML file {% load static … -
Django Form Modification with populated value set
I have a problem with this Lead Form. When the user create a lead, he assigns it to a customer. I got the list of customers from the init that retrieve the user associates and build the customers list for my user and his associate. This works fine during the lead CREATION. Unfortunately, when the user wants to edit the lead, I can see the customer id in the pre-loaded form from the lead instance, but it is not pre-selected on the screen. my class LeadForm class LeadForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(LeadForm, self).__init__(*args, **kwargs) userutils = UserUtilities() associated_users = userutils.get_associated_users_for_customer_module(self.user) self.fields['customer'].queryset = Customer.objects.filter(creator__in=associated_users) team_members = userutils.get_associated_users(self.user) self.fields['assignee'].queryset = team_members customer = forms.ModelChoiceField( queryset=None, label="Customer Email", required=True, widget=forms.Select(attrs={'class': 'form-control select2 select2-container--custom', 'style': 'width:20%'})) and here it is what I obtain instead of the existing customer -
Audio not playing in django template
I am trying to build a audio player with a django backend.The front end is made with javascipt and html5.IT works on its own but the audio wont play with django.Here's my code. My app/models.py:- from django.db import models # Create your models here. class song_thumb(models.Model): artist=models.CharField(max_length=100,null=True) song_title=models.CharField(max_length=100,null=True) album=models.CharField(max_length=100,null=True) song_duration=models.FloatField(null=True) img=models.ImageField(upload_to='pics',null=True) song=models.FileField(upload_to='media',null=True) my views.py:- from django.shortcuts import render from .models import song_thumb # Create your views here. def songs(request): artist1=song_thumb() artist1.artist='Alcest' artist1.song_title='Kodama' artist1.album='Kodama' artist1.song_duration='9.10' artist1.img='kodama.jpg' artist1.song='Kodama.mp3' artist2=song_thumb() artist2.artist='Tash Sultana' artist2.song_title='Jungle' artist2.album='Jungle' artist2.song_duration='5.17' artist2.img='jungle.jpg' artist2.song='Jungle.mp3' artist3=song_thumb() artist3.artist='Animals as leaders' artist3.song_title='Cafo' artist3.album='Cafo' artist3.song_duration='6.56' artist3.img='cafo.jpg' artist3.song='Cafo.mp3' artists=[artist1,artist2,artist3] return render(request, 'home.html', {'artists':artists}) my template:- <div class="data-content"> {% for artist in artists %} <div id="img-1" class="tabcontent"> <div class="blog-content"> <div class="row"> <div class="col-3"> <div class="img"> <img class="img-thumbnail" src="{{baseurl}}/{{artist.img}}" alt=""> </div> </div> </div> <div class="title"> <p> {{artist.artist}} </p><br> <p>{{artist.song_title}}</p><br> <p>{{artist.album}}</p><br> <p>{{artist.song_duration}}</p><br> <audio id="myAudio"> <source src="E:\coding\fyp\music\assests\media\Kodama" type="audio/ogg"> <source src={{artist.song}} type="audio/mpeg"> Your browser does not support the audio element. </audio> <p>Click the buttons to play or pause the audio.</p> <button onclick="playAudio()" type="button">Play Audio</button> <button onclick="pauseAudio()" type="button">Pause Audio</button> <script src="{% static 'assests/js/home.js' %}"></script> </div> <span>Close</span> </div> </div> {% endfor %} </div> I have added media_root and media_url.The MEDIA_ROOT=os.path.join(BASE_DIR,'media') and i've saved the audio files in a folder called media inside …