Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Obtain absolute path on image ckeditor + django + react
Django There are 2 question about this topic, but both of them (this is one Absolute paths on images uploaded by django-ckeditor) are not updated. For example, in Django 4.X, url was removed. Despite this, I've tried these solutions, but no one worked for me. I've also tried to use: CKEDITOR_MEDIA_PREFIX on my settings.py But it didn't work either. So here is my question, how can I set up my Django-rest-framework app in such way that I get the absolute path when I render the html on my next.js site? This is what I get right now: <img alt=\"\" src=\"/media/uploads/2022/01/19/video.svg\"/> This is what I'd like to get: <img alt=\"\" src=\"http://website.com/media/uploads/2022/01/19/video.svg\" React Is there any way to achieve these from the frontend? For example, updating all img's src -
Why do I get model DoesNotExist but server is able to display it?
I don't understand the Traceback of the error, but Server is running fine (0 problems), and I get all the data I needed from the view.py. Seems it has to be with the get() method... DoesNotExist: matching query does not exist This are the models I used. from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): id = models.AutoField(primary_key=True) name = models.CharField(max_length=64, blank=True) image = models.ImageField(upload_to="portraits", blank=True, default="default.jpg") def __str__(self): return f"{self.username}" class Category(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=64) description = models.CharField(max_length=255, blank=True) def __str__(self): return f"{self.name}" class Item(models.Model): id = models.AutoField(primary_key=True) owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="inventory") name = models.CharField(max_length=64) description = models.CharField(max_length=255) image = models.ImageField(blank=True, default="Megamind.jpg") starting_bid = models.PositiveIntegerField(default=0) category = models.ForeignKey(Category, on_delete=models.CASCADE, default="1", related_name="stuff") active = models.BooleanField(default=True) favorited = models.ManyToManyField(User, blank=True, related_name="favorites") def __str__(self): return f"{self.name} of {self.owner}" and the related view.py file def index(request): auctions = Item.objects.filter(active=True) context = {'auctions':auctions, 'title':'Active Listings'} return render(request, "auctions/index.html", context) def category_view(request, category): category = category.capitalize() category_obj = Category.objects.get(name=category) category_id = category_obj.id items = Item.objects.filter(category=category_id, active=True) context = {'auctions':items, 'title':category} return render(request, "auctions/index.html", context) If it helps: I'm passing from urls.py to view as str path("<str:category>", views.category_view, name="category") -
How to render Django context data (JSON) within external JavaScript file?
The question I have is: How do I get template-ed JSON data to be usable by .js file to see and use JSON data from my Django context? The problem I am trying to solve is: I am working on adding a CSP (Content Security Policy) to my Django website. The catch is that I have some inline JavaScript when templating JSON variables. This wouldn't be a problem, but the templating is inside the JavaScript section of the .html file. Thus, in order to abide by a strict CSP, I need to move the entire JavaScript portion out of the .html file and into a .js file. The code I need to move looks like this: <script> let data = [ { "key" : "Last 10 Days", "values" : {{ last_ten_days }}, }, { "key" : "Daily Score", "bar": true, "values" : {{ daily_scores }}, } ].map(function(series) { series.values = series.values.map(function(d) { return {x: d[0], y: d[1] } }); return series; }); </script> I am passing the values via a Django TemplateView to the context so I can render the data to plot, using NVD3.js, on my webpage. It looks something like this: class TheScores(LoginRequiredMixin, TemplateView): template_name = 'the_scores.html' def … -
Url not parsed when testing a ModelViewSet
I am trying to test a Django Rest Framework view. When I call my endpoint from a real api client, pk is correctly set. When it is called from the test, pk is None. class ResourceViewSet(ModelViewSet): serializer_class = ResourceSerializer @action(detail=True) def foo(self, request, pk=None): print(pk) # None when called by the test def test_foo(client: Client, db): request = factory.post(f'/api/resource/1/foo/') view = ResourceViewSet.as_view({'post': 'foo'}) response = view(request) How can I do to fix my test? -
Django url path is duplicated
I am getting a duplicate url pattern from newly added app : http://127.0.0.1:8000/quote/quote/new/ base app urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('register/', user_views.register, name='register'), path('profile/', user_views.profile, name='profile'), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), path('', include('post.urls')), path('quote/', include('quote.urls')), ] New app urls.py: urlpatterns = [ path('quote/new/', QuoteCreateView.as_view(), name='quote-create'), ] I have tried: path('', include('quote.urls')), in base urls.py but get the same problem. -
Count booleans inside a for-loop in a django template
I would like to know how to count all the true/false booleans inside a for-loop in my django template, but im not sure how to achieve this inside the loop. My goal is to show the user how many questions are unsolved/solved. lets say these are my models: class Category(models.Model): name = models.CharField(max_length=50) class Question(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField(max_length=50) description = models.TextField(max_length=250) solved = models.BooleanField(default=False) ListView: class CategoryView(ListView): model = Category context_object_name = 'categories' Template: {% for category in categories %} {{ category.name }} # I would like to show: 5/10 questions solved {% for question in category.question_set.all %} {{ question.name }} {{ question.title }} {{ question.description }} {{ question.solved }} {% endfor %} {% endfor %} Usually i print the total number of objects with .count like: {{ cagetories.count }} But i cant do this inside the loop because it returns: 1 1 1 1 1 1: {% for question in category.question_set.all %} {% if not question.solved %} {{ question.count }} ## returns 1 1 1 1 1 1 {% endif %} {% endfor %} Same thing with the {{ forloop.counter }} it returns multiple numbers because of the loop, but i only need that last … -
Django: foreign key (many-to-many) return empty queryset despite not being empty
My Model: class Account(models.Model): """ An account is for a team of users, or a single customer """ name = models.CharField(max_length=100, unique=True) admins = models.ManyToManyField('AccountUser', related_name='+', blank=True) metadata = models.JSONField(default=dict, blank=True) def __str__(self): return self.name @property def customers(self): """Accounts linked to this account""" return self.linked_accounts.linked_accounts.all() and my code: >>>account = Account.objects.get(id=1) >>> print(account) Bramble CFD >>> print(account.name) Bramble CFD when I try to get the admins many_to_many field I get the following empty queryset: >>> print(account.admins.all()) <QuerySet []> but the admins field is not empty as demonstrate by the following screen shot -
How to make dropdownlist of currency codes using django model
I need to make dropdownlist of all countries iso-4217 currencycodes like below, AFN-Afghani EUR-Euro USD-Dollar ... I have tried lot I don't get what I want. I just want to make it like CountryField() from django-countries.I have tried django-internation there i have got confused with how to implement that. If there is any possible to implement this one do reply.. Any help Appreciable.. -
Updating a django project from local to server
I want to have my local work in production so I pushed to gitlab what I had done locally and I pull to the django project on the server but when I do a python3 manage.py makemigrations then python3 manage.py migrate , that I restart nginx and that I go on my url of my api of the server I have an error message on what I have pull. I also had this error message locally but by doing a makemigrations followed by a migrate it was fixed there no... Error message on API: -
Django render function takes forever to load
I have a function definition in the views.py file of my Django app as follows: def dashboard_page(request, date_range=None): ''' This is the function ''' template = 'accounts/dashboard.html' dashboard_data_url = reverse('dashboard_data') return render(request, template, {'dashboard_data_url': dashboard_data_url}) The Templates configuration on the settings.py file is as follows: DEBUG = False TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates/'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages' ], }, }, ] I tried to debug the issue using the pdb and got the following error as shown in the screenshot. I tried to add print statements before the render function, that works fine. But the render function takes forever and returns no response. -
Currently file-upload is not present in ModelAdmin change page
I have a model ProductImages(models.Model) with a fk to Product(models.Model). In /admin/<app>/product/<id>/change/, all fields of Product(models.Model), even other models with fk to Product, show a data stored on db to edit, only ProductImages(models.Model) not display currently p.file-upload, like: That is other model(User model) with a expected bahavoir work. But in ProductImages(models.Model) part of Product(models.Model), this data is not present, i check the html maybe for css mistakes but not. Im not use a custom View, use admin.urls with custom site.admin. The code: models.py class Product(models.Model): ...#some fields def __str__(self): return self.slug or '' def get_absolute_url(self): return reverse('product_change', kwargs={'slug': self.slug, 'pk': self.pk}) def save(self, *args, **kwargs): self.product_title_seo = self.fn_product_title_seo self.product_title = self.product_title.capitalize() if not self.slug: self.slug = slugify(self.product_title_seo) return super().save(*args, **kwargs) class ProductImages(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) image_file_w200_png = models.ImageField( verbose_name = "Imagens", upload_to=upload_to_image_file_w200_png, null=True, blank=True, default='magickhat-profile.jpg' ) ... admin.py class AdminProductImages(admin.TabularInline): model = ProductImages form = ProductImagesForm extra = 10 max_num = 10 list_display = ('image_file_w200_png',) fieldsets = ( (None, {'fields': ('image_file_w200_png',)}), ) add_fieldsets = ( (None, { 'fields': ( 'image_file_w200_png'), }), ) class Media: js = ('users/js/img_product_upload.js',) class AdminProductModel(admin.ModelAdmin): inlines = [AdminProductImages,AdminProductFeatures] model = Product def product_thumb(self, obj): # return HTML link that will not be escaped return mark_safe( … -
The view form.views.form_view didn't return an HttpResponse object. It returned None instead
I try to learn about form validation and this ValueError appears , here is my views.py and forms.py file forms.py : from django import forms from django.core import validators class SignUp(forms.Form): user = forms.CharField(label='User Name', max_length=100) email = forms.EmailField(label='Email', max_length=100) password = forms.CharField(widget=forms.PasswordInput, label='PassWord') botcatcher = forms.CharField(required=False, widget=forms.HiddenInput, validators=[validators.MaxLengthValidator(0)]) views.py from django.shortcuts import render from django.http import HttpResponseRedirect from .forms import SignUp # Create your views here. # 127.0.0.1/ def index(request): return render(request, 'home/index.html') # 127.0.0.1/form def form_view(request): if request.method == ('POST'): form = SignUp(request.POST) if form.is_valid(): return HttpResponseRedirect('/') else: form = SignUp() return render(request, 'form.html', {'signupForm' : form}) -
How to stop save -data if the data is saved within today for a user
class RequestPop(models.Model): request_pop = models.PositiveIntegerField(default=0) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE,unique=False,null=True) created_at = models.DateTimeField(auto_now_add=True) available_pop = models.PositiveIntegerField(default=0) def __str__(self): return "{}-{}".format(self.user,self.request_pop) def save(self, *args, **kwargs): if self.user: old_obj = RequestPop.objects.filter(user=self.user).filter(created_at = datetime.today).last() if not old_obj: super(RequestPop, self).save(*args, **kwargs) But my code is not working. How to stop save data if data already saved within today. -
Error in models folder "doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS"
I can't find a solution for the following error: RuntimeError: Model class users.models.User.User doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. The INSTALLED_APPS: LOCAL_APPS = [ "api.users", "api.achievements", "api.others", ] # https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS Models folder users/models/__init__.py: from .User import * # noqa from .Profile import * # noqa users/models/User.py: """ User related models """ from django.contrib.auth.models import AbstractUser from django.db import models from django.urls import reverse from django_countries.fields import CountryField from api.others.constants import GENDER class User(AbstractUser): """ Default custom user model for Dezumi API. If adding fields that need to be filled at user signup, check forms.SignupForm and forms.SocialSignupForms accordingly. """ birth_date = models.DateField(null=True, blank=True) country = CountryField(null=True, blank=True, blank_label='Select country') gender = models.CharField(choices=GENDER, max_length=6, null=True, blank=True) is_verified = models.BooleanField( default=False, ) def get_absolute_url(self): """Get url for user's detail view. Returns: str: URL for user detail. """ return reverse("users:detail", kwargs={"username": self.username}) The app is on installed_apps, so what could it be? Something with the init.py? -
"Incomplete response received from application" when i reload url
i am new to hosting a Django application on a shared hosting using cpanel. am running a django==2.1 version. after all it requirres to setup and host the appication , when i reload the url, it gives me the above error. this is the error log. cpanel error log this is the error from terminal when i run manage.py runserver terminal error log can some one pliz help figure out the problem thanks. -
If else statement in django template based on request.session data
I'm trying to prevent/allow the user from clicking a button depending on whether a key is present in the request.session data. It works for blocking it, but once the key is added to the session, that isn't reflected on the webpage/template and the key remains blocked. I presume I'll have to do this in JS but I'm not sure how to approach it. Any ideas? Thanks {% if choices not in request.session %} <form class="submit-form" action="{% url 'search' %}" method="post" onsubmit="return false;"> {% csrf_token %} <input type="submit" class="show-more-button cunt" style="margin-left: 5px" name="mybtn" value="Search" data-bs-toggle="popover" data-bs-placement="right" data-bs-trigger="focus" data-bs-content="Please select one or more ingredient"> </form> {% else %} <form action="{% url 'search' %}" method="post"> {% csrf_token %} <input type="submit" class="show-more-button" style="margin-left: 5px" name="mybtn" value="Search"> </form> {% endif %} if request.POST.get('button_color') == 'green': selected_ingredients = request.session.get('choices', []) selected_ingredients.insert(len(selected_ingredients), ingredients_name) request.session['choices'] = selected_ingredients request.session.modified = True -
i have some issue when creating django project. i cannot create new project whenever i ran cmd i get error saying
C:\Users\Dnyane\Documents\file_1>django-admin startproject a CommandError: [WinError 2] The system cannot find the file specified:'C:\Users\Dnyane\Documents\file_1\a' -
Prepopulate Django ModelForm With all records
I am trying to prepopulate my form with all records but i am receiving error 'QuerySet' object has no attribute '_meta' , I tried just passing my queryset through initial while i get no error the fields in my template aren't rendering initial={runninghours} my views.py: def runninghours(request): runninghours = RunningHours.objects.all() form = RunningHoursModelForm() form_populated = RunningHoursModelForm(initial={runninghours}) if request.method == 'POST' and 'form-create' in request.POST: form = RunningHoursModelForm(request.POST) if form.is_valid(): form.save() return redirect(request.path_info) context = {"form": form, "rhs": form_populated} return render(request, 'runninghours.html', context) The template: <form method="POST" action=""> {% csrf_token %} <td>{% render_field rhs.name %}</td> <td>{% render_field rhs.current_runninghours %}</td> <td>{% render_field rhs.last_runninghours %}</td> <td>{% render_field rhs.last_modified %}</td> <td> <input type="hidden" name="update_runninghours_id" value="{{ rhs.pk }}" /> <input name="form-delete" type="submit" class="button1" value='Update Runninghours' /></td> </form> the models.py: class RunningHours(models.Model): name = models.CharField(max_length=100) current_runninghours = models.IntegerField(blank=True,null=True) last_runninghours = models.IntegerField(blank=True,null=True,default=0) last_modified = models.DateField(("Date"), default=datetime.date.today) -
Creating a templatetag to check users
Creating a templatetag for checking is requested user is in group or not, but it is not working. I have a models class called Team, in that class there is members, and i want to check if the user is part of the team. Models.py class Team(models.Model): team_admin = models.ForeignKey(Profile, on_delete=CASCADE) team_name = models.CharField(max_length=55, unique=True, blank=True) members = models.ManyToManyField(Profile, related_name='teams') slug = models.SlugField(max_length=500, unique=True, blank=True) description = models.TextField(default='Team description') date = models.DateTimeField(auto_now_add=True) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.team_name) super(Team, self).save(*args, **kwargs) def get_url(self): return reverse('projects', kwargs={ 'slug':self.slug }) def __str__(self): return self.team_name auth_extras.py from django import template from django.contrib.auth.models import Group register = template.Library() @register.filter(name='has_group') def has_group(user, group_name): group = Group.objects.get(name=group_name) return True if group in user.groups.all() else False {% if request.user|has_group:"team" %} No matter what i try, if its team, team.members, members, nothing. always get; Group matching query does not exist. -
Is Python and python3 in Linux has different pip?
I installed Django on my Ubuntu 21.04 Software but when I use: python manage.py runserver I get an error massage : No module named “Django” But when I use : python3 manage.py runserve It works fine but my python —-version is 3.10.1 and python3 —version is 3.9.x So what is the error and how I can run it with python only not python3 -
Add tests for django filters
I'm using factory-boy to add tests in Django, and I have a filter : class filter(django_filters.FilterSet): class Meta: model = modelname fields = ["name","id","price"] and I wanna add tests for that filter. how should I write the test for that? -
Uploading images in django
I have being using django for sometime but recently noticed this. Before now I thought images in django, by default, gets uploaded in the path specified in STATIC_URL but I just saw that the bahaviour is diffrent in my app. I have this set up in settings.py: class BlogPost(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE) category = models.CharField(max_length=50, choices=Categories.choices, default=Categories.medications) title = models.CharField(max_length=50) slug = models.SlugField() image = ResizedImageField(upload_to='images/blog/', null=True, blank=True) introduction = models.CharField(max_length=255) body = models.TextField() settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static',), os.path.join(BASE_DIR, 'frontend/build/static'), ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') The static, staticfiles, and media are within the root directory. In my django app, if media directory isn't present the images get uploaded in static directory. However, when both static and media directorie are present preference is given to the media directory (the images get uploaded in media directory). Did I make a mistake somewhere? -
How to avoid no such table error Django db
Using django python, I come across this error whenever I want to clone the repository, and so I assume its whenever it creates a new database (the database is on .gitignore). I know its an issue regarding the models, but I have no idea how to fix it. Its not an issue for me as of right now, but will be if I move to production. Traceback (most recent call last): File "/Users/rayyanshikoh/Documents/GitHub/shaista-s-cooking-blog/.venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/Users/rayyanshikoh/Documents/GitHub/shaista-s-cooking-blog/.venv/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 416, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: blogger_postcategory The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 954, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "/Users/rayyanshikoh/Documents/GitHub/shaista-s-cooking-blog/.venv/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/rayyanshikoh/Documents/GitHub/shaista-s-cooking-blog/.venv/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 124, in inner_run self.check(display_num_errors=True) File "/Users/rayyanshikoh/Documents/GitHub/shaista-s-cooking-blog/.venv/lib/python3.9/site-packages/django/core/management/base.py", line 438, in check all_issues = checks.run_checks( File "/Users/rayyanshikoh/Documents/GitHub/shaista-s-cooking-blog/.venv/lib/python3.9/site-packages/django/core/checks/registry.py", line 77, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/Users/rayyanshikoh/Documents/GitHub/shaista-s-cooking-blog/.venv/lib/python3.9/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/Users/rayyanshikoh/Documents/GitHub/shaista-s-cooking-blog/.venv/lib/python3.9/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/Users/rayyanshikoh/Documents/GitHub/shaista-s-cooking-blog/.venv/lib/python3.9/site-packages/django/urls/resolvers.py", line 446, in check for pattern in self.url_patterns: File "/Users/rayyanshikoh/Documents/GitHub/shaista-s-cooking-blog/.venv/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/rayyanshikoh/Documents/GitHub/shaista-s-cooking-blog/.venv/lib/python3.9/site-packages/django/urls/resolvers.py", line … -
Images in django not showing up in react
This is an application in which I'm using django backend and react frontend. The images display in react when I keep react and django separate and communicate simply with the APIs. However, I want to deploy both the frontend and backend together. I'm trying to use django re_path to redirect any url that does't match with the urls specifiled in django urls.py. Whenever I do this the images from react and django stop displaying. Both django and react lose track of the path of the images. project structure >backend ... settings.py urls.py >blog ... urls.py serializers.py views.py >frontend ... build src package.json manage.py >static urls.py urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('djoser.urls')), path('api/', include('djoser.urls.jwt')), path('api/', include('accounts.urls')), path('summernote/',include('django_summernote.urls')), path('api/blog/', include('blog.urls')), re_path('*', TemplateView.as_view(template_name='index.html')), ] settings.py urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'frontend/build') ], 'APP_DIRS': True, }, ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static',), os.path.join(BASE_DIR, 'frontend/build/static'), ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') Also, whenever I use re_path to redirect unmatched urls from django to react the images in react such as the logo stop displaying but withouy setting re_path all the images in react, … -
Django - How to add annotation to queryset for request.user
I want to add new field to queryset (by annotate()) according to request.user. I have following models: class Tweet(models.Model): ... class Like(models.Model): tweet = models.ForeignKey(Tweet, related_names='likes') user = models.ForeignKey(AUTH_USER_MODEL, related_name='my_likes') type = models.CharField( choices=( ('like', _"Like"), ('dislike', "Dislike") ), ... ) Now I want to execute following query: tweets = Tweet.objects.all().annotate(user_reaction=some_method(request.user)) And I want to this annotated_field(user_reaction), reaction of user to the tweet. user_reaction has 3 states: 1- Like 2- Dislike 3- None (user hasn't like/dislike the tweet) I want to have something like tweets[10].user_reaction, and after that get one of 3 states that came before. (just like, dislkie or None) How can I do this? thanks.