Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
How to use multiple templates in Generic ListView?
I have some ListViews implemented seperately with different template_names with similar model,How can i use implement them in one single List view that can take multiple templates? Views.py class ManagerOpenedTicketView(LoginRequiredMixin,TemplateView): template_name = 'app/pm_open_tickets.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['tickets'] = Ticket.objects.filter(status = 'Opened',created_by = self.request.user) return context class ManagerCompletedTicketView(LoginRequiredMixin,TemplateView): template_name = 'app/pm_completed_tickets.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['tickets'] = Ticket.objects.filter(status = 'Completed',created_by = self.request.user) return context class ManagerAcceptedTicketView(LoginRequiredMixin,TemplateView): template_name = 'app/pm_accepted_tickets.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['tickets'] = Ticket.objects.filter(status = 'Accepted',created_by = self.request.user) return context -
How to serve static files (like images) in a combined django-react application
This is the first web application I'm developing by combining django and react, in fact react is new to me. Please if my approach is wrong I'm open for correction. When developing with purely django, I find no difficulty with static and media files. I understand the elements involved are the media root and static root, respectively. In that case, all I need to do is to specify the static/media root in the settings.py in the django app as shown below: settings.py STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = '/media/images/' urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) \ + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) However, when I combine django and react the configuration changes since django is configured to look at index.html file in react, in which case an additional element called STATICFILES DIRS is added to the seetings.py file to specify the path to react index.html. In fact, my django app configuration looks like this when I combine django and react: settings.py STATICFILES_DIRS = [os.path.join(BASE_DIR, 'build/static')] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = '/media/images/' urls.py urlpatterns = [ ... re_path(r'^.*', TemplateView.as_view(template_name='index.html')) ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, … -
Data from database not showing Django
I am trying to get for people to upload their answers for for a specific assignment and trying to show them the instructions from the django database. But it is not working. Not sure why. Here's some of the code I have: html: <div class="main"> {% for a in assignment %} <div> <div><h1>{{a.title}} </h1><p>{{a.due_date}}</p></div> <div> <h2>{{a.instructions}}</h2> <h6 style="color: grey;">{{a.points}}</h6> </div> </div> {% endfor %} </div> views.py: from django.shortcuts import render from django.contrib.auth.decorators import login_required from ******.models import Assignment ..... @login_required def assignments_page(request): assignments = Assignment.objects.order_by('id') context = {'assignment': assignments} return render(request, 'samgau_page/assignments.html', context) models.py: from django.db import models # Create your models here. class Assignment(models.Model): groups = ( 'your choices' ) title = models.CharField(max_length=200) assignment_image = models.ImageField(null=True, blank=True, upload_to="images/") instructions = models.TextField(max_length=1000) due_date = models.DateTimeField(blank=True) points = models.IntegerField(default=100) group = models.CharField(max_length=10000, choices=groups) def __str__(self): return self.title And the picture below is the admin website -
How do I create a Django migration for my ManyToMany relation that includes an on-delete cascade?
I'm using PostGres 10, Python 3.9, and Django 3.2. I have set up this model with the accompanying many-to-many relationship ... class Account(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) ... crypto_currencies = models.ManyToManyField(CryptoCurrency) After generating and running Django migrations, the following table was created ... \d cbapp_account_crypto_currencies; Table "public.cbapp_account_crypto_currencies" Column | Type | Modifiers -------------------+---------+------------------------------------------------------------------------------ id | integer | not null default nextval('cbapp_account_crypto_currencies_id_seq'::regclass) account_id | uuid | not null cryptocurrency_id | uuid | not null Indexes: "cbapp_account_crypto_currencies_pkey" PRIMARY KEY, btree (id) "cbapp_account_crypto_cur_account_id_cryptocurrenc_38c41c43_uniq" UNIQUE CONSTRAINT, btree (account_id, cryptocurrency_id) "cbapp_account_crypto_currencies_account_id_611c9b45" btree (account_id) "cbapp_account_crypto_currencies_cryptocurrency_id_685fb811" btree (cryptocurrency_id) Foreign-key constraints: "cbapp_account_crypto_account_id_611c9b45_fk_cbapp_acc" FOREIGN KEY (account_id) REFERENCES cbapp_account(id) DEFERRABLE INITIALLY DEFERRED "cbapp_account_crypto_cryptocurrency_id_685fb811_fk_cbapp_cry" FOREIGN KEY (cryptocurrency_id) REFERENCES cbapp_cryptocurrency(id) DEFERRABLE INITIALLY DEFERRED How do I alter my field relation, or generate a migration, such that the cascade relationship is ON-DELETE CASCADE? That is, When I delete an account, I would like accompanying records in this table to also be deleted. -
Django acces <table> content POST
im creating an app where the user selects an Excel file and i create a dataframe out of that file. After that I add a checkbox to the dataframe and render the DataFrame to HTML Table. Now the user should be able to select individual rows and save the corresponding data into the database. This is my view: def mmuebersicht_view(request): if request.method == 'POST': context = {} form = request.POST.get('dropdown') stueckliste_data_file = '../prozessmapping/media/' + form df = read_file(stueckliste_data_file) df.insert(0,'A','<input type="checkbox">') context['result'] = df.to_html(index=False,escape=False) return render(request, 'web/mmuebersicht.html', { 'result': context['result'], }) I display the Table with the following: <form method="post" id="tableForm"> {% csrf_token %} {{ result|safe }} <button type="submit" form="tableForm" class="btn">MaterialMatrix Anlegen</button> </form> The output is shown in the following picture: Picture of HTMl table I want to achieve that the selected rows of the user are stored in the database. I have two Problems: How can i acces the Data of the table when i make a POST ? how can i filter the data and save only selected rows ? I tried to get the content of the Table via Name tag. But i have found out that the Name tag is not an allowed attribute of in HTML5. -
Why is this code throwing a syntax error?
I'm just learning Django and tried to execute this example in the shell from .models import model_name obj_or_queryset = model_name.obejcts.<method_name_from_the_table>() It fails with several syntax errors. File "", line 1 from .models import model_name obj_or_queryset = model_name.obejcts.<method_name_from_the_table>() ^ SyntaxError: invalid syntax -
Django database tables
i would like to get some help setting up my db tables relationships. My main issue is that I have a many to many relationships between trucks and locations and then I have a third model of sales were for each sale I need to add the location and the truck but I'm confused how to set all that up, thanks in advanced