Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error: 'QuerySet' object has no attribute '_meta'
When calling the update API i and getting this Error: 'QuerySet' object has no attribute '_meta' Please have a look at my code, not sure where i am going wrong. models.py class FarmerAdvisory(models.Model): ''' Farmer Advisory model definition ''' CATEGORY_CHOICES = ( ("CROP", "CROP"), ("WEATHER", "WEATHER"), ("FARMLAND", "FARMLAND") ) SUB_CATEGORY_CHOICES = ( # ("CROP", "CROP"), # ("WEATHER", "WEATHER"), # ("FARMLAND", "FARMLAND") ) STATUS_CHOICES = ( ('OPEN', 'OPEN'), ('IN-PROGRESS', 'IN-PROGRESS'), ('CLOSED', 'CLOSED') ) id = models.AutoField(db_column='id', primary_key=True) category = models.CharField(db_column='category', max_length=100, null=False, blank=False, choices=CATEGORY_CHOICES) sub_category = models.CharField(db_column='sub_category', max_length=100, null=False, blank=False) # ,choices=SUB_CATEGORY_CHOICES) title = models.CharField(db_column='title', max_length=200, null=True, blank=True) description = models.CharField(db_column='description', max_length=500, null=True, blank=True) media = models.JSONField(db_column='media', blank=True, null=True) status = models.CharField(db_column='status', max_length=15, null=False, blank=False, default='OPEN', choices=STATUS_CHOICES) # assigned_to = reply = models.CharField(db_column='reply', max_length=500, null=True, blank=True) reply_media = models.JSONField(db_column='reply_media', blank=True, null=True) label = models.CharField(db_column='label', max_length=100, null=True, blank=True) farmer_id = models.ForeignKey(Farmer, on_delete=models.CASCADE, db_column='farmer_id') objects = models.Manager() class Meta: managed = True db_table = 'farmer_advisory' serializers.py class FarmerAdvisorySerializer(serializers.ModelSerializer): class Meta: model = FarmerAdvisory fields = '__all__' views.py class FarmerAdvisoryObjectView(ShortCircuitMixin, APIView): def put(self, request, farmer_id, adv_id): try: farmer_adv = FarmerAdvisory.objects.filter(farmer_id=farmer_id, id=adv_id) serializer = FarmerAdvisorySerializer(farmer_adv, data=request.data) if serializer.is_valid(raise_exception=True): serializer.save() response = JsonResponse(serializer.data, status=status.HTTP_201_CREATED) return response return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) except Exception as ex: logger.error(traceback.format_exc()) return Response(data={"Error": … -
How to remove similar and duplicate queries in django rest framework?
When i call product endpoint, duplicate and similar queries are occured for average rating. I have used prefetch_related to solve the problem but it seems like the way i used arenot correct. Can you guys please help me to solve this scenario. Here is the model structure models.py class Product(models.Model): name = models.CharField(max_length=255) vendor = models.ForeignKey( Vendor, on_delete=models.CASCADE, ) class ProductRating(models.Model): product_id = models.ForeignKey( Product, on_delete=models.CASCADE, ) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) maxval=5 message='Rating must be less than 5' rate =models.PositiveIntegerField(validators=[MaxValueValidator(maxval,message)],null=True) comment = models.TextField(blank=True,null=True) seller_reply = models.TextField(blank=True,null=True) reply_at=models.DateTimeField(auto_now=True) created_at=models.DateTimeField(auto_now=False,auto_now_add=True) class VendorRating(models.Model): product_id = models.ForeignKey( Product, on_delete=models.CASCADE, ) vendor_id=models.ForeignKey( Vendor, on_delete=models.CASCADE ) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) maxval=5 message='Rating must be less than 5' communication_rate=models.PositiveIntegerField(validators=[MaxValueValidator(maxval,message)],null=True,blank=True) product_quality_rate=models.PositiveIntegerField(validators=[MaxValueValidator(maxval,message)],null=True,blank=True) experience_rate=models.PositiveIntegerField(validators=[MaxValueValidator(maxval,message)],null=True,blank=True) created_at=models.DateTimeField(auto_now=False,auto_now_add=True) in views.py def get_queryset(self): queryset=self.get_serializer().setup_eager_loading(Product.objects.all()) return queryset in serializers.py class ProductSerializer(TaggitSerializer, serializers.ModelSerializer): avg_productrating = serializers.SerializerMethodField("get_rating") avg_vendorrating=serializers.SerializerMethodField("get_avgvendorrating") def get_rating(self, obj): rating=obj.productrating_set.all().aggregate(avg=Avg("rate"))['avg'] average_rate=round(rating,2) if rating else rating return average_rate def get_avgvendorrating(self,obj): try: average_rate=obj.vendor.vendorrating_set.all().aggregate( Avg("communication_rate"),Avg('product_quality_rate'),Avg("experience_rate") ) rates=[rate for rate in average_rate.values() if rate is not None] if(not rates): total=0 else: total=sum(rates)/3 return round(total,2) except: return 0 @staticmethod def setup_eager_loading(queryset): """ Perform necessary eager loading of data. """ queryset=queryset.prefetch_related(Prefetch('vendor',queryset=Vendor.objects.prefetch_related('user','vendorrating_set'))) in urls.py rom rest_framework import routers from . import views router = routers.SimpleRouter() router.register(r"product", views.ProductViewSet,basename='products') output … -
Validate keys and value types in Django .JSONFields
Problem Statement I have a Django model containing a JSONField: class DataModel(models.Model): dict_field = models.JSONField() How can I validate the inputs of this JSONField such that it only accepts a pre-defined list of keys and their associated types, as follows: "key1": bool "key2": int "key3": Optional[int] My Attempt I attempted to solve this with Pydantic by defining a class: class DictModel(pydantic.BaseModel): key1: bool key2: int key3: Optional[int] But I couldn't find a way to pass this schema to my Django model. Does django have something built in for this type of problem? -
how to connect postgresql database using IP Address in python
I want to connect my posgresql database using remote ip address but i am getting an error. psycopg2.OperationalError: connection to server at "178.56.25.266", port 5432 failed: Connection refused (0x0000274D/10061) Is the server running on that host and accepting TCP/IP connections? here also i am sharing my python code. import psycopg2 conn = psycopg2.connect(database="test", user='postgres', password='', host='178.56.25.266') cursor = conn.cursor() cursor.execute("select version()") data = cursor.fetchone() print("Connection established to: ",data) conn.close() Please help me to resolve this problem. -
Django project doesn't work on the VPS with a port, gunicorn+ nginx
I have Django project on my VPS. When I check my website in the browser I get an error: 1 connect() failed (111: Connection refused) while connecting to upstream, client: 86.245.120.83, server: mysite.com, request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:6112/", host: "mysite.com" upstream app_server_wsgiapp { server 127.0.0.1:6112 fail_timeout=0; } server { server_name mysite.com www.mysite.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { autoindex on; alias /var/www/www-root/data/www/mysite.com/public_html/static/; } location /media/ { alias /var/www/www-root/data/www/mysite.com/public_html/media/; } location / { include proxy_params; proxy_pass http://app_server_wsgiapp; } charset off; disable_symlinks if_not_owner from=$root_path; include /etc/nginx/vhosts-includes/*.conf; include /etc/nginx/vhosts-resources/mysite.com/*.conf; access_log /var/www/httpd-logs/mysite.com.access.log; error_log /var/www/httpd-logs/mysite.com.error.log notice; set $root_path /var/www/www-root/data/www/mysite.com; root $root_path; listen XX.XXX.XX.XXX:80; } /etc/systemd/system/mysite.service [Unit] Description=mysite daemon Requires=mysite.socket After=network.target [Service] User=www-root Group=root WorkingDirectory=/var/www/www-root/data/www/mysite.com/public_html/sokovblogpr ExecStart=/var/www/www-root/data/www/mysite.com/public_html/mysiteenv/bin/gunicorn --bind 0.0.0.0:6112 mysitepr.wsgi:application [Install] WantedBy=multi-user.target /etc/systemd/system/mysite.socket [Unit] Description=sokovblog socket [Socket] ListenStream=/run/mysite.sock [Install] WantedBy=sockets.target systemctl status mysite ● mysite.service - mysite daemon Loaded: loaded (/etc/systemd/system/mysite.service; enabled; vendor preset: enabled) Active: active (running) since Wed 2022-12-07 18:54:42 CET; 16min ago TriggeredBy: ● mysite.socket Main PID: 4360 (gunicorn) Tasks: 2 (limit: 1843) Memory: 45.1M CGroup: /system.slice/mysite.service I checked it works if I start it in the terminal via Gunicorn gunicorn --bind 0.0.0.0:6112 mysitepr.wsgi And if I check it in terminal I get my main html page … -
How can I store clone of the image to another model on Django
Does anyone know how to store a clone of the original image to another model on Django. This is my models.py file class blogs(models.Model) title = models.CharField(max_length=100, null=True, blank=True) slug = models.SlugField(max_length=200, unique=True, auto_created=True) author = models.ForeignKey(User, on_delete=models.CASCADE) created_on = models.DateTimeField(auto_now_add=True) time = models.TimeField(auto_now_add=True) cone_image = models.ImageField(upload_to='cloned') image = models.ImageField(upload_to='photos',height_field="image_height", width_field="image_width" I am looking to clone the image field in this model and store to clone image model -
Sync to Async Django ORM queryset length
In asynchronous context I try to do: invites = await InviteLogic.get_invites(self.app.user) if len(invites) > 0: ... InviteLogic is like this: @sync_to_async def get_invites(self, inviter): return Invite.objects.filter(inviter=inviter) I get an error in line if len(... django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. How do I call len asynchronously? -
Object type <class 'str'> cannot be passed to C code in AES CTR
I want to encrypt with AES ctr in Python, but I get an error: Object type <class 'str'> cannot be passed to C code I was trying code from tweaksp using code. All I want is just to encrypt the plaintext. Here's my code: key_bytes = 16 def encrypt(key, pt): pt = read_file(pt) if len(key) <= key_bytes: for x in range(len(key),key_bytes): key = key + "0" assert len(key) == key_bytes print(key) print(pt) # Choose a random, 16-byte IV. iv = Random.new().read(AES.block_size) # Convert the IV to a Python integer. iv_int = int(binascii.hexlify(iv), 16) print(iv_int) # Create a new Counter object with IV = iv_int. ctr = Counter.new(AES.block_size * 8, initial_value=iv_int) print(ctr) ctr2 = ctr.encode('utf8') # Create AES-CTR cipher. aes = AES.new(key.encode('utf8'), AES.MODE_CTR, counter=ctr2) print(aes) # Encrypt and return IV and ciphertext. ciphertext = aes.encrypt(pt) return (iv, ciphertext) def read_file(f): f = open('media/txt/'+f, 'r') f.read() f.tell() f.seek(0) file_content = f.read() f.close() return file_content And my traceback: Traceback (most recent call last): File "C:\Users\Capoo\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\Capoo\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "F:\KULIAH\SEMESTER8\SKRIPSI\MusicLockApp\MusicLockApp\views.py", line 54, in homepage (iv, enc) = encrypt(ky, pt) File "F:\KULIAH\SEMESTER8\SKRIPSI\MusicLockApp\MusicLockApp\views.py", line 268, in encrypt ciphertext = aes.encrypt(pt) … -
Django nested serializers - Direct assignment to the reverse side of a related set is prohibited
I want to implement my own create function on my serializer but I'm getting the following error: Internal Server Error: /api/cheatsheets/ Traceback (most recent call last): File "/home/christian-sama/Code/cheatsheet-app/venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/christian-sama/Code/cheatsheet-app/venv/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/christian-sama/Code/cheatsheet-app/venv/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/christian-sama/Code/cheatsheet-app/venv/lib/python3.10/site-packages/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "/home/christian-sama/Code/cheatsheet-app/venv/lib/python3.10/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/home/christian-sama/Code/cheatsheet-app/venv/lib/python3.10/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/home/christian-sama/Code/cheatsheet-app/venv/lib/python3.10/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/home/christian-sama/Code/cheatsheet-app/venv/lib/python3.10/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/home/christian-sama/Code/cheatsheet-app/venv/lib/python3.10/site-packages/rest_framework/mixins.py", line 19, in create self.perform_create(serializer) File "/home/christian-sama/Code/cheatsheet-app/venv/lib/python3.10/site-packages/rest_framework/mixins.py", line 24, in perform_create serializer.save() File "/home/christian-sama/Code/cheatsheet-app/venv/lib/python3.10/site-packages/rest_framework/serializers.py", line 212, in save self.instance = self.create(validated_data) File "/home/christian-sama/Code/cheatsheet-app/api/serializers.py", line 35, in create Section.objects.create(cheatsheet=cheatsheet, **section) File "/home/christian-sama/Code/cheatsheet-app/venv/lib/python3.10/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/christian-sama/Code/cheatsheet-app/venv/lib/python3.10/site-packages/django/db/models/query.py", line 669, in create obj = self.model(**kwargs) File "/home/christian-sama/Code/cheatsheet-app/venv/lib/python3.10/site-packages/django/db/models/base.py", line 562, in __init__ _setattr(self, prop, value) File "/home/christian-sama/Code/cheatsheet-app/venv/lib/python3.10/site-packages/django/db/models/fields/related_descriptors.py", line 595, in __set__ raise TypeError( TypeError: Direct assignment to the reverse side of a related set is prohibited. Use lines.set() instead. My models.py from django.db import models class Cheatsheet(models.Model): title = models.CharField(max_length=500) description = models.CharField(max_length=500) score = models.IntegerField() … -
How to resolve django filter button not working?
I am trying to implement Django Filtering but I cant seem to make it work. Only an 'Option' button appears the 'filter' button does not. It still does not work. What seems to be the problem here? views.py class MKRealtyListView(generics.ListAPIView): queryset = Realty.objects.all() serializer_class = RealtySerializer filter_backends = [DjangoFilterBackend] filterset_fields = ('type', 'location') #@permission_classes([IsAuthenticated]) @api_view(['GET', 'POST']) def listings(request, format=None): if request.method == 'GET': realty = Realty.objects.all() serializer = RealtySerializer(realty, many=True) return Response(serializer.data) settings.py INSTALLED_APPS = [ 'rest_framework', 'mkrealty', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework.authtoken', 'django_filters' ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ], 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend',] } urls.py urlpatterns = [ path('admin/', admin.site.urls), path('listings/', views.MKRealtyListView.listings), path('listings/<int:id>', views.listing_detail), path('api-token-auth/', obtain_auth_token, name='api_token_auth'), # <-- And here ] -
How to construct dynamic Q() in Django
I'm trying to filter dynamic value from a form in template to my query in Django project the value can be dynamic, but it would look like this first_query = ['a', 'b', 'c'] second_query = ['d', 'e', 'f'] what i want to achieve is to query something like this SELECT * FROM table WHERE column_1 = 'a' OR column_1 = 'b' OR column_1 = 'c' OR column_2 = 'd' OR column_2 = 'e' OR column_2 = 'f' Here's what i've done first_query = [ Q(column_1__contains=w) for w in first_query ] """ If you print first_query [<Q: (AND: ('column_1__contains', 'a'))>, <Q: (AND: ('column_1__contains', 'b'))>, <Q: (AND: ('column_1__contains', 'c'))>] """ reduce_first_query = reduce(or_, query_first_query) """ (OR: ('column_1', 'a'), ('column_1', 'b'),('column_1', 'c')) """ second_query = [ Q(column_2__contains=w) for w in second_query ] reduce_second_query = reduce(or_, query_second_query) When i try to filter Item from my database it gives me rows more than doubled than what i do directly from the database test_item = Item.objects.filter(reduce_first_query) # Gives 1900 ish rows, should be 900 ish What do i do wrong, is it because of the way i construct Q() ? or there other mistake ? NOTES I'm using Postgresql 14 -
How to address this codec error when fetching an api for image upload in django?
Error: UnicodeDecodeError at /user_image_upload/ 'utf-8' codec can't decode byte 0xcc in position 144: invalid continuation byte Payload: Image (binary) 500 internal server error. VueJS method/data...: data(){ return { profile_image:null } }, async createImage() { let received_image = document.querySelector('#imageInput').files[0] let formData = new FormData // 'image' as in models.py formData.append('image', received_image) fetch('/user_image_upload/',{ method:'POST', credentials: 'include', body: formData }).then(response => response.json()).then((data) => this.profile_image=(data)) console.log(this.profile_image) }, In Django template: {% csrf_token %} <form @submit.prevent=""> {% csrf_token %} <input id ="imageInput" type = "file" accept="image/"> <button @click="createImage()">Upload</button> </form> in models.py class Profile(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) image = models.ImageField(upload_to='uploads') def __str__(self): return f'{self.user.username} Profile' in views.py @login_required @csrf_exempt def user_image_upload(request): if request.method=='POST': response = json.loads(request.body) Item.objects.create(user=request.user) return JsonResponse({'new':'updated'}) -
Django - How to change Textarea rows and columns in media query
I am having difficulties trying to understand how to change Textarea sizes so that my webpage is responsive. I currently have it set where the rows are 8 and cols is 60 which is perfect for viewing a webpage on a desktop. However, as i am trying to make my webpage responsive, i can not find a way to change the column value down to 30. I have thought about using css media query for this but can not understand how to change the values as they are currently set in the forms.py file as as shown below. I know users are able to resize the Textarea but i would like it if they can not resize the text area. So my question is if it is possible to make the Textarea responsive? forms.py: class UserSettings(ModeldForm): class Meta: model = Profile fields = ["name", "email", "profile_biography"] widgets = { 'profile_biography': forms.Textarea(attrs={ 'rows': 8, 'cols': 60, 'style':'resize:none'}), } -
What is the purpose of using GraphQL with MVC web frameworks (Laravel, Django, etc.), when currently built-in controllers does not make sense then?
What is the purpose of using GraphQL with MVC web frameworks (Laravel, Django, etc.), when currently built-in MVC framework controllers do not make sense then? Is there any simpler way/framework with just that purpose and is the reason for that just love for Laravel, Django and other MVC frameworks? If there is nothing similar and simpler, could we build something good and open-source just for that purpose, taking into account the increasing popularity of using that architecture and logic with GraphQL? I am open to suggestions and to start such a project. (It would be nice to hear suggestions/opinions from @taylorotwell, @adrian-holovaty, @simon-willison, Jeffrey Way) After a lot of experience with backend and frontend technologies, that question comes to me logically. Thank you :) -
It is impossible to add a non-nullable field 'classid' to classes without specifying a default
from django.db import models class students(models.Model): studentid = models.BigIntegerField(null = False, primary_key = True) lastname = models.TextField() firstname = models.TextField() middlename = models.TextField() addr1 = models.TextField() addr2 = models.TextField() city = models.TextField() stateprovince = models.TextField() country = models.TextField() postalcode = models.TextField() email = models.TextField() class gradevalues(models.Model): grade = models.TextField(null = False, primary_key = True) qgrade = models.DecimalField(blank=True, null=True, max_digits=10, decimal_places=10) class stuclasses(models.Model): classid = models.BigIntegerField(null = False, primary_key = True, ) studentid = models.BigIntegerField(null = False) grade = models.ForeignKey(gradevalues, on_delete = models.CASCADE) class courses(models.Model): courseid = models.TextField(null = False, primary_key = True) coursename = models.TextField() coursedesc = models.TextField() credits = models.BigIntegerField(null = False) deptid = models.TextField() class classes(models.Model): classid = models.BigIntegerField(primary_key = True) courseid = models.ForeignKey(courses, on_delete = models.CASCADE) term = models.TextField() year = models.DecimalField(blank=True, null=True, max_digits=10, decimal_places=10) instructor = models.TextField() classroom = models.TextField() classtime = models.TextField() class stuclasses_students(models.Model): stuclasses_studentid = models.ForeignKey(stuclasses, on_delete = models.CASCADE) students_studentid = models.ForeignKey(students, on_delete = models.CASCADE) class stuclasses_classes(models.Model): stuclasses_classid = models.ForeignKey(stuclasses, on_delete = models.CASCADE) classes_classid = models.ForeignKey(classes, on_delete = models.CASCADE) It is impossible to add a non-nullable field 'classid' to classes without specifying a default. This is because the database needs something to populate existing rows. Please select a fix: Provide a one-off default now … -
Django migrations not applied
I am trying to do the portfolio project and when doing the migration part, I get this: Operations to perform: Apply all migrations: projects Running migrations: No migrations to apply. What am I doing wrong? I am following the exact steps written on the document I tried looking on google and could not find any good answers, please help. -
Authentication credentials were not provided. social django postman api testing
I'm developing a Django 4.1 application, and i'm using the drf-social-oauth2 framework. Here's my config: INSTALLED_APPS = [ ... 'oauth2_provider', 'social_django', 'drf_social_oauth2', ] TEMPLATES = [ { ... 'OPTIONS': { 'context_processors': [ ... 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticatedOrReadOnly', ], 'DEFAUL_ATHENTICATION_CLASSES': [ # drf auth classes 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', # # oauth2 auth classes 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', 'drf_social_oauth2.authentication.SocialAuthentication', ] } AUTHENTICATION_BACKENDS = ( 'drf_social_oauth2.backends.DjangoOAuth2', 'django.contrib.auth.backends.ModelBackend', ) I generate the Bearer token normally to any user, but, when I try to make a request like to patch some user, i add at the authorization windown at postman type: Bearer, and Token: the valid one i just generated. The header is made by postman, and is ok, but when i test, I still recieving the "detail": "Authentication credentials were not provided." response code: 403 the url is right, and at the API i can patch it normally. Anyone knwos what's happening? thanks I tried changing the user, use a superuser or not, generating new tokens, change the body, nothing worked -
How to add a filter by category option using Django filter
Hai i am trying to add a filter option by category on django using Django filter. But when i am trying to add a filter i got an error saying that Field 'id' expected a number but got 'blogs'. Can anyone please help me to create a filter by category. This is my blog model class blog(models.Model): title = models.CharField(max_length=100, null=True, blank=True) slug = models.SlugField(max_length=200, unique=True, auto_created=True) author = models.ForeignKey(User, on_delete=models.CASCADE) created_on = models.DateTimeField(auto_now_add=True) tags = TaggableManager(blank=True) category = models.ForeignKey('Categorie', null=True, blank=True, on_delete=models.CASCADE) This is my category model class Categorie(models.Model): name = models.CharField(max_length=100, null=True, blank=True) slug = models.SlugField(max_length=250, unique=True, auto_created=True) This is my filters.py file blog_choice = ( ('new','new'), ('latest','latest'), ('technology','technology'), ('sports','sports'), ) category = django_filters.MultipleChoiceFilter(label='Category', choices=blog_choice, widget=CheckboxSelectMultiple(attrs={'class': 'mr-2 h-[15px] w-5 border-gray-300 inline mb-4 '})) I tried to create a filter function but got error Field 'id' expected a number but got 'new'. -
in my django template my input is reset when I send the search
What do I need to put in the value parameters of my inputs so that this information is forwarded to the fields? You can see what I'm talking about by entering the page and verify that when a search is made all my entries are restarted http://54.166.3.214:8000/results here is my html code in case it was necessary <input id="kword" name="kword" value="" class="input-form search-box" type="search" placeholder="Profesión, palabra clave o empresa" data-ac="//ac.careerjet.net/ns" data-target="#ac-s" data-target2="#s" data-as="1" data-lc="es_MX" data-mhd="10" data-mhm="3" > <input id="location" name="location" value="" class="input-form search-box" type="search" placeholder="Ubicacion" data-ac="//ac.careerjet.net/ns" data-target="#ac-s" data-target2="#s" data-as="1" data-lc="es_MX" data-mhd="10" data-mhm="3" > <select name="type" id="type"> <option value="Todos">Todos</option> <option value="Remoto">Remoto</option> <option value="Presencial">Presencial</option> </select> <select name="sort" id="sort"> <option value="relevance">Relevancia</option> <option value="date">Fecha</option> <option value="salary">Salario</option> </select> -
How to put all my cart items in an XML Django
Does anyone know why it's returning only 1 item? There are 2 items in my cart. Here is the "item_dict" variable: cart_items = CartItem.objects.filter(user=current_user) for cart_item in cart_items: total += (cart_item.product.price * cart_item.quantity) quantity += cart_item.quantity item_dict = f""" <item> <id>{cart_item.product.id}</id>\r\n <description>{cart_item.product.name}</description>\r\n <quantity>{cart_item.quantity}</quantity>\r\n <amount>{cart_item.product.price}</amount>\r\n </item> """ return HttpResponse(item_dict) In my HttpResponse(item_dict) it is returning me only 1 item Meu objetivo é poder devolver todos os itens do meu carrinho no meu XML I don't know what I'm doing wrong. -
How to render each item of a dictionary in django
I am working on a django project whereby users upload resumes and they are parsed before the results are save in user profile. I have achieved the parsing part and saved the data bu the problem is rendering the data. An example is in the skills field whereby the data is stored as a dictionary and therefore I cannot display them one at a time. Here is my models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(default='default.jpg', upload_to='profile_images') bio = models.TextField() resume = models.FileField('Upload Resumes', upload_to='resumes/', null=True, blank=True,default='resume.docx') name = models.CharField('Name', max_length=255, null=True, blank=True) email = models.CharField('Email', max_length=255, null=True, blank=True) mobile_number = models.CharField('Mobile Number', max_length=255, null=True, blank=True) education = models.CharField('Education', max_length=255, null=True, blank=True) skills = models.CharField('Skills', max_length=1000, null=True, blank=True) company_name = models.CharField('Company Name', max_length=1000, null=True, blank=True) college_name = models.CharField('College Name', max_length=1000, null=True, blank=True) designation = models.CharField('Designation', max_length=1000, null=True, blank=True) experience = models.CharField('Experience', max_length=1000, null=True, blank=True) total_experience = models.CharField('Total Experience (in Years)', max_length=1000, null=True, blank=True) whatsapp = models.URLField(null=True, blank=True) facebook = models.URLField(null=True, blank=True) twitter = models.URLField(null=True, blank=True) linkedin = models.URLField(null=True, blank=True) languages = models.CharField(max_length=1000, null=True, blank=True) profession = models.CharField(max_length=100, null=True, blank=True) nationality = models.CharField(max_length=100, null=True, blank=True) def __str__(self): return self.user.username # resizing images def save(self, *args, **kwargs): super().save() img = … -
Two versions of the same Django app: 1 for administration, 1 for queries only
I have two Django apps that share a database and also a number of models. App 1 is used to administrate the data via the admin page. App 2 is used only to query the data and present the data. The apps are running on different servers. My current solution is to run the exact same code in models.py on both apps. However, I have not run makemigration/migrate on app2. This solution works but makes me bothered by the fact that I have the same code in two models.py but only have one operational table in the database. What is the correct way of dealing with this situation? -
'str' object has no attribute 'decode' on djangorestframework_simplejwt/backend.py
I am getting such error in my django rest framework project. Local working but live not working 'str' object has no attribute 'decode' I try pip install pyjwt==v1.7.1, pip install PyJWT==v1.7.1 , pip install PyJWT==1.7.1 and the problem persists. Didn't have any solution. The site is live as https. Urls.py from django.contrib import admin from django.urls import path, include from rest_framework_simplejwt import views as jwt_views from django.views.generic import TemplateView from rest_framework.authtoken import views from rest_framework_simplejwt.views import ( TokenObtainPairView, TokenRefreshView, ) urlpatterns = [ path('admin/', admin.site.urls), path('', TemplateView.as_view(template_name='index.html'), name='index'), path('api/customers/',include('customer.api.urls')), path('api/user/',include('account.api.urls')), path('api/user/login', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/user/refresh/', TokenRefreshView.as_view(), name='token_refresh'), ] Please help me -
Django modelAdmin create or update exist instance in creation form
I need a creation form in my model admin, so that if a user exists with that phone(email) use it or create a new one because I have an inline form that needs an instance of the user model. In the fact, I have a model that foreign key to the User Model I create an inline form for it, and its shows in my admin for the User model. And when I try to create a new user with a different unique field it's created as well with the inline data for it but when trying to create with field with the same unique its throws an error to me that the user with this data exists but I want in that situation use existing user and add inline data to that -
Pulling images from a hosting company to django project
I have recently put my website into production. I am using a company to host my projects on their servers and everything is working perfectly apart from when I upload images. The uploading its self works and they are uploaded to the base/static/images/images folder correctly. But the website its self when uploading through django admin are trying to pull the images from the public_html/images/images folder. What would I need to change for either the images to be pulled from correct folder or images to be uploaded to correct folder. Below is my settings for my static files. STATIC_URL = 'static/' MEDIA_URL = 'images/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')