Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is VAPID keys are unique to each server for web push notifications?
While implementing push notification (in Django framework), I have used VAPID keys which generated by a website (https://vapidkeys.com/). Can I use any random dummy text for these keys instead of generating using any other platforms ? Or does these VAPID keys being checked with any server during push notification process ? -
Migrations conflicts in Django, CircularDependencyError
I have a fresh new Postgres DB for my Django app. After applying the initial migrations with python3 manage.py migrate I run python3 manage.py makemigrations to create the tables for my models but no change is detected and no migrations created. This is weird but running python3 manage.py makemigrations app_name for each individual app in my project seems to work. When I try to python3 manage.py migrate I got an error: django.db.migrations.exceptions.CircularDependencyError: hub.0001_initial, crm.0001_initial where hub and crm are the names of 2 of the apps in the projects. This happens because some models in my hub app have relationships with some models in the crm app and viceversa. An effective solution would be to comment out all the relationship fields in my models, migrate, un-comment and makemigrations and migrate again to create the relationships tables. I don't want to go through all my models commenting out fields, is anyone aware of a more elegant solution? Thanks in advance. -
Django get_form results in unbound form (or what is the best way to get url parameters into a model form using CBV createview?)
I'm using a model form and a CBV (createview) to build a form. I needed to get url parameters into the form so I could access details from the previous view that sent the user to the form. To achieve this I initially tried overriding get_form as follows: def get_form(self): form = AddDataForm(key_a=self.request.GET['a'], key_b=self.request.GET['b']) return form This didn't work. The form wouldn't save (even when all fields were correctly completed). It would result in an unbound form. I eventually got a positive result by using get_form_kwargs as follows: def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs.update({'key_a': self.request.GET['a'], 'key_b':self.request.GET['b']}) return kwargs My question is, what about get_form (or my lack of understanding of it) results in this behaviour? My forms.py is below too. class AddDataForm(forms.ModelForm): class Meta: model = MiningTech fields = '__all__' exclude = ('user',) def __init__(self, key_a, key_b, *args, **kwargs): # key_a comes from the view's get_form. super(AddDataForm, self).__init__(*args, **kwargs) if len(key_a) > 3: for field_name in self.fields: if not field_name.startswith(key_a[0:3]): # If field_name doesn't start with first 3 characters of key_a, hide it. self.fields[field_name].widget = forms.HiddenInput() print("__init__ args", kwargs) else: self.fields[field_name].required = True self.fields['slug'].initial = key_b else: print("All fields Hidden") -
How to show/hide field in django admin with js?
I want to hide/show the field depending on the selection, but it doesn't work for me I have models: STATUS_CHOICES = ((1, 'Accepted'),(0, 'Rejected'),) class City(models.Model): id = models.BigAutoField(primary_key=True) status = models.IntegerField(choices=STATUS_CHOICES, default = 0) name = models.CharField(max_length=200) In my admin, i have: @admin.register(City) class CityAdmin(admin.ModelAdmin): list_display = ( 'pk', 'name', 'status', ) form = CityForm class CityForm(forms.ModelForm): class Media: js = ('targets-show.js',) In targets-show.js $(function() { $('input[name="status"]').on('click', function() { if ($(this).val() == '0') { $('#id_name').show(); } else { $('#id_name').hide(); } }); }) -
How to fix "self.model.DoesNotExist"?
I'm trying to filter through some data I've scraped for my project. And I would like to create a "categories" section. I get this error Traceback (most recent call last): File "C:\Users\MUHUMUZA IVAN\Desktop\JobPortal\test.py", line 127, in <module> the_category = Category.objects.get(title='Project') File "C:\Users\MUHUMUZA IVAN\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\MUHUMUZA IVAN\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py", line 397, in get raise self.model.DoesNotExist( jobapp.models.Category.DoesNotExist: Category matching query does not exist. However, I do have an existing model for Category. class Category(models.Model): title = models.CharField(max_length= 200, null = True, blank = True) description = models.TextField(null = True, blank = True) uniqueId = models.CharField(null = True, blank = True, max_length = 100) categoryImage = models.ImageField(default = 'category.png', upload_to = 'upload_images') slug = models.SlugField(max_length = 500, unique=True, blank = True, null = True) seoDescription = models.CharField(max_length = 500, null = True, blank = True) seoKeywords = models.CharField(max_length = 500, null = True, blank = True) def __str__(self): return '{} - {}'.format(self.title, self.uniqueId) def get_absolute_url(self): return reverse('category-detail', kwargs = {'slug': self.slug}) def save(self, *args, **kwargs): if self.uniqueId is None: self.uniqueId = str(uuid4()).split('-')[0] self.slug = slugify('Category {} {}'.format(self.title, self.uniqueId)) self.slug = slugify('Category {} {}'.format(self.title, self.uniqueId)) self.seoDescription = 'Apply for {} Jobs online, start your career journey today'.format(self.title) self.seoKeywords … -
If category == x select the option in Django Template
In my Django Template I have to template tag. {{categories}} and {{category}}. If category equals one of the items in categories ı want that option select. But my code isn't working. I'm pretty sure category equals one item in categories. Here is my code: <select id="category" name="category"> {% for x in categories %} <option value="{{x}}" {% if category == x %}selected{% endif %}>{{x}}</option> {% endfor %} </select> -
IntegrityError: null value in column "categories_id" of relation "polls_products" violates not-null constraint
I am trying to do CRUD with foreign keys using serializers,the issue is that I am unable to insert the data that I want to display with the below error coming : "django.db.utils.IntegrityError: null value in column "categories_id" of relation "polls_products" violates not-null constraint DETAIL: Failing row contains (42, aw, 12, 4, good, 9, null, 3, 3, 1, t)." I in fact made sure to add every data as shown in the images below despite having insert every data the error is coming below is the models and serializer class Products(models.Model): categories = models.ForeignKey(Categories,on_delete=models.CASCADE) sub_categories = models.ForeignKey(SUBCategories,on_delete=models.CASCADE) color = models.ForeignKey(Colors,on_delete=models.CASCADE) size = models.ForeignKey(Size,on_delete=models.CASCADE) # image = models.ImageField(upload_to = 'media/',width_field=None,height_field=None,null=True) title = models.CharField(max_length=50) price = models.CharField(max_length=10) sku_number = models.CharField(max_length=10) product_details = models.CharField(max_length=300) quantity = models.IntegerField(default=0) isactive = models.BooleanField(default=True) class POLLSerializer(serializers.ModelSerializer): class Meta: model = Products fields = "__all__" class pollSerializer(serializers.ModelSerializer): categories = serializers.StringRelatedField() class Meta: model = Products fields = "__all__" def insert(request): data = {} if request.method == "POST": print('POST',id) data['categories'] = request.POST.get('categories') data['sub_categories'] = request.POST.get('sub_categories') data['color'] = request.POST.get('color') data['size'] = request.POST.get('size') data['title'] = request.POST.get('title') data['price'] = request.POST.get('price') data['sku_number'] = request.POST.get('sku_number') data['product_details'] = request.POST.get('product_details') data['quantity'] = request.POST.get('quantity') form = pollSerializer(data=data) print(form) if form.is_valid(): print('form after valid:',form) print("error of form:",form.errors) form.save() … -
DRF Image serializer with nested thumnails
I'm writing django project, in which I have the following models in my media_app application: class Image(File): """ Image model class, through which client will get images stored on AWS S3. """ # ... (not needed in serializer fields) class Thumbnail(File): """ Related model for Image, that contains thumbnails of Image. """ parent = models.ForeignKey( Image, on_delete=models.CASCADE, related_name='thumbnails', ) resolution = models.CharField( _('resolution'), max_length=11, validators=[resolution_validator], ) # ... File class is base model class for media files in my project. It contains mime_type, origina_file_name, size, etc. My question is how can I write serializer for Image, that will have the following structure: { "2775f83e-1608-4135-91d3-f357484df3b1": { "full_size": "http://localhost:8000/api/media/2775f83e-1608-4135-91d3-f357484df3b1/", "358x227": "http://localhost:8000/api/media/8809a43d-c387-4a8e-9c84-8419c406ecd8/", "190x121": "http://localhost:8000/api/media/cb32967e-a576-44ee-b636-6e3a65ec93ba/" } } Where "2775f...df3b1" is pk of Image, "full_size" its own get url (model has method/property api_url, that generate endpoint url to media file get view) and other fields ("358x227" and "190x121") are urls of related thumbnails (keys are from resolution fields in Thumbnail). This structure is not common for DRF, so I've not found the solution in documentation... Serializer will be used in other ModelSerializers. Image contains foreignkeys to other models, those need media files (I'm not using Django Content Type, just nullable OneToOnes), and in api_url there … -
I was just hosting my django project on heroku and it is getting internal server error
2022-07-11T09:25:52.180154+00:00 app[web.1]: from django.urls import path, include,re_path,url 2022-07-11T09:25:52.180154+00:00 app[web.1]: ImportError: cannot import name 'url' from 'django.urls' (/app/.heroku/python/lib/python3.10/site-packages/django/urls/init.py) 2022-07-11T09:25:52.180154+00:00 app[web.1]: 2022-07-11T09:25:52.180154+00:00 app[web.1]: During handling of the above exception, another exception occurred: 2022-07-11T09:25:52.180154+00:00 app[web.1]: 2022-07-11T09:25:52.180155+00:00 app[web.1]: Traceback (most recent call last): 2022-07-11T09:25:52.180155+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner 2022-07-11T09:25:52.180155+00:00 app[web.1]: response = get_response(request) 2022-07-11T09:25:52.180158+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/whitenoise/middleware.py", line 60, in call 2022-07-11T09:25:52.180158+00:00 app[web.1]: response = self.get_response(request) 2022-07-11T09:25:52.180158+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/core/handlers/exception.py", line 57, in inner 2022-07-11T09:25:52.180158+00:00 app[web.1]: response = response_for_exception(request, exc) 2022-07-11T09:25:52.180159+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/core/handlers/exception.py", line 139, in response_for_exception 2022-07-11T09:25:52.180159+00:00 app[web.1]: response = handle_uncaught_exception( 2022-07-11T09:25:52.180159+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/core/handlers/exception.py", line 183, in handle_uncaught_exception 2022-07-11T09:25:52.180159+00:00 app[web.1]: callback = resolver.resolve_error_handler(500) 2022-07-11T09:25:52.180160+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/urls/resolvers.py", line 710, in resolve_error_handler 2022-07-11T09:25:52.180160+00:00 app[web.1]: callback = getattr(self.urlconf_module, "handler%s" % view_type, None) 2022-07-11T09:25:52.180160+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/utils/functional.py", line 49, in get 2022-07-11T09:25:52.180160+00:00 app[web.1]: res = instance.dict[self.name] = self.func(instance) 2022-07-11T09:25:52.180160+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/urls/resolvers.py", line 689, in urlconf_module 2022-07-11T09:25:52.180160+00:00 app[web.1]: return import_module(self.urlconf_name) 2022-07-11T09:25:52.180161+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/importlib/init.py", line 126, in import_module 2022-07-11T09:25:52.180161+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2022-07-11T09:25:52.180162+00:00 app[web.1]: File "", line 1050, in _gcd_import 2022-07-11T09:25:52.180162+00:00 app[web.1]: File "", line 1027, in _find_and_load 2022-07-11T09:25:52.180162+00:00 app[web.1]: File "", line 1006, in _find_and_load_unlocked 2022-07-11T09:25:52.180162+00:00 app[web.1]: File "", line 688, in _load_unlocked 2022-07-11T09:25:52.180162+00:00 app[web.1]: File "", line … -
Will it be correct if property will change the data?
@property def check_too_much_sent_confirmation(self): if self._count_of_hashes_sent >= 3: if UTC.localize(datetime.now()) <= self.updated_at + timedelta(minutes=10): return True else: self.reset_count_of_hashes_sent() return False def reset_count_of_hashes_sent(self, commit=False): self._count_of_hashes_sent = 0 self._save_if_commit(commit) In the code above, check_too_much_sent_confirmation checks if the user can send the confirmation code again, he is given 3 attempts every 10 minutes. self.reset_count_of_hashes_sent() The line above resets the number of attempts. Is it correct that a method is called from a property function that changes the data in the database? Or is it better to call this function separately? -
model form has no attribute 'cleaned_data'
I want to sign in to be able to use the site. However, I'm having a problem: 'LoginForm' object has no attribute 'cleaned_data'. Please tell me how can I solve it. I apologize in advance for my English My forms.py class LoginForm(forms.Form): user_name = forms.CharField(max_length=20, widget=TextInput(attrs={'type':'text','class': 'form-control','placeholder': 'Input username'})) passWord = forms.CharField(max_length=25, widget=TextInput(attrs={'type':'password','class': 'form-control','placeholder': 'Input password'})) class Meta: fields = ['user_name', 'passWord'] My views.py def login_view(request): template_name = 'main/login.html' action_detail = '' if request.method == "POST": form = LoginForm(request.POST) if form.is_valid: username = form.cleaned_data.get('user_name') password = form.cleaned_data.get('passWord') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('/') else: action_detail = 'invalid username or password' else: form = LoginForm() context={ 'title': 'Login', 'form': form, 'action_detail': action_detail, } return render(request, template_name, context) -
Is there a way to deploy Django with other web applications?
I'm starting a new personal server in a VPS (debian). I am doing the mainpage with django. I will like to add to this server/site other external apps (such as GitLab CE, Veloren , FluxRSS and Wallabag). The idea is to centralize everything through django. To have something like : Blog : webpage.com GitLab : gitlab.webpage.com Nevertheless, I cannot seem to find any tutorials or information to do this. I think there is something related to nginx and reverse proxy, but still cant find good information. I know the question is very broad but I'm out of resources and do not know where to search... I've been searching through the web (including stackoverflow) and can't seem to find what I'm looking for, so even if it is just keyword recommendations or links to possible solutions/implementations I'll be extremely happy. -
Foreach Answer calculate score
I have a set of questionnaires, each with questions and each question has an answer, an answer value, and an answer weight. I need to get each answer and multiple the answer value.count by the answer weight value For example question, 1 answer value is -- which is given a value of -2 and the weight is 20 so I need to calculate -2 x 20 and so on for each question to give me a total score of all the questions in the questionnaire. my view so far questionnaires = ProjectQuestionnaire.objects.all() results = [] for q in questionnaires: if ProjectQuestionnaireResponse.objects.filter(project_name_id=project_id, questionnaire_id = q.id).exists(): q_response = ProjectQuestionnaireResponse.objects.get(project_name_id=project_id, questionnaire_id = q.id) q_answered = ProjectQuestionnaireAnswer.objects.filter(response = q_response, answer__isnull=False).count() if q_answered > 1: q_count = (100 / ProjectQuestionnaireQuestion.objects.filter(questionnaire_id = q.id).count() * q_answered) else: q_count = 0 ###### Trying to calculate here ###### the_score = [] for answer in q_answered: answer_score = ProjectQuestionnaireAnswer.objects.filter() ###### END of Calculation ###### Models: class ProjectQuestionnaire(models.Model): title = models.CharField(max_length=50, blank=False, unique=True) description = models.TextField(blank=True) def __str__(self): return str(self.title) class ProjectQuestionnaireQuestion(models.Model): questionnaire = models.ForeignKey(ProjectQuestionnaire, on_delete=models.CASCADE) sequence = models.IntegerField() question = models.TextField() description = models.TextField(blank=True) def __str__(self): return str(self.question) class ProjectQuestionnaireResponse(models.Model): project_name = models.ForeignKey(Project, on_delete=models.CASCADE) questionnaire = models.ForeignKey(ProjectQuestionnaire, on_delete=models.CASCADE) user = … -
redis.exceptions.ConnectionError: Error -3 connecting to redis:6379. Temporary failure in name resolution
redis.service is active and I can connect to redis-cli but in Django I got the issue when Celery try to get access to redis:6379 (as I understand). CELERY_RESULT_BACKEND = os.environ.get('REDISCLOUD_URL', 'redis://localhost:6379/0') CACHEOPS_REDIS = os.environ.get('CACHEOPS_REDIS', 'redis://localhost:6379/9') CACHES = { 'default': { 'BACKEND': 'redis_lock.django_cache.RedisCache', 'LOCATION': 'redis://127.0.0.1:6379/', 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', 'DB': 3, } } } It happened after I reinstalled Ubuntu. Before was ok. Kindly help :) -
Not getting name of the object even with correct function StringRelatedField
I am doing CRUD with foreign keys using serializers and I am getting the data like this not only am I getting the names of "sub_categories" wrong(as I am getting ),but also not getting the names of size and colors that I have added below are the serializers class POLLSerializer(serializers.ModelSerializer): class Meta: model = Products fields = "__all__" class pollSerializer(serializers.ModelSerializer): categories = serializers.StringRelatedField() sub_categories = serializers.StringRelatedField() color = serializers.StringRelatedField() size = serializers.StringRelatedField() class Meta: model = Products fields = "__all__" below is the model class Products(models.Model): categories = models.ForeignKey(Categories,on_delete=models.CASCADE) sub_categories = models.ForeignKey(SUBCategories,on_delete=models.CASCADE) color = models.ForeignKey(Colors,on_delete=models.CASCADE) size = models.ForeignKey(Size,on_delete=models.CASCADE)A # image = models.ImageField(upload_to = 'media/',width_field=None,height_field=None,null=True) title = models.CharField(max_length=50) price = models.CharField(max_length=10) sku_number = models.CharField(max_length=10) product_details = models.CharField(max_length=300) quantity = models.IntegerField(default=0) isactive = models.BooleanField(default=True) insert and show function def show(request): showall = Products.objects.filter(isactive=True) print("show all data:",showall) serializer = pollSerializer(showall,many=True) return render(request,'polls/product_list.html',{"data":serializer.data}) def insert(request): data = {} if request.method == "POST": print('POST',id) data['categories'] = request.POST.get('categories') data['sub_categories'] = request.POST.get('sub_categories') data['color'] = request.POST.get('color') data['size'] = request.POST.get('size') data['title'] = request.POST.get('title') data['price'] = request.POST.get('price') data['sku_number'] = request.POST.get('sku_number') data['product_details'] = request.POST.get('product_details') data['quantity'] = request.POST.get('quantity') form = pollSerializer(data=data) print(form) if form.is_valid(): print('form after valid:',form) print("error of form:",form.errors) form.save() messages.success(request, "Record Updated Successfully...!:)") return redirect("polls:show") else: print('form not valid') print(form.errors) … -
I'm having error in heroku while deploying my Djnago+Vuejs project
I'm trying to deploy my app in heroku through github. I have added whitenoise and gunicorn. It runs fine on my server. What could be the reason? I want the staticfiles in my project... It tells it failed to find my Vue dist folder. Also one more issue is my folder "frontend" is untracked in git. It is not adding even after I tried running "git add ." This is the error I'm getting: -----> Building on the Heroku-20 stack -----> Determining which buildpack to use for this app -----> Python app detected -----> Using Python version specified in runtime.txt -----> Installing python-3.10.5 -----> Installing pip 22.1.2, setuptools 60.10.0 and wheel 0.37.1 -----> Installing SQLite3 -----> Installing requirements with pip Collecting asgiref==3.5.2 Downloading asgiref-3.5.2-py3-none-any.whl (22 kB) Collecting certifi==2022.6.15 Downloading certifi-2022.6.15-py3-none-any.whl (160 kB) Collecting cffi==1.15.1 Downloading cffi-1.15.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (441 kB) Collecting charset-normalizer==2.1.0 Downloading charset_normalizer-2.1.0-py3-none-any.whl (39 kB) Collecting confusable-homoglyphs==3.2.0 Downloading confusable_homoglyphs-3.2.0-py2.py3-none-any.whl (141 kB) Collecting cryptography==37.0.4 Downloading cryptography-37.0.4-cp36-abi3-manylinux_2_24_x86_64.whl (4.1 MB) Collecting defusedxml==0.7.1 Downloading defusedxml-0.7.1-py2.py3-none-any.whl (25 kB) Collecting dj-database-url==0.5.0 Downloading dj_database_url-0.5.0-py2.py3-none-any.whl (5.5 kB) Collecting Django==3.2.10 Downloading Django-3.2.10-py3-none-any.whl (7.9 MB) Collecting django-allauth==0.51.0 Downloading django-allauth-0.51.0.tar.gz (709 kB) Preparing metadata (setup.py): started Preparing metadata (setup.py): finished with status 'done' Collecting django-crispy-forms==1.14.0 Downloading django_crispy_forms-1.14.0-py3-none-any.whl (133 kB) Collecting django-extensions==3.2.0 Downloading … -
Django custom tags validation
I'm getting this error -> Invalid filter: 'cutter' while this is my custom tags.py: from django import template from random import randint register = template.Library() def cutter(list, args): return list[args] register.filter('cutter', cutter) a short part of index.html: {% extends 'main.html' %} {% load custom_tags %} {% load humanize %} {% load static %} {% block title %}main{% endblock title %} {% block home %}active{% endblock home %} {% block body %} <span>{{regions_count|cutter:forloop.counter0}}</span> {% endblock body %} -
Adding a value only once in a ManytoMany field across the table
I have a many-to-many field called paper in a model called Issues. Each Issues record shall have a list of papers. But the paper should be unique across the issue table. In other words, a paper that is added once to Issues should not be able to be added in any other record of the Issues table. How do i achieve it? class Papers(models.Model): ''' All the published papers ''' title = models.CharField(max_length=300) # title def __str__(self): return self.title class Issues(models.Model): ''' All issues ''' number = models.SmallIntegerField() # issue number paper = models.ManyToManyField('Papers') def __str__(self): return str(self.number) -
I got a query error when calling the user login in django
views.py from .models import Profile @login_required(login_url='/signin') def settings(request): user_profile=Profile.objects.get(user=request.user) return render(request,'setting.html',{'user_profile':user_profile}) I think the error is in :user_profile=Profile.objects.get(user=request.user) but I don't know why models.py from django.contrib.auth.models import User from django.db import models class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) id_user = models.IntegerField() bio = models.TextField(blank=True) profileimg = models.ImageField(upload_to='profile_pics/', default='default-profile.png') location = models.CharField(max_length=300, blank=True) birth_date = models.DateField(null=True, blank=True) ERROR -
I am unable to import css and js files from statcfiles in root directory
I have tried everything suggested on the entire internet and stuck here for over 5 days Here are my settings.py STATIC_URL = '/static/' # Add these new lines STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') I have a staticfile directory, i created with python manage.py collectstatic and I have all my css in that file here are my urls from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('accounts.urls')), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Here are my app urls from django.urls import path from accounts.views import * from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', SignUpView.as_view(), name='signup'), path('otp/', OTPView.as_view(), name='otp'), path('login/', LoginView.as_view(), name='login'), path('home/<int:id>', HomeView.as_view(), name="home"), path('logout/', UserLogout.as_view(), name="logout"), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and here is my template base.html that I am inheriting in every other template {% csrf_token %} {% load crispy_forms_tags %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="/User_Authentication/staticfiles/admin/css/responsive.css"> </head> I am getting this error Not Found: /User_Authentication/staticfiles/admin/css/responsive.css [11/Jul/2022 12:05:51] "GET /User_Authentication/staticfiles/admin/css/responsive.css HTTP/1.1" 404 4211 Not Found: /User_Authentication/staticfiles/admin/css/responsive.css … -
Is it possible to define examples for individual `Model` or `Serializer` fields with DRF-Spectacular?
I use DRF-Spectacular to generate the OpenAPI specification for my DRF-based API. So far, I do not add examples but instead rely on SwaggerUI to show examples based on the type and regex patterns. However, in same cases, I would like to add examples directly to the openapi.yml file. I would like to define examples for individual Model or Serializer fields, similar to generating descriptions based on the help_text parameters. Unfortunately, so far I've only found ways to defining complete examples for views and serializers based on OpenApiExample with extend_schema and extend_schema_serializer, respectively. This leads me to my question: Is it possible to define examples for individual Model or Serializer fields with DRF-Spectacular and, if yes, how? -
How can I get the average of 5 grades of User? Django
I am making a movie evaluation site using Djnago. This site allows each user to comment on a movie. At that time, I will give a 5-grade rating. How can I get the average of the 5-grade ratings of all users who commented on the movie? Below is a model of the comment. from datetime import datetime from accounts.models import CustomUser from django.core.validators import MaxValueValidator, MinValueValidator from django.db import models # Create your models here. class Comment(models.Model): comment = models.TextField(max_length=1000) stars = models.FloatField(blank=False,null=False,default=0, validators=[MinValueValidator(0.0), MaxValueValidator(5.0)]) user = models.OneToOneField(CustomUser, on_delete=models.CASCADE,) movie_id = models.IntegerField() created_at = models.DateTimeField(default=datetime.now) updated_at = models.DateTimeField(auto_now=True) -
Django print all permissions of a users in template
I am editing the user permissions in templates. And I want to display checked checkbox if user has permissions or unchecked if user has not specific permissions. My View.py codes are as below. def EditUserView(request,id=0): user = User.objects.get(pk=id) permission = Permission.objects.all() return render(request,'edituser.html',{"userdata":user,"permissions":permission}) And My templates code are as given below. <div class="table-wrapper"> <table class="table"> <thead> <tr> <th>Permissions</th> <th>Status</th> </tr> </thead> <tbody> {% for perm in permissions%} <tr> <td id="perm">{{perm}}</td> <td><input type="checkbox" name="status" id="status" onclick="ChangeUserPermissions(this,userid='{{userdata.id}}',permission='{{perm}}')"></td> </tr> {% endfor %} </tbody> </table> </div> My objectives of the code is only display checked checkbox if have permissions or unchecked if not have permissions -
openCv Can't convert object of type 'JpegImageFile' to 'str' for 'filename'
from PIL import Image import numpy as np def save(self, *args, **kwargs): # open image pil_img = Image.open(self.pic) # convert the image to array and do some processing cv_img = np.array(pil_img) img = main(pil_img) # convert back to pil image im_pil = Image.fromarray(img) # save buffer = BytesIO() im_pil.save(buffer, format='png') image_png = buffer.getvalue() self.pic.save(str(self.pic), ContentFile(image_png), save=False) super().save(*args, **kwargs) can't understand what's wrong with it. i even tried to comment the cv_img = np.array(pil_img) but it still fail to run -
Why is my Django URL not linked to user ID?
When I enter the following URL: 'http://127.0.0.1:8000/mainpage/13/updateportfolio/', the rendered template shows 'Welcome username#13' on the top right which corresponds to the id #13 on my PostgreSQL database. '13' on the url However, if I type the URL 'http://127.0.0.1:8000/mainpage/100/updateportfolio/, the rendered template still shows the same username on the top right, it should redirect the user to the login page. How do I produce this authentication or am I having the wrong concept about URLs in general? '100' on the url urls.py app_name = 'mainpage' urlpatterns = [ path('<int:pk>/updateportfolio/', mainview.UpdatePortfolioView.as_view(), name='update'), path('<int:pk>/transactions/'), mainview.TransactionsView.as_view(), name='transactions'), ] views.py class UpdatePortfolioView(LoginRequiredMixin, FormView): form_class = UpdatePortfolio template_name = 'mainpage/updateportfolio.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) current_user = get_object_or_404(User, pk=self.request.user.pk) tickers = TickerSymbols.objects.all() context['username'] = current_user.username context['form'] = self.form_class context['tickers'] = tickers return context def get_object(self): return self.request.user.pk def form_valid(self, form): user_holding = get_object_or_404(Transaction, pk=self.request.user.pk) symbol = form.cleaned_data['symbol'].upper() share_number = form.cleaned_data['share'] user_holding.symbol = symbol # Save form inputs to database messages.success( self.request, f"{share_number} shares of {symbol} has been updated to your portfolio") # Save form super(UpdatePortfolioView, self).form_valid(form) if 'submit' in self.request.POST: return redirect(reverse('mainpage:transactions', kwargs={'pk': self.request.user.pk})) elif 'submit_another' in self.request.POST: return render(self.request, self.template_name, {'form': form})