Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to save file or remove older files when going back to the previous step in formwizard
Could you please share idea that how we can delete the older files in fileinput field created by the same session during form wizard. Because each time when we came back to the previous step, the uploaded file seems to disappear, and I need to upload again. Thanks. -
What is the difference between django and tkinter?
I have just starting learning to code in tkinter. However, I was also exposed to django. Both uses pythn programming language. Why do they have different style or documentation in terms of coding? Can someone explain in detailed on the whole process flow? -
How to interrupt a running websocket function with a button
Hello everyone, I am using Channels to implement websocket in my Django app. My goal for the app is to log datas comming from a RS323 link, print them so the user can see them and save them in a file. The program logging the datas works fine. Saving the datas in a file is also working. But i have a problem with the printing part. I use Channels to print the data in "real time" using websockets and I want the user to just : press the 'start log' button It starts logging the datas press the 'stop log' button It stops logging This is my consumer.py file : import json from channels.generic.websocket import WebsocketConsumer class CrioConsumer(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): print('disconnected') pass def receive(self, text_data): text_data_json = json.loads(text_data) fifo = text_data_json['message'] # this is the part where i log the datas but i cannot post it here because it is 600 lines long And this is my log.html file : {% extends "appliCrio/base.html" %} {% block content %} <hr> <form action="/appliCrio/log/" method="post"> {% csrf_token %} <p> {{ form }} </p> <input id="id_Start" type="submit" value="Démarrer enregistrement"> </form> <input id="start_log" type="button" value="Log"> <input id="stop_log" type="button" value="Stop Log"> <script> … -
Django how to save objects in a for loop
I want to save x MediaStreams for one Media Object. So I have a One-to-Many relation here (ForeignKey) but I'm not sure how I can this working as currently always the same stream gets saved and not 5 different ones as expected. Where do I need to place "i" to make this working for object creation within the for-loop? for i in clean_result['streams']: new_stream = MediaStreams.objects.create(index=index_value, stream_bitrate=streambitrate_value, codec_name=codec_name_value, codec_type=codec_type_value, width=width_value, height=height_value, channel_layout=channel_layout_value, language=language_value, media=new_object) new_stream.save() current error: TypeError: 'dict' object is not callable Thanks in advance -
How can I solve Recursion Error in django rest framework when using render_fields?
here are my codes. views.py class Contents(models.Model): name = models.CharField(max_length=100) formula = models.CharField(max_length=20) description = models.TextField(null=True, max_length=100) wiki = models.CharField(null=True, max_length=100) youtube = models.CharField(null=True, max_length=100) file = models.FileField() def __str__(self): return self.name models.py from django.db import models # Create your models here. class Contents(models.Model): name = models.CharField(max_length=100) formula = models.CharField(max_length=20) description = models.TextField(null=True, max_length=100) wiki = models.CharField(null=True, max_length=100) youtube = models.CharField(null=True, max_length=100) file = models.FileField() def __str__(self): return self.name serializers.py from rest_framework import serializers from .models import Contents class ContentsSerializer(serializers.ModelSerializer): class Meta: model = Contents fields = '__all__' admin.html <h4>Add Name <i>*</i></h4> <span> <div class="input_box"> {% render_field serializer.name template_pack='rest_framework/inline' %} </div> </span> following is the error message Traceback (most recent call last): File "C:\Users\gyuman\PycharmProjects\CharChokka_DB\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\gyuman\PycharmProjects\CharChokka_DB\venv\lib\site-packages\django\core\handlers\base.py", line 204, in _get_response response = response.render() File "C:\Users\gyuman\PycharmProjects\CharChokka_DB\venv\lib\site-packages\django\template\response.py", line 105, in render self.content = self.rendered_content File "C:\Users\gyuman\PycharmProjects\CharChokka_DB\venv\lib\site-packages\rest_framework\response.py", line 70, in rendered_content ret = renderer.render(self.data, accepted_media_type, context) File "C:\Users\gyuman\PycharmProjects\CharChokka_DB\venv\lib\site-packages\rest_framework\renderers.py", line 167, in render return template.render(context, request=request) File "C:\Users\gyuman\PycharmProjects\CharChokka_DB\venv\lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) File "C:\Users\gyuman\PycharmProjects\CharChokka_DB\venv\lib\site-packages\django\template\base.py", line 170, in render return self._render(context) File "C:\Users\gyuman\PycharmProjects\CharChokka_DB\venv\lib\site-packages\django\template\base.py", line 162, in _render return self.nodelist.render(context) File "C:\Users\gyuman\PycharmProjects\CharChokka_DB\venv\lib\site-packages\django\template\base.py", line 938, in render bit = node.render_annotated(context) File "C:\Users\gyuman\PycharmProjects\CharChokka_DB\venv\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) … -
Dropdown box foreign key in django to change into text box
i m making a submit form in that form there are 2 foreign keys which appears in select option (dropdown-box ) foreign keys contains 1000 of keys value which make my severs load high when there are many request from client side so I want something like text box where user can type there foreign keys yeah have used select2 but it is not efficient way because it preloads all the foreign keys Django community please suggest we some efficient ways of doing it -
How to get field name and value in django-reversion?
I am using Django-reversion to track the version. I want to get previous value as well as updated value in all models with a field name that has been updated. Here is the code I have tried so far: class ModelHistoryView(generic.ListView): """Creates the version history for a given model here. """ # model = None queryset = reversion.models.Version.objects.all() template_name = "backend/single_card.html" single_card.html {% extends current_module.base_template %} {% load i18n material_form material_frontend %} {% load static %} {% load my_tags %} {% block breadcrumbs_items %} <a href="{% url "backend:index" %}">{{ title|default:"Backend" }}</a> {# {% if object_list %}#} {# {% for object in object_list %}#} <a class="active">History</a> {# {% endfor %}#} {# {% endif %}#} {% endblock %} {% block content %} {% block left-panel %} <div class="left-panel"> {% block cards %} <div class="row"> <div class="col m12 s12"> {% for object in object_list %} <div class="card"> <div class="card-content"> <div class="card-title"> {% block card-title %}{% if object %}{{ object }}{% else %}{{ title }} {% endif %}{% endblock %}</div> <div>Revision: {{ object.revision.id }}</div> <div>Model: {{ object.content_type }}</div> <div>Instance Id: {{ object.object_id }}</div> <div>Changed by <strong style="text-transform: capitalize">{{ object.revision.user }}</strong> on <strong>{{ object.revision.date_created }}</strong></div> <div> <table> <tr> <th>Field</th> <th>Value Before</th> <th>Value After</th> </tr> <tr> … -
Custom icons for Django Oscar Dashboard
I have created set of icons that I would like to replace the font-awesome fonts currently used by Django Oscar. It is possible to add custom icons to the Django Oscar dashboard including the primary and children links in the header? How can I do it? Any suggestion to how can this can be done? -
Log out a user when the user log in's from another device django
How can i logout a user from a device if the user log in's from another device in django -
How to let the user add as many forms as they want to a ModelForm that saves to the same model in django
I have a form to let users make a new poll, it consists of 2 ModelForms one for the Question model and another for the Choice model Make new poll form i want there to be something like a (+) or (add another choice) button where users can add as many choices as they want and then submit it all. here's the models.py file models.py from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=False) questionText = models.CharField(max_length=150) datePublished = models.DateTimeField(auto_now_add=True) def str(self): return self.questionText class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choiceText = models.CharField(max_length=200) choiceVotes = models.IntegerField(default=0) def str(self): return self.choiceText forms.py from django import forms from .models import Question from .models import Choice class NewPollForm(forms.ModelForm): class Meta: model = Question labels = { "questionText":"Poll question" } fields = ("questionText",) class NewChoicesForm(forms.ModelForm): class Meta: model = Choice labels = { "choiceText":"Choice" } fields = ("choiceText",) the view for this form's page you can see it is set for only one choice field right now from .forms import NewPollForm from .forms import NewChoicesForm def newpoll(request): if request.user.is_authenticated == True : pass else: return redirect("users:signup") if request.method == "POST": qform = NewPollForm(request.POST) cform = … -
How to query items and orders them if one of params is in the list
I've got the list with users: following = [x.user for x in UserFollow.objects.filter(user=request.user)] Also the tweets: tweets = Tweet.objects.all() How can i sort the tweets to have tweets that are created by users in following at first places? -
React and Django Cannot post Image using react hooks and formData()
I am trying to upload image to my Django model, Can use same API from postman and upload image as expected, but when posting through react I get error and in colsole formdata is not able to create a object to send to API. Also, everything works fine if I remove picture append, imagefield can be null in my model. import React, { useState, useEffect } from "react"; import { FaExclamationCircle } from "react-icons/fa"; import { Button } from "../../globalStyles"; import { useForm } from "react-hook-form"; import { ErrorsSignUp, FormField, FormName } from "../Login/Login.element"; import { PopContainer, ModalWrapper, FromContainer, FormFieldImage, } from "./AddItem.element"; import axios from "axios"; const AddItem = ( callback, { showModal, seteShowModal }, requestType, articleID ) => { const [values, setValues] = useState({ title: "", price: "", category: "", quantity: "", }); const data = [ { title: "new comer", description: "This is coming from form ", completed: true, }, ]; const handleChange = (e) => { const { name, value } = e.target; setValues({ ...values, [name]: value, }); }; const handleSubmit = (e) => { const formData = new FormData(); formData.append("title", values.title); formData.append("category", values.category); formData.append("quantity", values.quantity); formData.append("price", values.price); formData.append("picture", values.picture); # It works if I comment … -
How can I add 'dynamic' (?) data to the Django admin panel
Full disclosure, I'm working on this project that I did not start. My knowledge of Django is fairly limited, so I apologize if I make a mistake in my wording or otherwise. In our DB our objects have a UUID that we generate upon creation. In our backend, we have code that converts the UUID into a base64 token and subsequent verification hash. We use these two pieces of data to generate unique URLs for our users. Obviously we don't want these pieces of data to be stored, as that would defeat the entire security purpose. However, we want to be able to see this data in the admin panel when looking at the specific object. So my question is, how can I load this data into the form without storing it permanently in the object? We want to add a generated URL at the bottom of the form, picture included for reference: image -
Django: How to return a field from a ForeignKey model through filter queryset. As it throws not JSON Serializable
I want to return a field from the Contet model which is a ForeignKey field of Saved model. I'm using filter queryset since it returns multiple values. But, the problem is I can't return the slug field from Content model by using content.slug after Saved.objects.filter(user=self.request.user)! Content model: class Content(models.Model): title = models.CharField(max_length=200, blank=False) slug = models.CharField(max_length=200, blank=False) ... My Saved model: class Saved(models.Model): content = models.ForeignKey('Content', on_delete=models.SET_NULL) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ... My view: class SavedList(viewsets.ModelViewset): serializer_class = SavedSerializer permission_classes = [permissions.IsAuthenticated] def get_queryset(self): return Saved.objects.filter(user=self.request.user) def list(self, request): savedList = [] for i in self.get_queryset(): dict = { 'slug': i.content.slug, # i want this 'content': i.content, 'user': i.user } savedList.append(dict) return Response(savedList) When I'm running this, it's returning Object of type 'Content' is not JSON Serializable! How do I get the slug from Content model? -
I want to use fields in an object to filter product
Here is my model: class PromotedProduct(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) start_date = models.DateField( verbose_name="When do you want your advert to start", null=True, blank=True) stop_date = models.DateField( verbose_name="When do you want your advert to end", null=True, blank=True) is_promotion_paid = models.BooleanField(default=False) is_active = models.BooleanField(default=False) created_at = models.DateTimeField( auto_now_add=True, editable=False, null=True) updated_at = models.DateTimeField(auto_now=True, editable=False, null=True) class Product(models.Model): merchant = models.ForeignKey( MerchantProfile, on_delete=models.SET_NULL, null=True) name = models.CharField(verbose_name="Product Title", max_length=255, null=True, blank=True) is_digital = models.BooleanField(default=False, null=True, blank=False) category = models.ForeignKey( ProductCategory, on_delete=models.RESTRICT, null=True, blank=True) image = models.ImageField(null=True, blank=True, upload_to='products') product_video_provider = models.CharField( max_length=60, null=True, blank=True) product_video = models.CharField(max_length=60, null=True, blank=True) brand = models.CharField(max_length=200, null=True, blank=True) description = models.TextField(null=True, blank=True) class ProductCategory(models.Model): name = models.CharField(max_length=200, null=True) image = models.ImageField(null=True, blank=True, default="category/blank.jpg", upload_to='category') icon = models.ImageField(null=True, blank=True, default="category/icon.jpg", upload_to='category') added_by = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True, null=True, blank=True) slug = models.SlugField(null=True, unique=True, default=None) I want to filter our promoted products under a category, say we have the category "computers" and a promoted product "Laptop" which has the category "computers". i want to filter my PromotedProduct table with products under the category 'computers', i tried this but got an error, any help will be appreciated: def promoted_products(request) cat = ProductCategory.objects.get(slug='computers') promoted = PromotedProduct.objects.filter(product.category=cat … -
I am getting an error in when i am trying to execute django models migrate command - python manage.py migrate . How to solve this error?
from django.db import models from django.contrib.auth.models import User class Student(models.Model): rollno = models.CharField(max_length=13) name = models.OneToOneField(User, on_delete=models.CASCADE) dept = models.CharField(max_length=30) def __str__(self): return str(self.name) class Subject(models.Model): subname = models.CharField(max_length=50) deptname = models.CharField(max_length=50) def __str__(self): return str(self.subname) PS C:\Users\Akhil\Desktop\django\studentportal> python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, studentapp Running migrations: Applying studentapp.0003_auto_20210602_0944...Traceback (most recent call last): File "C:\Users\Akhil\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\fields_init_.py", line 1823, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: 'CSE' I tried to delete a model which I have created. After deleting whenever I try to migrate the model, I am getting this error. So I added the same model Subject again -
Errors When I try to migrate in django python
I was following This Tutorial https://www.youtube.com/watch?v=_uQrJ0TkZlc&t=19075s I am not able to migrate models to intial.py this is the Intial enter image description here apps enter image description here models enter image description here settings enter image description here Squlite enter image description here When I run make migrations enter image description here when I run migrate enter image description here I can't migrate all of the models to the intial.py I'm a begginer . I'm trying to figure out in th last few days , But I can't .Anyone please help -
Django form - how to use django on HTML with radio button options with image tag
I have a following HTML script that does what I want to achieve, obviously with CSS and JS. <form id="wrapped" method="POST"> <div class="container"> <div class="row"> <div class="col"> <div class="item"> <input id="id_1" name="group1" type="radio" class="required"> <label for="id_1"><img src="{% static 'website/images/Car.svg' %}" alt=""><strong>Motor vehicle</strong></label> </div> </div> <div class="col"> <div class="item"> <input id="id_2" name="group1" type="radio" class="required"> <label for="id_2"><img src="{% static 'website/images/Motorcycle.svg' %}" alt=""><strong>Motorcycle</strong></label> </div> </div> This is what I want to achieve (radio select with an image inside a box):outcome - Target and I am tring to use Django to achieve the same result and here is what I have so far: Model.py class Asset_Category(models.Model): ASSET_TYPE = ( ('Car','Car'), ('Van','Van'), ('Plane','Plane') ) asset = models.CharField(max_length=20,choices=ASSET_TYPE,null=True) forms.py from django import forms from .models import Asset_Category from django.utils.safestring import mark_safe from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Fieldset, ButtonHolder, Submit class Asset_Form(forms.ModelForm): class Meta: model = Asset_Category fields = ['asset'] class Asset_Form_Form(forms.Form): asset = forms.ChoiceField(choices=ASSET_TYPE, initial=0, widget=forms.RadioSelect(attrs={'class':'form-check-inline'})) HTML - with django code <div class="container"> <div class="row"> <div class="col"> <div class="item"> {{ form.asset.0 }} <label for="{{ form.asset.id_for_label }}"><img src="{% static 'website/images/Car.svg' %}" alt=""></label> <strong>Car</strong> </div> </div> <div class="col"> <div class="item"> {{ form.asset.1 }} <label for="{{ form.asset.id_for_label }}"><img src="{% static 'website/images/Van.svg' %}" alt=""><strong>Van</strong></label> </div> </div> </div> … -
How to change default numpy error handling
The default numpy error handling is: import numpy as np np.geterr() # {'divide': 'warn', 'over': 'warn', 'under': 'ignore', 'invalid': 'warn'} I know that I can change the error handling with: np.seterr(divide='raise', over='raise', under='ignore', invalid='raise') In my Django project, I have a lot of files that are importing numpy. Is there a way to change the default numpy error handling somehow, or do I really have to call np.seterr in each and every file? -
DoesNotExist at /admin/
DoesNotExist at /admin/ URL matching query does not exist. I copy code form old study-project and i haven't similar problem in old project. settings.py INSTALLED_APPS: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'cutter', ] admin.py: from .models import URL from django.contrib import admin admin.site.register(URL) urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('cutter.urls')), path('admin/', admin.site.urls), ] All another functions work. -
Loading data in django project to new postgres database taking very long
In my django project I am trying to migrate my database from sqlite to postgres. I've made a dump file of the database, changed my settings file to reflect the new database and now I want to upload this data to postgres. So initially I was running the following in the terminal: python manage.py loaddata data.json But this took very long - it was still running for more than a day, with no errors, and I eventually I stopped it. So then I found this answer on SO, and therefore I created a load_data.py file, like so: import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") import django django.setup() from django.core.management import call_command from django.db import transaction DJANGO_SETTINGS_MODULE='mysite.settings' with transaction.atomic(): call_command('loaddata', 'data.json') And then run it via python load_data.py. But it still takes incredibly long and the data has not loaded. My data file is 20.8MB. Is there anything that I can do to speed things up? For reference, the model that has the most data looks like this: class WordManager(models.Manager): def search(self, query=None): qs = self.get_queryset() if query is not None: or_lookup = (Q(target_word__icontains=query) | Q(source_word__icontains=query)| Q(example_sentence__icontains=query) ) qs = qs.filter(or_lookup).distinct() # distinct() is often necessary with Q lookups return qs class Word(models.Model): objects … -
How to create a .exe file of the Django project?
Can someone tell me how to How to create a .exe file of the Django project? I build my project using Django, AJAX and Jquery now I want to make a windows desktop app. Can someone help me? I tried pyinstaller, exe file was generated but it was just opening a cmd prompt and closing it automatically. -
Django class based View with 2 post forms returns valid unknown
I've got a view in django where post method has 2 different types of form: def post(self, request): tweet_form = TweetForm(request.POST, request.FILES) comment_form = TweetCommentForm(request.POST) print(request.POST['form-button']) if request.POST['form-button'] == 'add_tweet': print(tweet_form.is_valid) if tweet_form.is_valid(): content = tweet_form.cleaned_data['content'] image = tweet_form.cleaned_data['image'] tweet = Tweet.objects.create( user=request.user, content=content, ) if image != None: tweet.image = image tweet.save() return redirect("/home") if request.POST['form-button'] == 'add_comment': print(comment_form.is_valid) if comment_form.is_valid(): content = comment_form.cleaned_data['body'] return redirect("/home") ctx = {"tweet_form": tweet_form, "comment_form": comment_form} return render(request, "home.html", ctx) The both forms have different name, value, and id. When i print (tweet_form.is_valid()) or (comment_form.is_valid()) i receive sth like: <bound method BaseForm.is_valid of <TweetForm bound=True, valid=Unknown, fields=(content;image)>> Respectively for both forms. Can i somehow reorganize view to deal with both of forms or i have to have another View? Regards -
django join filtered realted model
I have three related model and want Aggregated filtered result models: class Symbol(models.Model): name = models.CharField(max_length=50) status = models.SmallIntegerField(choices=Status.types, default=Status.enable) class SymbolDailyInfo(models.Model): symbol = models.ForeignKey('Symbol', null=True, on_delete=models.PROTECT) monthly_vol_avg = models.BigIntegerField() ct = jmodels.jDateTimeField(auto_now_add=True) class MarketSnapshot(models.Model): symbol = models.ForeignKey('Symbol', null=True, on_delete=models.PROTECT) ct = jmodels.jDateTimeField(auto_now_add=True) tvol = models.BigIntegerField(null=True, blank=True) I would like to get symbols which its last tvol is 3 more time its last monthly_vol_avg I write this filter the problem is how to filter latest SymbolDailyInfo and MarketSnapshot objects? qs = Symbol.objects.prefetch_related('marketsnapshot_set', 'symboldailyinfo_set')\ .filter(status=Status.enable, marketsnapshot__tvol__gte= 3 *F('symboldailyinfo__monthly_vol_avg'))\ .values_list('i18', 'marketsnapshot__tvol', 'symboldailyinfo__monthly_vol_avg') qs = qs.extra(select={'trade_vol_grth_rate': "marketsnapshot__tvol / symboldailyinfo__monthly_vol_avg"}) qs = qs.extra(order_by=['trade_vol_grth_rate']) -
django how to use Choices for a Model DecimalField
i need to have a field to store values in range of (-20 to 20 with step 0.25) and the values should be displayed like (1.50, 3.00, 5.25), so i thought i should use decimal instead of float an after some searching i have used this function to generate the required range : def decimal_range(A, B, X): """ function to generate decimal floating numbers from start(A), to end(B), by step(X) """ getcontext().prec = 5 while A < B: yield float(A) A += Decimal(X) and generated the filed choices like so. S_CHOICES = tuple(tuple([i, f"{i:.2f}"]) for i in decimal_range(-20, 20.25, 0.25)) the result tuple is ((-20.0, '-20.00'), (-19.75, '-19.75'), (-19.5, '-19.50'), (-19.25, '-19.25'), (-19.0, '-19.00'), ...) the model field is arrs = models.DecimalField(max_digits=4, decimal_places=2, choices=S_CHOICES, null=True, blank=True, default=None) and when looking inside the db.sqlite3 file i see some different values like (-20 instead of -20.0). also when checking from python shell for field value it is like Decimal('15.00'), Decimal('4.50') in the end if i submitted a form with this field to value like 7.50 or 7.00 it is saved and retrieved correctly, but when trying to update this form the field value is going to be empty but if the value …