Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
getting 'ArticleSitemap' object has no attribute 'get_urls' error when creating sitemap in django
follow the description on django official document and standard setup for a sitemap but got the following error: AttributeError at /sitemap.xml/ 'ArticleSitemap' object has no attribute 'get_urls' there is my urls: from django.contrib.sitemaps.views import sitemap from . import views from .sitemaps import StaticViewSitemap, ArticleSitemap, ArticleCategorySitemap sitemaps = {'static': StaticViewSitemap, 'article': ArticleSitemap, 'article-category': ArticleCategorySitemap} urlpatterns = [ path('sitemap.xml/', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), ] there is my sitemaps.py: from django.contrib.sitemaps import Sitemap from django.shortcuts import reverse from iman_articles.models import Article, Category class StaticViewSitemap(Sitemap): def items(self): return ['home'] def location(self, item): return reverse(item) class ArticleCategorySitemap(Sitemap): changefreq = 'never' priority = 0.5 def items(self): return Category.objects.all() class ArticleSitemap(): changefreq = 'monthly' priority = 0.5 def items(self): return Article.objects.filter(active=True) def lastmod(self, obj): return obj.edited_at -
Django-Elasticsearch-DSL Range Query
I'm trying to implement the following Elasticsearch query using django-elasticsearch-dsl and am having some difficulty Query { "query":{ "nested":{ "path":"ip_addresses", "query":{ "bool":{ "filter":[ { "range":{ "ip_addresses.ip":{ "gte":"192.168.1.0", "lte":"192.168.1.255" } } } ] } } } } } Code def search_ip_range(self, start: str, end: str): range_query = Q('range', gte=start, lte=end) search = Search() search = search.query('nested', path='ip_addresses', query=range_query) try: response = search.execute() pprint("Found {} results".format(response.hits.total.value)) for hit in response: pprint(hit.detail_url) except Exception as e: pprint('Search error: {}'.format(e)) Error RequestError(400, 'parsing_exception', '[range] query does not support [gte]') -
I'm trying to get Saleor Django installation running
I have followed all the instructions from the saleor.io docs however, I got stuck at migrating the db. The problem is that every time I run python manage.py migrate I get this error message. I have python 3.8 installed and both GTK 2 and 3, MSYS2 but nothing seems to work. Does anyone know how to fix this issue? I have tried everything, and have no clue how to install cairo. Please help OSError: no library called "cairo" was found cannot load library 'C:\GTK\bin\libcairo-2.dll': error 0xc1 cannot load library 'libcairo.so.2': error 0x7e cannot load library 'libcairo.2.dylib': error 0x7e cannot load library 'libcairo-2.dll': error 0x7e -
Django site hosting on Heroku "No web processes runnng"
So I tried to host my Django application to Heroku and at first it worked. Then I wanted to add some release commands so I did this: release_commands.sh python manage.py makemigrations python manage.py migrate And in my Procfile: release: bash ./release_commands.sh web: gunicorn todo.wsgi --log-file - The second line in my Procfile is unchanged, so I guessed that the error must be coming from the release commands, but that's not the case as in my heroku logs I have this: 2021-02-17T19:41:31.675215+00:00 heroku[release.6232]: Process exited with status 0 2021-02-17T19:41:31.772693+00:00 heroku[release.6232]: State changed from up to complete 2021-02-17T19:41:34.021990+00:00 app[api]: Release v11 created by user georgi.hr.dim@gmail.com This is the error message: 2021-02-17T19:41:43.594322+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=POST path="/accounts/login/?next=/" host=essentialtodo.herokuapp.com request_id=5dce4816-6343-44c3-9c8f -171e79379abc fwd="78.90.0.206" dyno= connect= service= status=503 bytes= protocol=https -
How to intergrate API calls in Django-rest framework
I'm trying to build a dashboard app using Django-rest framework and Reactjs for frontend. I'm able to produce required json files for my query. How do I edit my code so as to get different query results for different plots. For example, I have a filter for 'year', 4 types ie. 'segment' here, and 'sale/profit'. I have the required data in my database. Should I make individual query-view for every combination of API calls or is there a better way to modify my code for respective call. I'm noob in Django and have no experience working with react also. Please help. class StatSerializer(serializers.Serializer): segment = serializers.CharField(max_length=25, required=True) sale = serializers.DecimalField(max_digits=12, decimal_places=5, required=True) class Meta: fields = ('segment', 'sale') class StatList(ListAPIView): serializer_class = StatSerializer queryset = superstore.objects.filter(order_date__year=2015).values('segment').annotate(sale=Sum('sales')) def list(self, request): query = self.get_queryset() serializer = StatSerializer(list(query), many=True) return Response(serializer.data) -
how can i add Django Filter in one line by removing the label and making it placeholder?
this is my filters.py class StudentFilterSel(django_filters.FilterSet): class Meta: model=Student fields=['registrationSession','registrationNumber','studentName','applyingForClass','studentDob','studentAadharNum','fathersName','fathersContactNumber'] this is my views.py def selectedList(request): Studentss=Student.objects.filter(AdmissionStatus='Selected') myFilter=StudentFilterSel(request.GET,queryset=Studentss) Studentss=myFilter.qs return render(request,"register/selectedList.html",{'myfilter':myFilter,"Studentss":Studentss}) this is my HTML file <form method='get'> {{myfilter.form}} <button type="submit">search</button> </form> I need a lot of filters in my table but they are getting distorted and getting in multiple lines how can I remove the label and change it to the placeholder to reduce space? -
How to Intercept and Modify / Alter a Django Request URL?
I have a search box. I search for: <- blank spaces in my search box. My form validation catches this. The URL shows: ++++++++++++++++ If I search for: <script>alert(1);</script> The URL shows: <script>alert%281%29%3B<%2Fscript> The Question Where in Django can I alter / change / modify the request that determines the request URL? I'm thinking middleware but I haven't found an example. Would I have to create an entirely new HttpRequest from scratch? Why do I want to? I want to encode the URL differently. For example, strip all punctuation from the q= value, replace whitespace, strip, replace single spaces with + to have cleaner URLs. Really looking for a clear example with CODE. -
How to acces Instances in Foreginkey
I have an app with 3 models class Transaction(models.Model): chp_reference = models.CharField(max_length=50, unique=True) .... Class FamilyGroup(models.Model): ... transaction = models.foreignkey(Transaction) ... Class Familymember(models.Model): ... transaction = models.foreignkey(Transaction) family_group = models.foreignkey(FamilyGroup) ... in another app i have a model Batch that will be a mirror of the three apps,the idea is this app will be imports that accept xlsx files with data being passed in, i have thought about how to make it through like this, but this aint working i cant make Transaction instance inside FamilyGroup get_or_create and same for FamilyMember class Batch(models.Model): income_period_choices = (('Weekly', 'Weekly'), ('Fortnightly', 'Fortnightly')) batch = models.CharField(max_length=50) transaction_chp_reference = models.CharField( max_length=50, null=True, blank=True) transaction_rent_effective_date = models.DateField(null=True, blank=True) transaction_income_period = models.CharField( max_length=11, choices=income_period_choices, null=True, blank=True) transaction_property_market_rent = models.DecimalField( help_text='Weekly', max_digits=7, decimal_places=2, null=True, blank=True) transaction_number_of_family_group = models.PositiveSmallIntegerField( null=True, blank=True, validators=[MaxValueValidator(5), ]) transaction_cruser = models.CharField(max_length=50, null=True, blank=True) transaction_prop_id = models.PositiveIntegerField(null=True, blank=True) transaction_state = models.CharField(max_length=50, null=True, blank=True) family_group_name = models.CharField(max_length=100, null=True, blank=True) family_group_family_type = models.CharField( max_length=50, null=True, blank=True) family_group_alloc_id = models.PositiveIntegerField(null=True, blank=True) family_group_last_rent = models.DecimalField( help_text='per week', max_digits=7, decimal_places=2, null=True, blank=True) family_group_any_income_support_payment = models.BooleanField( null=True, blank=True) family_group_cra_eligibilty = models.BooleanField( help_text='legislated', null=True, blank=True) family_group_cra_amount = models.DecimalField( help_text='per week', max_digits=6, decimal_places=2, null=True, blank=True) family_group_ftb_a = models.DecimalField( 'FTB-A', help_text='Legislated - per week', … -
my media files are shown in localhost but not on server after hosting it, django
I have E-commerce app which I created using django, and it works fine when I run it in localhost , but as soon as I host it to a linux based server it shows in console ' 404 media files. ' I already have " urlpatterns += static(settings.Media_url...) " thing in my urls.py I have done following thing in "settings.py" [ and tried many other ways , possibly not that one which will work for me.] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') BASE_DIR = os.path.dirname(os.path.dirname(file)) MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/') MEDIA_URL = '/media/' static files are shown but not the media files. when I goto domain_name.com\admin and i click on the image it gives me this path ' The requested URL /media/Data/shoes_nike.jpg was not found on this server. ' and in url section 'https://domain_name.com/media/Data/sdfghj.PNG' and on server my project folder is stored in following order home > labelbyk > modaz > >main >media >modaz >db >manage.py -
Why not receiving post body dict - Django
I'm using manual built form (not the Forms.form or ModelForms.form) in Django. <div class="container"> <div id="tabs-contents"> <div id="infos" class="tab-content"> <form action="/page/" method="POST"> {% csrf_token %} <div class="infos-form-content"> <div class="infos-row-1"> <input id="field1" type="text" value="" name="field1"> <input id="field2" type="text" value="" name="field2"> </div> <div class="infos-row-2"> <input id="field3" type="date" value="" name="field3"> </div> ... ... </div> <button type="submit">Save</button> </form> </div> </div> </div> And it contains also dynamic input fields (created by JavaScript). When I check the request.body type in the view (after decoding of course request.body.decode('utf-8')) I find it's a string and not a dictionary. Why is that happening ? And how to receive the form data in dict ? -
Django: Renew and set JWTs as HttpOnly cookie using a middleware. Response() returning django.template.response.ContentNotRenderedError
I have a custom middleware where I am adding SimpleJWR HTTP_AUTHORIZATION to every authorized requests as I am using HttpOnly cookies. Also here I have added code to check whether an access token is valid or not. If not, then a request is sent using requests which fetches the new access token and set's it as HttpOnly cookie. So far, I'm able to get the new access token after it expires. But, the url from where I dispatched the request returns this error: raise ContentNotRenderedError( django.template.response.ContentNotRenderedError: The response content must be rendered before it can be accessed. At the first request it works. It returns the response and saves the tokens as HttpOnly cookies but after the token expires and if I again make the request, instead of (what I want to happen) saving the tokens as HttpOnly cookies and returning the same response again, it is returning the error. I think the issue is in the response statements. My middleware: import jwt import datetime import requests import json from rest_framework.response import Response from django.conf import settings class AuthorizationHeaderMiddleware: def __init__(self, get_response=None): self.get_response = get_response def __call__(self, request): access_token = request.COOKIES.get('access') refesh_token = request.COOKIES.get('refresh') print(refesh_token) # check if the access … -
ModuleNotFoundError: No module named 'mysite.wsgi' error comes up during deployment
I was making a Django web app using pipenv, the Application error window pops up whenever i try running 'heroku open', please help i am stuck in deploying this for over one month and have tried almost every possible solution that was available online but the error still persists. please help. Running'heroku logs --tail' shows: $ heroku logs --tail 2021-02-17T17:50:51.188410+00:00 app[web.1]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> 2021-02-17T17:50:51.297606+00:00 heroku[web.1]: Process exited with status 1 2021-02-17T17:50:51.389796+00:00 heroku[web.1]: State changed from starting to crashed 2021-02-17T17:50:53.000000+00:00 app[api]: Build succeeded 2021-02-17T17:51:39.619675+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=bloggero.herokuapp.com request_id=ecbd78a2-5542-4d08-87f7-e7d12404ae9b fwd="223.239.61.176" dyno= connect= service= status=503 bytes= protocol=https 2021-02-17T17:51:41.855171+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=bloggero.herokuapp.com request_id=42dd37d3-ad4b-43dc-956d-41d34bf03ffd fwd="223.239.61.176" dyno= connect= service= status=503 bytes= protocol=https 2021-02-17T18:04:58.000000+00:00 app[api]: Build started by user ad******@gmail.com 2021-02-17T18:05:29.716771+00:00 app[api]: Deploy 879be0de by user a******@gmail.com 2021-02-17T18:05:29.716771+00:00 app[api]: Release v19 created by user a*******@gmail.com 2021-02-17T18:05:30.074089+00:00 heroku[web.1]: State changed from crashed to starting 2021-02-17T18:05:35.396728+00:00 heroku[web.1]: Starting process with command `gunicorn mysite.wsgi` 2021-02-17T18:05:37.756029+00:00 app[web.1]: [2021-02-17 18:05:37 +0000] [4] [INFO] Starting gunicorn 20.0.4 2021-02-17T18:05:37.756584+00:00 app[web.1]: [2021-02-17 18:05:37 +0000] [4] [INFO] Listening at: http://0.0.0.0:17786 (4) 2021-02-17T18:05:37.756675+00:00 app[web.1]: [2021-02-17 18:05:37 +0000] [4] [INFO] Using worker: sync 2021-02-17T18:05:37.761624+00:00 app[web.1]: [2021-02-17 18:05:37 +0000] [9] [INFO] Booting worker with … -
could someone explain why we return super().form_valid(form) in form_valid method in CreateView in django?
I am trying to link the Item associated with a user class createItem(CreateView): model=Item fields = ['x','y','image'] def form_valid(self,form): form.instance.user_name=self.request.user return super().form_valid(form) this is the snippet,i dont get why we use super().form_valid(form) ,and i also have doubt regarding using self in self.request.user ,i am new to django ,it will really helpful if someone assisted me. -
How do I access only first element in nested dictionary in Django template?
I'm trying to print only first key and value of nested dictionary in django. I am able to do this with python but in django template language my logic isn't working. Here is my code in DTL {% for key, value in data.items %} <h1>Dictionary: {{ key }}</h1> {% for key, value2 in value.items %} <h3>Nested Dictionary-> {{ key }}: {{ value2 }}</h3> <!-- Its printing complete nested Dictionary--> {% endfor %} Here is my view.py which takes data from api then converts json to dictionary def home(request): res = requests.get('https://covid19.mathdro.id/api/countries/india') data = (res.json()) print(type(data)) return render(request, 'Caraousel/home.html', {'data':data}) Here is my output screen. As you see I want to print only value: number -
Any suggestions for a Django Rest Framework JWT package that sets and supports HttpOnly cookies?
I've been using djangorestframework-simplejwt for a while but now I want to store the JWT token in the cookies (instead of localstorage or front-end states) so that every request that the client makes, contains the token. So did some research on it and the most relevant result I found was this stackoverflow question, in which the author is using djangorestframework-jwt which has a pre-configured setting for cookies called JWT_AUTH_COOKIE. So figured switching to that package but then ended up finding out that the package is pretty much dead. Although there is a fork for the djangorestframework-jwt that is recommended to use instead, I was wondering if anyone has any better suggestions of packages or anyways for setting the JWT token in an HttpOnly cookie in the response even in djangorestframework-simplejwt package or something. -
DJANGO: Cannot Filter My Sales List According to the Customer Which is Connected to the User
I have a system where a user can create multiple Customers(Musteri in Turkish) and assign them certain sales. I am trying to use filter() to get the results of my sales(satis in Turkish) list. However, I cannot figure out how to do this. OneToOneField doesn't work in this case and I can't find a way to display my sales and I'd love your help. Thank you in advance. models.py from django.db import models from datetime import datetime, date from django.utils.translation import ugettext_lazy as _ from django.contrib.auth import get_user_model User = get_user_model() class musteri(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1) ad = models.CharField(max_length=100,blank=True) soyad = models.CharField(max_length=100, blank=True) eposta = models.EmailField(max_length=100, blank=True) adres = models.TextField(max_length=200, blank=True) tc = models.CharField(max_length=12, blank=True) telefon = models.CharField(max_length=15, blank=True) def __str__(self): return self.ad + ' ' + self.soyad class Meta: verbose_name = _("musteriler") verbose_name_plural = _("musteriler") TITLE_CHOICES = [ ('Optik', 'Optik'), ('Güneş', 'Güneş'), ('Lens', 'Lens'), ] SATIS_CHOICES = [ ('Nakit', 'Nakit'), ('Kredi Kartı', 'Kredi Kartı') ] class satis(models.Model): musteri = models.ForeignKey(musteri,blank=True, null=True, on_delete= models.SET_NULL) tarih = models.DateField(null=True,blank=True) tur = models.CharField(max_length=5, choices=TITLE_CHOICES, null=True, default='Optik') satici = models.CharField(max_length=100, blank=True) uzak_cerv = models.CharField(max_length=300, blank=True) yakin_cerv = models.CharField(max_length=300, blank=True) uzak_cam = models.CharField(max_length=200, blank=True) yakin_cam = models.CharField(max_length=200, blank=True) saguz_sph = models.CharField(max_length=6, blank=True, null=True) … -
Django models: Name "undefined" is not defined
Hello there I'm trying to make an eBay-like commerce site with Django, and I'm using the Django models to do it. I have a create page with this form: <form method="POST"> {% csrf_token %} <div class="form-group"> <input type="text" class="form-control" placeholder="Item title" name="title" required> </div> <div class="form-group"> <textarea class="form-control" rows="5" placeholder="Description..." name="description" required></textarea> </div> <div class="form-group"> Category <select class="form-control" name="category" required> <option>Fashion</option> <option>Tools</option> <option>Toys</option> <option>Electronics</option> <option>Home accessories</option> <option>Books</option> </select> </div> <div class="form-group"> <label for="exampleFormControlInput1">Initial Bid</label> <input type="number" class="form-control" id="exampleFormControlInput1" placeholder="Starting bid..." name="price" required> </div> <div class="form-group"> <label for="exampleFormControlInput1">Image link (optional)</label> <input type="text" class="form-control" id="exampleFormControlInput1" placeholder="https://example.com/image.jpg..." name="link"> </div> <button class="btn btn-outline-info" type="submit">Submit</button> </form> And this as my views function: def create(request): if request.method == "POST": if Item.objects.last() == undefined: newid = 1 else: newid = lastitem = Item.objects.last().itemid+1 newitem = Item() newitem.owner = request.user.username newitem.name = request.POST.get('title') newitem.about = request.POST.get('description') newitem.price = request.POST.get('price') newitem.category = request.POST.get('category') newitem.itemid = newid if request.POST.get('link'): newitem.link = request.POST.get('link') else : newitem.link = "https://picsum.photos/400" newitem.save() return HttpResponseRedirect(reverse("index")) if request.user.is_authenticated: return render(request, "auctions/create.html") else: return HttpResponseRedirect(reverse("login")) . I have imported my models like from .models import User, Item and my model's file is the following: from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser, models.Model): pass class … -
django the following data would have been submitted to the server
I'm trying to create a question and answer survey with django, but the data is not saved in the database django the following data would have been submitted to the server def add_questions(request): form = QuestionForm(request.POST or None) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('users:question')) form = QuestionForm() context = { 'form': form } return render(request, 'pages/data-entry-tool/add-question.html', context) ``` -
Celery container crashes when using django cache_page (InvalidCacheBackendError)
I am facing an issue with my Django webapp project. I am running a containerized environment using Django, Postgres, Redis and Celery. Mainly, I want to use Redis for caching and Celery to set up live updates. So far, I have been able to connect to redis and celery and store celery task results in the redis cache. Things get messy when I try to cache pages in django using Redis. For some reason, using django's caching system (cache_page decorator) breaks my celery container. The Error My Celery container encounters this error: django.core.cache.backends.base.InvalidCacheBackendError: Could not find backend 'django_redis.cache.RedisCache': No module named 'django_redis' Here is the full traceback: Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/core/cache/__init__.py", line 50, in _create_cache backend_cls = import_string(backend) File "/usr/local/lib/python3.9/site-packages/django/utils/module_loading.py", line 17, in import_string module = import_module(module_path) File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django_redis' During handling of the above exception, … -
Django creating dependent dropdown menus using pyodbc queries
I'm trying to create a dependent dropdown menu in django. Basically, I have 3 menus, which are Division, District and Store. What I need is that depending on the value selected on Division, Disitrict will be filtered, and depending on the district, store will be filtered. I've seen some methods of doing here in stackoverflow but all of them are using models, and I'm using pyodbc. I haven't been able to implement any sort of filtering succesfully since I'm new to html/javascript/ajax, but here is how my files look like. views.py def homeView(request): conn = privatestuff cursor = conn.cursor() cursor.execute('''SELECT DISTINCT division FROM DimStore WHERE NOT division IN ('NULL', 'Closed') ''' ) divisions = [x[0] for x in cursor.fetchall()] cursor.execute('''SELECT DISTINCT district FROM DimStore WHERE NOT district IN ('NULL', 'Closed') ''' ) districts = [x[0] for x in cursor.fetchall()] cursor.execute('''SELECT DISTINCT SAP4Digits FROM DimStore ''' ) sap = [x[0] for x in cursor.fetchall()] context = { 'divisions' : divisions, 'districts' : districts, 'sap' : sap } return render(request, 'dashboard/home.html', context) home.html <form> <div class="row"> <div class="form-group"> <label for="example-date">Start Date</label> <input class="form-control" id="example-date" type="date" name="date"> </div> <div class="form-group"> <label for="example-date">End Date</label> <input class="form-control" id="example-date" type="date" name="date"> </div> <div class="form-group mb-3"> <legend>Division</legend> … -
django not loading .js static file in production
I have a hard time setting up my static files for Django to load. My UWSGI connection is on point, and i receive http 200 OK with index.html, but <scipt type="application/javascript" src="{% static "frontend/main.js" %}"></scipt> gives me nothing. It'strange, because 127.0.0.1:8000/static/main.js actually return main.js. I think there is a problem with loading this file into this template. Any ideas whats wrong? (I run the whole app in docker container) My index.html template to load: {% load static %} <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Label It</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" /> </head> <body style="margin: 0"> <div id="main"> <div id="app"> </div> </div> <scipt type="application/javascript" src="{% static "frontend/main.js" %}"></scipt> </body> </html> part from settings.py: STATIC_URL = '/static/' MEDIA_URL = '/static/media/' STATIC_ROOT = '/vol/web/static' MEDIA_ROOT = '/vol/web/media' STATICFILES_DIRS = [ '/vol/web/static/frontend' ] -
Django __str()__ method for model based on other instances
In Django, assuming a model that has a date and a description as attributes: 2021 Feb 04 Description A 2021 Feb 02 Description B 2021 Jan 31 Description C 2021 Jan 30 Description D 2020 Dec 24 Description E Is there an easy way to not print the year/month if there is an older record with that year/month? 04 Description A Feb 02 Description B 31 Description C 2021 Jan 30 Description D 24 Description E Can I write a __str()__ or another method for that model that considers others instances of the model? I have been through Meta options for models in Django but I'm not sure to which extent I can customize those. -
'IntegerField' object has no attribute 'value_from_datadict' error
I am having a problem with my IntigerField in Django forms: Getting error:IntegerField' object has no attribute 'value_from_datadict' This is mine forms.py: from django import forms from .models import Post class PostForm(forms.ModelForm): class Meta: model = Post fields = ('task_title','task_discription','task_category','recommended_tools','budget') widgets = { 'task_title': forms.TextInput(attrs={'class':'form-control'}), 'task_discription': forms.Textarea(attrs={'class':'form-control'}), 'task_category': forms.Select(attrs={'class':'form-control'}), 'recommended_tools': forms.TextInput(attrs={'class':'form-control'}), 'budget': forms.IntegerField(min_value=10, max_value=10000000), } Views.py: from django.shortcuts import render,get_object_or_404 from django.http import HttpResponse from django.views.generic import ListView,DetailView, CreateView from .models import Post, TaskCategory from .forms import PostForm class AddPost(CreateView): model = Post form_class = PostForm template_name = 'add_post.html' urls.py: from django.urls import path from .views import AddPost urlpatterns = [ path('AddPost/', AddPost.as_view(), name = 'add_post') ] -
Django static files protect access
Can i use login_required to get access to static files? For example if someone know url to static file, still can open this url even logged out. How can i resolve it? Could You give me any solutions how to protect my static files from not logged users. static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I would like to protect my media files -
Django Model with composite primary key didn't update
I have a model with composite primary key class ChatUserModel(CModelMixin): user = models.OneToOneField(Users, models.DO_NOTHING, primary_key=True) chat = models.ForeignKey(ChatModel, models.DO_NOTHING) chat_permissions = models.IntegerField(blank=True, null=True) class Meta: managed = True db_table = 'tbl_chat_users' unique_together = (('user', 'chat'),) And service, which use this model def connect_to_chat(self, serializer: ChatInfoSerializer) -> ChatUserModel: chat_id = serializer.validated_data.get('chat') if ChatUserModel.objects.filter(user_id=self.user.id, chat_id=chat_id).exists(): raise exceptions.ValidationError('User is already member of this chat') bundle = ChatUserModel.objects.create(user=self.user, chat_id=chat_id) if self.user.status == enum_status_of_user.confirmed_email: bundle.chat_permissions = ChatPermissions.canWrite.value bundle.save() return bundle when running, I get an error: django.db.utils.IntegrityError: duplicate key value violates unique constraint "pk_tbl_chat_user_user_id" DETAIL: Key (user_id, chat_id)=(26b01213-b9c3-4abc-b1d2-f7213781a2c6, 3054495f-8a92-49fc-8dd7-7c0700319d87) already exists. I think Django instead update model does create, but i don't know why. Parameter force_update=True didn't help me.