Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
- 
        
Django - Group by two columns to create a stacked column chart with Highcharts
I have a Student model for my Django app, like this: from django.db import models class Student(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) major = models.CharField(max_length=100) year = models.IntegerField() And I'm trying to create a stacked column chart, using Highcharts. So the output is like this: The idea is that I want to show the number of students that we have in each year, stacked with majors. This is all the data for this example, excluding the names: [{'major': 'Computer Science', 'year': 1394}, {'major': 'Electrical Engineering', 'year': 1394}, {'major': 'Computer Science', 'year': 1394}, {'major': 'Chemistry Engineering', 'year': 1395}, {'major': 'Computer Science', 'year': 1396}, {'major': 'Computer Science', 'year': 1394}, {'major': 'English Literature', 'year': 1395}, {'major': 'English Literature', 'year': 1394}, {'major': 'Computer Science', 'year': 1395}, {'major': 'Chemistry Engineering', 'year': 1397}, {'major': 'Art', 'year': 1397}, {'major': 'Electrical Engineering', 'year': 1398}, {'major': 'Electrical Engineering', 'year': 1399}, {'major': 'English Literature', 'year': 1399}, {'major': 'Computer Science', 'year': 1400}, {'major': 'Chemistry Engineering', 'year': 1397}, {'major': 'English Literature', 'year': 1397}, {'major': 'Physics', 'year': 1393}, {'major': 'Physics', 'year': 1393}, {'major': 'Chemistry Engineering', 'year': 1392}, {'major': 'Persian Literature', 'year': 1392}, {'major': 'Computer Science', 'year': 1392}] I grouped the two major and year columns, grouped = (Student.objects .values("major", "year") .annotate(count=Count("id")) .order_by("major", … - 
        
Bonjour comment changer une variable dans settings.Py à partir de l'interface admin de Django aci' de fournir les clefs D'api et de les changer merci [closed]
Bonjour, je voudrais savoir comment changer les variables dans settings.Py avec l'interface admin de Django. Exemple changer les clefs D'api à la volée sans avoir à passer par un éditeur de code/texte. J'ai une piste peut être en passant par un model... Et faire appel à ce model dans settings ... Qu'en pensez vous ? Merci - 
        
django automatic creation of the form from the model
is there a possibility from a model like: class foo(models.Model): a = models.CharField(max_length=64) b = models.ForeignKey(foo2, on_delete=models.CASCADE, blank=True, null=True) c = models.DateField(name='c', blank=True, null=True) d = models.EmailField(name='d') e = models.BooleanField(default=False, name='e') automatically generate a form like: where for all attributes (self-written) an attribute must be in the form. the name parameter could then be the label. class fooform(forms.ModelForm): a = models.CharField(name='a1', max_length=64) b = models.ForeignKey(foo2, name='b1', on_delete=models.CASCADE, blank=True, null=True) c = models.DateField(name='c1', blank=True, null=True) d = models.EmailField(name='d1') e = models.BooleanField(default=False, name='e1') class Meta: model = foo fields = ['a', 'b', 'c', 'd', 'e'] labels = { 'a': 'a1', 'b': 'b1', 'c': 'c1', 'd': 'd1', 'e': 'e1'} I found out that I can run through all attributes attributes = [i for i in dir(foo)] and that the wsgi.py is called with runserver. but I can't find a way to generate an attribute / field in the form for each attribute of the model. - 
        
I find problem in importing django in vscode
PS C:\Users\siruvani\projectsss\sshafeeq> workon try PS C:\Users\siruvani\projectsss\sshafeeq> python manage.py startapp calxx Traceback (most recent call last): File "manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main()`enter code here` File "manage.py", line 17, in main ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? - 
        
Django snackbar like message
What's the best way to have a custom tag with Django messages which disappears after a few seconds This is how I did it I know i am late, but i did it as follows views.py CRITICAL = 50 def my_view(request): messages.add_message(request, CRITICAL, 'A serious error occurred.') messages.html {% if message.level == 50 %} <div class="snackbar">{{message}}</div> </div> {% else %} {{ message }} CSS .snackbar { display: block; min-width: auto; margin-left: auto; background-color: #333; color: #fff; text-align: center; border-radius: 2px; padding: 16px; position: fixed; z-index: 1; left: 74%; bottom: 30px; -webkit-animation: cssAnimation 8s forwards; animation: cssAnimation 8s forwards; } @keyframes cssAnimation { 0% { opacity: 1; } 90% { opacity: 1; } 100% { opacity: 0; } } @-webkit-keyframes cssAnimation { 0% { opacity: 1; } 90% { opacity: 1; } 100% { opacity: 0; } } Tho this works, looking if there's any better way out there - 
        
ModelForm is not rendering on browser
I am creating a form for users to be able to create listings for an auction page however when I click the link from my index page to take me to the create page, i get redirected to the create page but on the browser, the form does not show. INDEX.HTML <p>You can create your first auction here <a href={% url 'create_listing' %}>Add new</a></p> URLS.PY path("create/", views.create_listing, name="create_listing") MODELS.PY from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): pass class Auction(models.Model): title = models.CharField(max_length=25) description = models.TextField() current_bid = models.IntegerField(null=False, blank=False) users_bid = models.IntegerField(null=False, blank=False) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title VIEWS.PY from django.shortcuts import render, redirect from django.template import context from .forms import AuctionForm from .models import User def create_listing(request): form = AuctionForm() if request.method == 'POST': form = AuctionForm(request.POST) if form.is_valid: form.save() return redirect('index') context = {'form': form} return render(request, 'auctions/create-listing.html', context) FORMS.PY from .models import Auction from django.forms import ModelForm class AuctionForm(ModelForm): class Meta: model = Auction fields = ['title', 'description', 'current_bid'] CREATE-LISTING.HTML {% extends "auctions/layout.html" %} {% block content %} <form action="" method="post" class="ui form"> {% csrf_token %} {{form.as_p}} <input type="submit" class="ui button primary teal" value="Submit"> </form> {% endblock %} - 
        
Trying to create an object in Django's database with React using User as foreign key (rest-framework)
I'm trying to register Club with owner (ForeignKey) and name fields via form in React. Everything works untill I submit the form. This gives me 401 Unauthorized error: const onSubmit = (event) => { event.preventDefault(); if (checkExistingClubNames(clubName, clubs)) { const owner = isAuthenticated().user; const name = clubName; createClub({owner, name}) .then((data) => { if (data.name === clubName) { setClubName(''); setNameTaken(false); navigate('/'); } }) .catch((error) => console.log(error)); } else { setNameTaken(true); } } clubName is a text variable from an input form (useState, ofc), checkExistingClubNames(clubName, clubs) just checks if a club with the same name exists, isAuthenticated().user returns currently logged user, nameTaken is just for displaying some text it does not matter in this case. The problem lies within createClub function, at least I think so: export const createClub = (club) => { return fetch('http://127.0.0.1:8000/api/clubs/', { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json", }, body: JSON.stringify(club), }) .then((response) => { return response.json(); }) .catch((error) => console.log(error)); }; On the backend part it's just serializer: class ClubSerializer(serializers.ModelSerializer): class Meta: model = Club fields = 'id', 'owner', 'name' And viewset: class ClubViewSet(viewsets.ModelViewSet): queryset = Club.objects.all() serializer_class = ClubSerializer So as I said it gives me 401 Unauthorized error, I use basically the same … - 
        
there is short api of loan calculator python code executed but the value of MonPayment is not showing on front end plzzz check the code below
this is the html file {% csrf_token %} Enter Years Enterest rate Enter Amount <button type='submit' class="btn btn-primary">calculate</button> <input type='text' value="{{MonPayment}}" class="form-control"> </form> my views.py is below def calculator(request): try: if request.method=='POST': year=eval(request.POST.get('year')) print(year) rate=eval(request.POST.get('rate')) print(rate) principal=eval(request.POST.get('Principal')) print(principal) year=year*12 rate=(rate/100)/12 MonPayment=(rate*principal*((1+rate)**year)-1) print(MonPayment) context={''} context={'rates' :'rate', 'years': 'year', 'Principal': 'principal'} except: MonPayment='invalid operation...' return render(request, 'calculator.html',context) - 
        
Custom lookup in Django (filter parameter different type than field type)
I have a simple model in Django. class Books(models.Model): title = models.CharField(max_length=255) page_size = models.IntegerField(null=True) An example instance of this model may look like this: ("Alice's Adventures in Wonderland", 70). I would like to create a lookup which would allow users to filter the books by page sizes in the following form if the user types (inside the filter box) >n Django filter would return only books which have more pages than n, if the user types <n Django filter would return only books with less pages than n. To sum up I would need a lookup __cmp which would be capable of joining the queryset before executing it. So I would like to have an if-else block implemented somewhere inside. filter_param, value = filter_param, filter_value = list(user_filter) if filter_param == ">": qr = Books.objects.filter(page_size__gt=n) else: qr = Books.objects.filter(page_size__lt=n) Is it possible to create a custom lookup which would implement such logic? - 
        
datetimefield only show time in html template
I have a datetime field but in the html code I would like to show only the time, how can I do? I tried {{ data|time }}, {{ value|time:"H:i" }} but nothing views from django.shortcuts import render from .models import Count import datetime # Create your views here. def contatore(request): settaggio = Count.objects.get(attivo = True) data = settaggio.data.strftime("%m %d, %Y %H:%M:%S") context = {'data':data} return render(request, 'count.html', context) models class Count(models.Model): data = models.DateTimeField() html <h5 style="color: #fff">{{ data }}</h5> - 
        
How to dockerize Django project already created in anaconda?
I have a Django application that is already created and running in anaconda, now I want it to be dockerized, can you please help me so that I can dockerize my Django project. - 
        
Custom TruncFunc in Django ORM
I have a Django model with the following structure: class BBPerformance(models.Model): marketcap_change = models.FloatField(verbose_name="marketcap change", null=True, blank=True) bb_change = models.FloatField(verbose_name="bestbuy change", null=True, blank=True) created_at = models.DateTimeField(verbose_name="created at", auto_now_add=True) updated_at = models.DateTimeField(verbose_name="updated at", auto_now=True) I would like to have an Avg aggregate function on objects for every 3 days. for example I write a queryset that do this aggregation for each day or with sth like TruncDay function. queryset = BBPerformance.objects.annotate(day=TruncDay('created_at')).values('day').annotate(marketcap_avg=Avg('marketcap_change'),bb_avg=Avg('bb_change') How can I have a queryset of the aggregated value objects for each 3-days interval with the index of the second day of that interval? - 
        
Want to upload an image using a custom upload image function python djano
This is my custom image upload function def upload_image(file, dir_name, filename): try: target_path = '/static/images/' + dir_name + '/' + filename path = storage.save(target_path, file) return storage.url(path) except Exception as e: print(e) and this is my model class MenuOptions(models.Model): name = models.CharField(max_length=500, null=False) description = models.CharField(max_length=500, null=True) image_url = models.ImageField(upload_to=upload_image()) def __str__(self): return f'{self.name}' I want to upload the image using my upload_image function, and as you can see it is taking 3 parameters file,dir_name, and the file_name. how can I pass these parameters in my model.ImageField() Also, I want to store the image_url to my database as returned by the upload_image function will it store the file in DB or the URL? - 
        
Heroku Django request.POST giving wrong values
I have deployed an app in heroku build using django.In my django views.py iam getting some value using request.POST and storing in a global variable so that i can access that value in another function which is then rendered into the template. Eveything worked fine on devolopment server but when i deployed it on heruko,request.POST is not retriving the correct value. views.py: serv='--' def home(request): global serv if request.method=='POST': dayCheck.clear() serv=request.POST['service'] return HttpResponseRedirect('func') def func(request): global serv #Doing something,does not involve serv return render(request,'index.html',{'service':serv}) When i try to log serv in home() it gives correct value but different value in func and the same is rendered,mostly it will be value which i previously clicked or sometimes it would be just -- as declared. Please help me! Thanks in Advance - 
        
mysql 8 gives error on creating table ( running migrate command in django )
Django3.2 mysql 5.7 I have a model name BlackboardLearnerAssessmentDataTransmissionAudit and its length is 48 characters and it has 1 not null field. On mysql5.7 it is working fine. But when try to upgrade with mysql8+ migrations throws error Identifier name is too long. This model generates following name in mysql8.5 blackboard_blackboardlearnerassessmentdatatransmissionaudit_chk_1 it has 65 characters. mysql8 limit info I have a question what are the possible solutions to fix this issue on mysql8 ? - 
        
dot line graph in django with mysql
Thanks in Advance...! Query: I want to display my graph in a card. The graph must look like enter image description here but i am unable to design this... as this graph must be dynamic with Django and mysql. my models.py file is: class JaAiPredictions(models.Model): project_management_id = models.IntegerField(blank=True, null=True) date = models.DateField(blank=True, null=True) ecommerce_users = models.FloatField(blank=True, null=True) total_revenue = models.FloatField(blank=True, null=True) conversion_rate = models.FloatField(blank=True, null=True) total_transactions = models.IntegerField(blank=True, null=True) avg_order_value = models.FloatField(blank=True, null=True) total_ads_clicks = models.IntegerField(blank=True, null=True) total_ads_cost = models.FloatField(blank=True, null=True) ads_cpc_value = models.FloatField(blank=True, null=True) mcf_conversion = models.FloatField(blank=True, null=True) mcf_conversion_value = models.FloatField(blank=True, null=True) mcf_assisted_conversion = models.FloatField(blank=True, null=True) mcf_assisted_value = models.FloatField(blank=True, null=True) social_facebook_clicks = models.IntegerField(blank=True, null=True) social_twitter_clicks = models.IntegerField(blank=True, null=True) social_pinterest_clicks = models.IntegerField(blank=True, null=True) social_instagram_clicks = models.IntegerField(blank=True, null=True) new_visitors = models.IntegerField(blank=True, null=True) returning_visitors = models.IntegerField(blank=True, null=True) total_users = models.IntegerField(blank=True, null=True) total_pageviews = models.IntegerField(blank=True, null=True) bounce_rate = models.FloatField(blank=True, null=True) total_sessions = models.IntegerField(blank=True, null=True) session_duration = models.IntegerField(blank=True, null=True) session_by_desktop = models.FloatField(blank=True, null=True) session_by_tablet = models.FloatField(blank=True, null=True) session_by_mobile = models.FloatField(blank=True, null=True) total_mobile_users = models.IntegerField(blank=True, null=True) total_desktop_users = models.IntegerField(blank=True, null=True) total_tablet_users = models.IntegerField(blank=True, null=True) total_paid_pageviews = models.IntegerField(blank=True, null=True) total_paid_users = models.IntegerField(blank=True, null=True) total_referral_pageviews = models.IntegerField(blank=True, null=True) total_referral_users = models.IntegerField(blank=True, null=True) total_organic_pageviews = models.IntegerField(blank=True, null=True) total_organic_users = models.IntegerField(blank=True, null=True) total_direct_pageviews = models.IntegerField(blank=True, null=True) total_direct_users = models.IntegerField(blank=True, … - 
        
How to assign value? [closed]
In my project I have A class of choices: class ServiceChoices(models.IntegerChoices): WASHING_OUTSIDE_WINDOWS = 1 HEATING = 2 I want to add the following choices: MAINTENANCE_HEAtING_INSTALLATION/AUTOMATIC_DOOR(24_HOUR_SERVICE) = 4 I am getting an error when I am using () and the / is there any way to do it. Thanks in advance! - 
        
Celery/django - chunk tasks
I have a lot of tasks that are being generated that I would like to group in to chunks, but I think in the opposite way as Celery does. From my understanding, I can use the chunks feature to split up a list of items when I create the task. I would like to do the opposite. The data I have is being produced one at a time from different endpoints. But I would like to process them in chunks so that I can insert them in to a database in single transactions. So essentially I'd like to add items to a queue 1 at a time, and dequeue them 100 at a time (either at some specified time interval or once the queue reaches a certain level) and use a transaction to insert all of them in to a database. This would save me from Is this possible with celery? Would it be easier to drop down to redis and create a custom queue there? - 
        
python - Django Operational Error, No such table
I am learning django and I really can't solve this error, I tried modifying every file but I can't find where the issue is. Error: OperationalError at /topics/ no such table: pizzas_topic I have to mention that this exercise is from Python Crash Course 2nd Edition Thanks Here is the code from my project: base.html: <p> <a href="{% url 'pizzas:index' %}">Pizzeria</a> - <a href="{% url 'pizzas:topics' %}">Pizzas</a> </p> {% block content %}{% endblock content %} index.html {% extends "pizzas/base.html"%} {% block content %} <p>Pizzeria</p> <p>Hi</p> {% endblock content%} topic.html {% extends 'pizzas/base.html' %} {% block content %} <p>Topic: {{topic}}</p> <p>Entries:</p> <ul> {% for entry in entries %} <li> <p>{{entry.date_added|date:'M d, Y H:i'}}</p> <p>{{entry.text|linebreaks}}</p> </li> {% empty %} <li>There are no entries for this topic yet.</li> {% endfor %} </ul> {% endblock content %} topics.html {% extends "pizzas/base.html" %} {% block content %} <p> Topics</p> <ul> {% for topic in topics %} <li> <a href="{% url 'pizzas:topic' topic.id %}">{{ topic }}</a> </li> {% empty %} <li>No topics have been addet yet.</li> {% endfor %} </ul> {% endblock content %} urls.py """Defines URL patterns for pizzeria.""" from django.urls import path from . import views app_name = 'pizzas' urlpatterns = [ # Home … - 
        
How to pass Serizalizer Fields to front-end Framework from RESTful API - DRF (Django)?
I want to use Svelte in the front-end and DRF (Django) in the back-end. This is what I have right now: #models.py class Student(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) # serializers.py class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = "__all__" But when I know want to create a form in the front-end (Svelte) I have to manually do that? Is there a way of requesting a json with all the required fields and the to build a form around it. Like first I request api.com/students/form wich returns a json: { "fields":[ "first_name", "last_name" ] } And then I could just iterate over the fields in "fields" and create <input> tags for the form acordingly. - 
        
Django: How to get parameters used in filter() from a QuerySet?
For the following QuerySet, qs = MyModel.objects.filter(attribute_one='value 1', attribute_two='value 2') How can I retrieve the parameters used in the filter (i.e. attribute_one and attribute_two) and the corresponding values (i.e. value 1 and value 2) from qs? Thank you! - 
        
API call interation store each response
I have a list of items that I pass into an API call for each item and return a response for each one. For each response, I extract the values I want. The list of items will grow over time. How do I collect the response of each call and reference that in the template? for item in tokens: data = cg.get_coin_by_id(item.token_slug) price = (data['market_data']['current_price']['usd']) symbol = (data['symbol']) day_change_percentage = (data['market_data']['price_change_percentage_24h']) logo = (data['image']['small']) I have been adding each value to the database so that I can reference the values using query set using tokens = profile.tokens.all() and then using {% for token in tokens%} ... , but I don't really need to be storing this long-term. Thanks - 
        
Python: SystemError: null argument to internal routine
After installation of python packages I am running into below error. It doesn't give any idea what is doing wrong. garg10may@DESKTOP-TVRLQTQ MINGW64 /e/coding/github/product-factory-composer/backend ((bf13ffe...)) $ python manage.py migrate Traceback (most recent call last): File "E:\coding\github\product-factory-composer\backend\manage.py", line 22, in <module> main() File "E:\coding\github\product-factory-composer\backend\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Python310\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Python310\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Python310\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python310\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Python310\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<e:\coding\github\product-factory-composer\backend\src\core-utils\src\core_utils\__init__.py>", line 3, in <module> File "<frozen core_utils>", line 6, in <module> SystemError: null argument to internal routine - 
        
how to display multiple videos in django
Here code is working fine but I want to display multiple videos. Here only displaying one video. when Uploading second video, second video file is storing but it is not displaying. Please help me out to solve this. Please. views.py: def showvideo(request): lastvideo= Video.objects.all() form= VideoForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() context= {'lastvideo': lastvideo, 'form': form } return render(request, 'master/video.html', context) forms.py: class VideoForm(forms.ModelForm): class Meta: model= Video fields= ["name", "videofile"] models.py: class Video(models.Model): name= models.CharField(max_length=500) videofile= models.FileField(upload_to='videos/', null=True, verbose_name="") def __str__(self): return self.name + ": " + str(self.videofile) video.html: <html> <head> <meta charset="UTF-8"> <title>Upload Videos</title> </head> <body> <h1>Video Uploader</h1> <form enctype="multipart/form-data" method="post" action=""> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Upload"/> </form> <br><br> <video width='400' controls> <source src='{{videofile.url}}' type='video/mp4'> Your browser does not support the video tag. </video> <br><br> </p> </body> <script>'undefined'=== typeof _trfq || (window._trfq = []);'undefined'=== typeof _trfd && (window._trfd=[]),_trfd.push({'tccl.baseHost':'secureserver.net'}),_trfd.push({'ap':'cpbh-mt'},{'server':'p3plmcpnl487010'},{'id':'8437534'}) // Monitoring performance to make your website faster. If you want to opt-out, please contact web hosting support.</script> <script src='https://img1.wsimg.com/tcc/tcc_l.combined.1.0.6.min.js'></script> </html> urls.py: path('videos/',views.showvideo,name='showvideo'), - 
        
Could not parse the remainder: '(audio_only=True)'
in my templates/videos.html, <div class="grid grid-cols-3 gap-2"> {% for vid in videos.streams.filter(audio_only=True) %} <a href="{{vid.url}}">{{vid.resolution}}</a> {% endfor %} </div> Error is, Could not parse the remainder: '(audio_only=True)' from 'videos.streams.filter(audio_only=True)' I can solve this when i pass all_videos = videos.streams.filter(audio_only=True) from my views.py as context, and in templates/videos.html i replace videos.streams.filter(audio_only=True) with all_videos, but I want to know that is there any other method to solve this