Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to display querysets in Django?
I write a functiın and the final, function creates several model objects (same model different values). I listed these objects but I want to list just one time with the same dashboard_id value. I found something about that but I have an issue with displaying in the table. It is working but does not display the values. How can I solve it? views.py def reports_list(request): report_list = Reports.objects.values_list('dashboard_id', flat=True).distinct() context = { 'report_list': report_list, } return render(request, "report_list.html", context) report_list.html <table id="table_id" class="display"> <thead> <tr> <th>Kullanıcı</th> <th>Yüklenme Tarihi</th> <th>Görüntüle</th> </tr> </thead> <tbody> {% for report in report_list %} <tr> <td>{{ report.user.first_name }} {{ report.user.last_name }}</td> <td>{{ report.created_at }}</td> <td>view</td> </tr> {% endfor %} </tbody> </table> to be clear: -
Use GCC and java in Heroku dyno
I am trying to build a code compiler using Python Djano. The code works in my local machine as I use subprocess to compile and then run codes like python,java,c/c++. But when I upload it on Heroku which has a python build pack, it fails to run java and c/cpp codes because somehow it cannot access gcc and java [probably they are unavailable]. Hence how do I use java and cpp while retaining python too and run and execute the codes that are inputted from the front end. -
Django select_related() with latest() limit on related object
Consider having Table table and Reservation table in my restaurant Django APP. class Reservation(models.Model): table = models.ForeignKey( Table, on_delete=models.CASCADE, blank=False,null=False, related_name='reservations' ) def __str__(self): return str(self.pk) class Table(models.Model): def __str__(self): return str(self.pk) If I wanna to show a list of restaurant tables with it's corresponding reservation, then I need to select related reservation for each table. but I need to select related only the last reservation of each table (that is active right now). How To Achieve that? -
Django file upload with model form
there are tons of relevant posts: https://docs.djangoproject.com/en/3.2/topics/http/file-uploads/ Uploading A file in django with ModelForms https://github.com/axelpale/minimal-django-file-upload-example I am creating a simple app that allow user to upload css file: First, validate field field to make sure the file is css and the max size does not exceed 5MB. fields.py from django.db import models from django import forms from django.template.defaultfilters import filesizeformat def mb(n): return n * 1048576 class FileField(models.FileField): def __init__(self, *args, **kwargs): self.content_types = kwargs.pop('content_types', []) self.max_upload_size = kwargs.pop('max_upload_size', []) super().__init__(*args, **kwargs) def clean(self, *args, **kwargs): data = super().clean(*args, **kwargs) file = data.file try: content_type = file.content_type if content_type in self.content_types: if file.size > self.max_upload_size: raise forms.ValidationError('Please keep filesize under {}. Current filesize {}' .format(filesizeformat(self.max_upload_size), filesizeformat(file.size))) else: raise forms.ValidationError('File type rejected') except AttributeError: pass return data second, implement validation into model models.py # Create your models here. class Css(models.Model): file = FileField(upload_to='css', blank=True, null=True, content_types=['text/css'], max_upload_size=mb(5), ) third, create form for model creation forms.py class CssCreateForm(forms.ModelForm): class Meta: model = Css fields = ['file'] last, write a callable view views.py # Create your views here. def cssUploadView(request): if request.method == 'POST': print(request.POST['file']) print(type(request.POST['file'])) print(request.FILES) form = forms.CssCreateForm(request.POST, request.FILES) if form.is_valid(): print('---------') print(form.cleaned_data['file']) else: print('not valid') else: form = forms.CssCreateForm() return … -
How can I resolve fts5 error after I upgraded Wagtail
I have upgraded my Wagtail installation to 2.15.1 with Django 3.1.13 When I run manage.py migrate I get an error django.db.utils.OperationalError: no such module: fts5 I have searched but cannot find any solutions to this problem Can someone please help? -
|as_crispy_field got passed an invalid or inexistent field django?
views.py def VendorEdit(request, id=0): if request.method == "GET": vendor = CustomUser.objects.get(pk=id) print(vendor) form = VendorCreationForm(instance=vendor) vendordetails = VendorDetails.objects.filter(vendoruser_id=vendor.id) print(vendordetails) vendordetailform = VendorAdminDetailsForm(instance=vendordetails[0]) return render(request, 'vendor/edit.html', {'form':form, 'vendor':vendor, 'vendordetailform':vendordetailform}) else: vendor = CustomUser.objects.get(pk=id) form = VendorCreationForm(request.POST, instance=vendor) vendordetails = VendorDetails.objects.filter(vendoruser_id=vendor.id) vendordetailform = VendorAdminDetailsForm(request.POST, request.FILES, instance=vendordetails[0]) if form.is_valid() and vendordetailform.is_valid(): vendor=form.save() # vendordetailform.instance.vendoruser = vendor vendordetailform.save() # vendor.is_active = False # vendor.save() return redirect('login') edit.html <form method="POST" action="{% url 'vendor_edit' vendor.id %}" enctype='multipart/form-data'> {% csrf_token %} {{ vendorform.email|as_crispy_field}} {{ vendorform.first_name|as_crispy_field}} {{ vendorform.last_name|as_crispy_field}} {{ vendorform.mobile_number|as_crispy_field}} {{ vendorform.password1|as_crispy_field}} {{ vendorform.password2|as_crispy_field}} {{ vendordetailform.type_of_vendor|as_crispy_field}} {{ vendordetailform.aadhar_number|as_crispy_field}} {{ vendordetailform.aadhar_image|as_crispy_field}} {{ vendordetailform.pan_number|as_crispy_field}} {{ vendordetailform.pan_image|as_crispy_field}} {{ vendordetailform.store_name|as_crispy_field}} {{ vendordetailform.brand_name|as_crispy_field}} {{ vendordetailform.mail_id|as_crispy_field}} {{ vendordetailform.contact_no|as_crispy_field}} {{ vendordetailform.gst_number|as_crispy_field}} {{ vendordetailform.attach_gst_cert|as_crispy_field}} {{ vendordetailform.acct_number|as_crispy_field}} {{ vendordetailform.attach_passbook|as_crispy_field}} {{ vendordetailform.ifsc_code|as_crispy_field}} {{ vendordetailform.insta_account|as_crispy_field}} {{ vendordetailform.website|as_crispy_field}} {{ vendordetailform.street_name|as_crispy_field}} {{ vendordetailform.city|as_crispy_field}} {{ vendordetailform.pincode|as_crispy_field}} <button type="submit" class="btn btn-dark" value="Submit">Preview</button>&ensp; <a href="{% url 'login' %}">Already a Vendor?</a> </form><br> after the user signup, I allow them to preview and edit their details once they edit their details and preview, then click submit. It will redirect to login. The edit option is not working and after the preview submit not redirect to login the user. please need help. -
Django is using old views.py
So when running my project the homepage is good and the signup and in. However, some things don't work. I found errors where have things from old views.py. So I am thinking that Django is using a vies.py folder for other projects. views.py class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, SuccessMessageMixin, DeleteView): model = Posts success_message = 'Your post has been deleted' #it is not working and I dont know why success_url = reverse_lazy('homepage') template_name = 'posts/delete.html' def test_func(self): post = self.get_object() if self.request.user == post.user: return True return False urls.py from django.urls import path from django.conf import settings from django.conf.urls.static import static from .views import PostsListView, PostCreatView, PostDeleteView urlpatterns = [ path('', PostsListView.as_view(), name='homepage'), path('delete/<int:pk>/', PostDeleteView.as_view(), name='delete-post'), path('creat-post', PostCreatView.as_view(), name='create-post') ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) delete.html {% extends "posts/base.html" %} {% block content %} <form method="POST"> {% csrf_token %} <h2> Are you sure you want to delete your post?</h2> <button class="btn btn-outline-danger mt-1 mb-1 mr-1 ml-1" type="submit">Yes Delete</button> <a class="btn btn-outline-secondary mt-1 mb-1 mr-1 ml-1" href="{% url 'post-and-comments' object.id %}">Cancel</a> </div> </form> {% endblock %} list.html {% extends "posts/base.html" %} {% block content %} {% for post in posts %} <p class="font-weight-bold">{{post.user.username}}</p> {% if user == post.user %} <div> <a href="{% url 'delete-post' post.pk … -
ImportError: Couldn't import Django in running Docker image
I am so new in Docker and I have dockerized a simple django application and this is Dockerfile : FROM python:3.8-slim-buster ENV PYTHONUNBUFFERED 1 WORKDIR /app COPY . . RUN pip freeze > requirements.txt RUN pip3 install -r requirements.txt CMD ["python3","manage.py", "runserver","0.0.0.0:8000"] i have created image myapp 4 successfuly and when i tried to run this image with dcoker run myapp4 i got the following error : 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() File "manage.py", line 13, in main raise ImportError( 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? what am i missing here? -
Display all dates of November in a template
I'm trying to learn datetime and i'm currently trying to display all dates of November in an html template, in views i have: year = today.year month= today.month num_days = calendar.monthrange(year, month)[1] days = [datetime.date(year, month, day) for day in range(1, num_days+1)] for days in days: days_str = days.strftime('%A, %B, %d, %Y') print(days_str) context = {'': } return render(request, 'template.html', context) The output of the above is: Monday, November, 01, 2021 Tuesday, November, 02, 2021 Wednesday, November, 03, 2021 Thursday, November, 04, 2021 Friday, November, 05, 2021 Saturday, November, 06, 2021 Sunday, November, 07, 2021 Monday, November, 08, 2021 Tuesday, November, 09, 2021 Wednesday, November, 10, 2021 Thursday, November, 11, 2021 Friday, November, 12, 2021 Saturday, November, 13, 2021 Sunday, November, 14, 2021 Monday, November, 15, 2021 Tuesday, November, 16, 2021 Wednesday, November, 17, 2021 Thursday, November, 18, 2021 Friday, November, 19, 2021 Saturday, November, 20, 2021 Sunday, November, 21, 2021 Monday, November, 22, 2021 Tuesday, November, 23, 2021 Wednesday, November, 24, 2021 Thursday, November, 25, 2021 Friday, November, 26, 2021 Saturday, November, 27, 2021 Sunday, November, 28, 2021 Monday, November, 29, 2021 Tuesday, November, 30, 2021 How can i display above dates in a template? Thank you! -
"JSON parse error - Expecting property name enclosed in double quotes: line 1 column 2 (char 1)"
I am creating a project with Django Rest Framework and I ran into some problems and im not able to fix them. So, I have a URL for post method and when I post there using postman, I get an error: { "detail": "JSON parse error - Expecting property name enclosed in double quotes: line 1 column 2 (char 1)" } This is the data im sending: {username:"REQUAB", password:"REQUAB", emailId:"requab@gmail.com"} And just to check if i had some problem in the serializer or the model, i did a normal get request and i got correct output. my models.py: from django.db import models # Create your models here. class User(models.Model): emailId = models.EmailField(max_length=50) username = models.CharField(max_length=20) password = models.CharField(max_length=50) recipes = models.IntegerField(default=0) def __str__(self): return self.username my serializers.py: from rest_framework import serializers from .models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'emailId', 'password', 'recipes'] my urls.py: from django.urls import path from .views import UsersList, UsersDetail urlpatterns = [ path('', UsersList.as_view()), ] my views.py: from django.http import Http404 from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from users.models import User from .serializers import UserSerializer # Create your views here. class UsersList(APIView): def … -
Calculate Sub Table Django
I'm new on Django, I try to calculate sub table of related table. I have two models Transaction and Detail. here is my models: class Transaction(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) code = models.CharField(max_length=50) class Detail(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) transaction = models.ForeignKey(Transaction, related_name='details', on_delete=models.CASCADE) qty = models.DecimalField(max_digits=10, decimal_places=2, null=False, blank=False) price = models.DecimalField(max_digits=10, decimal_places=2, null=False, blank=False) I want to get sum of calculation (Detail.qty * Detail.price) on a single query like this: datas = Transaction.objects.all().annotate(sum=sum(qty*price)) How to do that on Django ORM? -
ckeditor toolbar not getting displayed in django-admin form
Guess I am doing something wrong here, but I have followed the most part from docs , little help here , Am i missing something , thanks in advance Admin.py class ArticleAdminForm(forms.ModelForm): article_text = RichTextField(blank=True) class Meta: model = Article fields = '__all__' class ArticleAdmin(admin.ModelAdmin): form = ArticleAdminForm autocomplete_fields = ('tags',) class TagsAdmin(admin.ModelAdmin): search_fields = ('name',) Settings.py CKEDITOR_UPLOAD_PATH = "ck_uploads/" CKEDITOR_IMAGE_BACKEND = "pillow" CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'Advanced', 'width': 758, 'height': 300, }, } Models.py class Article(models.Model): date_published = models.DateTimeField(auto_now_add=True) article_text = models.TextField() title = models.CharField(max_length=100,null=True,blank=True) topic = models.ForeignKey(Topic,on_delete=models.SET_NULL,null=True) tags = models.ManyToManyField(Tags) date_updated = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = 'Articles' def __str__(self): return "{} title {}".format(self.title,self.article_text[:4]) if self.title else " not topic for {}".format(self.article_text) -
Django Dynamically Calculate Average
I've multiple fields in my model, and I need to remove the average of only the columns user inputs Could be How can I do it dynamically? I know I can do mean = results.aggregate(Avg("student_score")) This is one, I want to add multiple Avg statements dynamically I tried making a loop as well to get all names and add all fields given by user one by one eg - Avg('students'), Avg('playtime'), Avg('grade'), Avg('sales') But I get QuerySet.aggregate() received non-expression(s): <class 'django.db.models.aggregates.Avg'>('students'), <class 'django.db.models.aggregates.Avg'>('sales'). I've even tried raw query, but it needs a unique ID because of which that isn't working Any workaround ideas? I am using MySQL DB -
hidden field changes value when saving form django
This is my model class Person(models.Model): name = models.CharField(max_length=100, blank=True, default='') is_ignore_validations = models.BooleanField(default=False) and this is my form class PersonForm(forms.ModelForm): class Meta: model = Person fields = ['name', 'is_ignore_validations', ] is_ignore_validations = forms.BooleanField(widget=forms.HiddenInput(), required=False) The usage for is_ignore_validations is in the clean_name() function def clean_name(): original_name = self.data.get('name') if not self.initial.get('is_ignore_validations'): pattern = re.compile('^[a-zA-Z]+$') if not pattern.match(original_name): raise ValidationError('name must consist only of letters') return original_name I initiate my form with request.POST, which doesn't have is_ignore_validations. I want it to stay how I've set it manually in the DB, but when I use form.save() it always changes to False. So firstly, how do I keep is_ignore_validations data in DB always the same? Secondly, is the usage in clean_name of the variable from initial best practice - self.initial.get('is_ignore_validations')? -
Having trouble updating python from 2.7 to 3.9 on MacBook
I'm a newbie to python and am having a really rough time trying to update the python version on my MacBook. I use a MacBook with macOS Monterey and with python installed over a year ago. When I type python --version in the terminal, the version printed out is v2.7. I'm trying to self-learn Django for web development, and need python version 3.9. I did a google search and found a site that gives a step by step tutorial on getting up and running with Django. As instructed on this site, I tried running "brew install python3" but I get the following message: "Error: homebrew-core is a shallow clone. To brew update, first run: ----and some info here---- What is confounding is that even though I get an error, the terminal then shows hundreds of errors before the process finally ends. Could someone provide guidance on how I (being a noob) can resolve this mess and update python to the latest version (3.9), so I can do an install of Django? -
How Django widget initiates from django form classs?
I am trying to add CKEditor to django form flields . I saw that there is a item that is widget . Whenever CKEditor is added as widget I saw that the field is assigned with a object of ckeditor . So what I did is I have written a decorator that modifies fields and adds widget's value is CKEditorWidget(). But when I am updating the widget its not reflecting on browser. My question is when the widget initiates ? do I need to do anything like call any function after updating the field.widget ? class CompanyForm(forms.ModelForm): # description = forms.CharField(widget=CKEditorWidget(), required=False) system_description = forms.CharField(widget=CKEditorWidget(), required=False) system_focus = forms.CharField(widget=CKEditorWidget(), required=False) class Meta: model = Company fields = ('description', 'system_description', 'system_focus') -
Static is not loading properly after cloning a Django project from git
Actually, I am hosting a project to a domain using a Linode server. The Project is on Bitbucket. I have tried all the methods static root static dirs and collect static but nothing works half of the CSS is loading but not left Static. STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR / 'static/')] #STATIC_ROOT = os.path.join(BASE_DIR, 'static/') -
How can I connect to the same github repository for heroku and Ditigitalocean?
Is it possible to do that connection??? I have a project which I want to run on heroku at the same time on Digitalocean. I tried it but heroku returns an error if I remove the Procfile, which Digitalocean does not require. DO works if I remove the Procfile but heroku errors, and vieversa. -
Django Admin unable to create custom view with get_urls
I am following the instructions in the following video here on creating a CSV upload on the admin site but have ran into an issue at about 13:50. I am trying to create a custom view but whenever I click on the link, instead of going to the new page it returns to the main admin page with the following error at the top. Crime with ID “upload-csv” doesn’t exist. Perhaps it was deleted? I'm pretty sure I've done the code the same as in the video, but here are a couple of code snippets in case I missed something. class CrimeAdmin(admin.ModelAdmin): def get_urls(self): urls = super().get_urls() new_urls = [path('upload-csv/', self.upload_csv),] return new_urls + urls def upload_csv(self, request): return render(request, "admin/csv_upload.html") And here is the HTML. {% extends 'admin/base.html' %} {% block content %} <div> hello world </div> {% endblock %} What exactly is causing the issue here? I can't figure out if I did something in the code wrong or there is something I was supposed to that wasn't in the video that I forgot? -
is there a way to show my Django code in github so people can try it?
I currently uploaded my first Django project to github and made a url thinking this will show my project on a github webpage just like it does for html and css but this wasn't the case it just shows the readme file instead. -
DRF Serializer logic to transform data
In a word of introduction - I'm using the react-table library and I want to display in it (if any) all PZItems and no Item or just Item (if there are no PZItems). I decided that it would be the best solution to display the data, as I couldn't otherwise design a serializer without duplicating the data anyway. React-Table doesn't like data in diffrent form, at least I failed trying to during the tests. I spent the last hours trying to flatten the serializ data which turned out to be a dead end. I was able to write code in JS that transforms serializerdata into the form I need. However, this is not the best solution... Below are simplified models and the rest of the code. How to write a serializer to match the given form? & How to display a table using a react-table with the current data. The second question is because I'm not sure my approach to the problem is right. However, executing some type of header in the middle of the list in the react-table for an Item that has a PZItem is beyond my abilities. Models class PZItem(models.Model): item = models.ForeignKey(Item, related_name='pz_items', verbose_name="Przedmiot", on_delete=models.CASCADE) quantity_available_to_order … -
How to solve the error when dummy data gets stored in Django database with its id as none and all values as null
I had made this form in Django which takes some data and when a save button is clicked it saves it to the database. It stores the data that I give, but I noticed that every time I refreshed the page that contained the form it would automatically save an object with the Id as none and all values set to null. I wanted to know how to write a function that says the form only submits to the database when the save submit button is clicked and not when reloading the page and making a dummy object in the database. -
How to set a derived attribute field of a django model in a JSON fixtures file?
The model would look something like this: class MyModel(models.Model): primary_key = models.CharField(blank=False, unique=True) created_at = models.DateTimeField(auto_now_add=True, blank=False) And in the fixtures file for unit tests: [ { "model": "app.model", "pk":1, "fields" : { "primary_key" : "Idetifier1", "created_at": {NO IDEA} } } ] Note that if left blank I get NOT NULL violations because it hasn't been set automatically as it would have when using .create() Perhaps this can't be done? Is this a bad use of django fixtures? Thanks! -
How to retrieve information from database to html template using built in usermodel django.contrib.auth
This is my html part where i want to retrieve it but it wont work -
Capture image with opencv and upload to django database
I can capture image using opencv in django app but don't know how to load it to database model. I am new to django. Thanks for help