Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SetPasswordForm: clean only if new_password1 or new_password2 field is set
I need to validate updatePasswordForm only if new_password1 or new_password2 are not empty. I want to make the password fields optional, these are only for update the password. The view not only has the updatePasswordForm form. I'm using the next approach: .forms class UpdatePasswordForm(SetPasswordForm): class Meta: model = Account fields = ("new_password1","new_password2") def __init__(self, *args, **kwargs): super(SetAdminPasswordForm, self).__init__(*args, **kwargs) self.fields['new_password1'].required = False self.fields['new_password2'].required = False .view (CBV): class AdminProfileUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = AdminProfile form_class = AdminProfileForm second_form_class = AccountForm third_forms_class = ModulesForm fourth_form_class = UpdatePasswordForm login_url = '/login/' redirect_field_name = 'redirect_to' def handle_no_permission(self): return HttpResponseRedirect(reverse_lazy('login')) def test_func(self): return is_admin_check(self.request.user) def get_context_data(self, **kwargs): context = super(AdminProfileUpdateView, self).get_context_data(**kwargs) if self.request.POST: context['form'] = AdminProfileForm(self.request.POST, instance=self.object) context['form2'] = self.second_form_class(self.request.POST, instance=self.object.account, prefix='account') context['form3'] = self.third_forms_class(self.request.POST, instance=self.object.modules, prefix='modules') context['form4'] = self.fourth_form_class(self.object.account, self.request.POST, prefix='password') else: context['form'] = AdminProfileForm(instance=self.object) if 'form2' not in context: context['form2'] = self.second_form_class(instance=self.object.account,prefix='account') if 'form3' not in context: context['form3'] = self.third_forms_class(instance=self.object.modules, prefix='modules') if 'form4' not in context: context['form4'] = self.fourth_form_class(user=self.object.account, prefix='password') return context def post(self, request, *args, **kwargs): self.object = self.get_object() current_profile = self.object form_class = self.get_form_class() form_profile = self.get_form(form_class) form2 = self.second_form_class(request.POST, instance=current_profile.account, prefix='account') form3 = self.third_forms_class(request.POST, instance=current_profile.modules, prefix='modules') form4 = self.fourth_form_class(self.object.account, request.POST, prefix='password') new_password1 = form4.data.get('password-new_password1') new_password2 = form4.data.get('password-new_password2') if form_profile.is_valid() … -
How to pass one MethodField data to another MethodFiels in django
I have a SerializerMethod field like below cal = models.SerializerMethodField('__getcal__') def __getcal__(self, obj): return obj*20 Now i want those data to be passed in another SerializerMethod and do some other calculation. something like this cal2 = models.SerializerMethodField('__getcaltwo__') def __getcaltwo__(self, obj): x = self.__getcal__(obj) return x*100 how can i achive this? -
DEBUG = TRUE in settings.py and "no urls are configured". However, they ARE configured
My urls are configured, yet it is displaying the standard success page for django. My app is listed in installed apps with the comma after it. My urls in both my src and application are configured, yet the program won't display. If you can help out I would appreciate it, bless. (https://i.stack.imgur.com/ZWskJ.png)(https://i.stack.imgur.com/yfJzX.png)(https://i.stack.imgur.com/fWaMk.png)(https://i.stack.imgur.com/SxVkk.png)(https://i.stack.imgur.com/CkFIF.png)(https://i.stack.imgur.com/3jMXW.png) I just have no clue why it will not portray my program. -
Django Model Mixin: Adding loggers to model save() and delete() using Mixins
I would like all my models to inherit from a single "loggingMixin" class. The problem is that, instead of using the save() defined in the LoggingMixin, the standard save() is used. (none of the print statements in the loggingmixin are executed and my traceback always referenced the object.save() from my views and not the error raised in the loggingmixin. all other logs works as they should and i can save and delete objects. but nothing gets logged. thanks in advance for the help! import logging logger = logging.getLogger(__name__) ## this file defines a mixin to logg all saves, updates, deletes and errors class LoggingMixin: def save(self, *args, **kwargs): try: print("---------------------------------------------------------------1") if hasattr(self.pk): print("---------------------------------------------------------------2") if self.pk is None: # Object is new print("---------------------------------------------------------------3") super(LoggingMixin, self).save(*args, **kwargs) logger.info(f"{self._meta.db_table} object saved: " + str(str(self).split('\n')[1])) else: # Object is being updated print("---------------------------------------------------------------4") super(LoggingMixin, self).save(*args, **kwargs) logger.info(f"{self._meta.db_table} object updated: " + str(str(self).split('\n')[1])) else: # Object is being updated print("---------------------------------------------------------------5") super(LoggingMixin, self).save(*args, **kwargs) logger.info(f"{self._meta.db_table} object updated: " + str(str(self).split('\n')[1])) # error when saving except Exception as e: print("-------------------------------------------------------------6") logger.error(f"Error saving {self._meta.db_table} object: " + str(str(self).split('\n')[1]) + f"Error: {e}") raise e def delete(self, *args, **kwargs): # delete log try: super(LoggingMixin, self).delete(*args, **kwargs) logger.info(f"{self._meta.db_table} object deleted. ID: {str(self.pk)}") … -
Mod_wsgi error (Getting error message in error_log)
Getting error message in error_log [Wed May 17 16:02:05.624941 2017] [:error] [pid 28655] [remote 10.10.10.48:148] mod_wsgi (pid=28655): Exception occurred processing WSGI script '/usr/share/ipa/wsgi.py'. [Wed May 17 16:02:05.625006 2017] [:error] [pid 28655] [remote 10.10.10.48:148] Traceback (most recent call last): ###wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'AdminPanel.settings') application = get_wsgi_application() ###xyz.conf <VirtualHost *:80> ServerAdmin admin@xyz.com ServerName xyz.com ServerAlias www.xyz.com DocumentRoot /home/abc/Disk1/andew/xyz/xyz ErrorLog /home/abc/Disk1/andew/xyz/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static/admin/ /home/abc/Disk1/andew/xyz/xyz/static/admin/ <Directory "/home/abc/Disk1/andew/xyz/xyz/static/admin"> Require all granted </Directory> Alias /static/ /home/abc/Disk1/andew/xyz/xyz/static/ <Directory /home/abc/Disk1/andew/xyz/xyz/static> Require all granted </Directory> Alias /media/ /home/abc/Disk1/andew/xyz/xyz/media/ <Directory /home/abc/Disk1/andew/xyz/xyz/media> Require all granted </Directory> <Directory /home/abc/Disk1/andew/xyz/xyz/AdminPanel> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess xyz.com python-path=/home/abc/Disk1/andew/xyz/xyz python-home=/home/abc/Disk1/andew/xyz/xyz/env WSGIApplicationGroup %{GLOBAL} WSGIProcessGroup xyz.com WSGIScriptAlias / /home/abc/Disk1/andew/xyz/xyz/AdminPanel/wsgi.py </VirtualHost> -
Search results doesn't show in the template (Django)
I am very new to Django and I am creating a very simple project. However, the "search" part of my project is having some issues. Every time I try to search, it redirect me to the search template but not showing the data from the database. No error message. Here's my code... models.py class Userprofile(models.Model): use_id = models.IntegerField() first_name = models.CharField(max_length = 50) last_name = models.CharField(max_length = 50) position = models.CharField(max_length = 50) email = models.CharField(max_length= 100) password = models.CharField(max_length= 100) def __str__(self): return self.first_name account_list.html This is the template where the search bar is located <div class="search"> <form method="post" action="{% url 'account_search' %}" autocomplete="off"> <br> {% csrf_token %} <input type="text" name="acc_search" placeholder="Search Account"> <input type="submit" name="submit" value="Search" style="width: 24%"></p> </form> </div> <hr> views.py def account_search(request): if request.method == "POST": account_search = request.POST.get('acc_search') accounts = Userprofile.objects.filter(use_id__contains=account_search) | Userprofile.objects.filter(first_name__contains=account_search) | Userprofile.objects.filter(last_name__contains=account_search) | Userprofile.objects.filter(position__contains=account_search) | Userprofile.objects.filter(email__contains=account_search) return render(request, 'core/account_search.html', {'account_search': account_search, 'accounts':accounts}) else: return render(request, 'core/account_search.html', {}) account_search.html ` {% if account_search %} <div class="main-right"> <div class="h-1"> <h1>'{{ account_search }}' in Accounts</h1> </div> <table rules="all" style="border: 1px"> <thead> <td>Personnel's ID</td> <td>Name</td> <td>Position</td> <td>Email</td> <td>Action</td> </thead> <tbody> {% for userprofile in userprofiles %} <tr> <td>{{ userprofile.use_id }}</td> <td>{{ userprofile.first_name }} {{ userprofile.last_name }}</td> … -
How do I add StackedInlines to another model when the model for the inlines has a foreignkey in it
I have created models for a an election project. I want the polling agent to collect and submit results from different parties. I want to add the VoteInline to the ElectionResult models so that the PollingAgent can fill in the result of the different party's and the votes scored. I have created the following models and admin but I am getting the following error. How do I solve this? class Election(models.Model): election_category = models.CharField(max_length=255) start_date = models.DateTimeField() end_date = models.DateTimeField() class PoliticalParty(models.Model): name = models.CharField(max_length=200) election = models.ForeignKey(Election, on_delete=models.CASCADE) class Candidate(models.Model): fullname = models.CharField(max_length=120) party = models.ForeignKey(PoliticalParty, on_delete=models.CASCADE) bio = models.TextField(blank=True, null=True) class PollingAgent(models.Model): candidate = models.ForeignKey(Candidate, on_delete=models.CASCADE) election = models.ForeignKey(Election, on_delete=models.CASCADE) fullname = models.CharField(max_length=120) phone = models.IntegerField() email = models.EmailField() class Vote(models.Model): party = models.ForeignKey(Candidate, on_delete=models.CASCADE) votes= models.IntegerField() class ElectionResult(models.Model): polling_agent = models.ForeignKey(PollingAgent, on_delete=models.CASCADE) votes = models.ForeignKey(Vote, on_delete=models.CASCADE) uploaded_on = models.DateTimeField(auto_now_add=True) class VoteInline(admin.StackedInline): model = Vote extra = 0 admin.site.register(Vote) @admin.register(ElectionResult) class ElectionResultAdmin(admin.ModelAdmin): inlines = [ VoteInline, ] ERRORS: <class 'dashboard.admin.VoteInline'>: (admin.E202) fk_name 'party' is not a ForeignKey to 'dashboard.ElectionResult'. -
How to Filter + select json inside Jsonfield in django-rest-framwork
In one colomn response is store like this :- Now i want to filter this response [ { "id": "A", "children": [ { "id": "propertyName#0", "index": 0, "label": "Property", }, { "id": "userName#0", "index": 1, "label": "Reported By", }, { "id": "textinput#0", "index": 2, "label": "Reported By Title", }, { "id": "dateinput", "index": 3, "label": "Date Reported", } ], "component": "sectionDivider" }, { "id": "B", "children": [ { "id": "propertyName#0", "index": 0, "label": "Property", }, { "id": "userName#0", "index": 1, "label": "Reported By", }, { "id": "textinput#0", "index": 2, "label": "Reported By Title", }, { "id": "dateinput", "index": 3, "label": "Date Reported", } ], "component": "sectionDivider" }, { "id": "C", "children": [ { "id": "propertyName#0", "index": 0, "label": "Property", }, { "id": "userName#0", "index": 1, "label": "Reported By", }, { "id": "textinput#0", "index": 2, "label": "Reported By Title", }, { "id": "dateinput", "index": 3, "label": "Date Reported", } ], "component": "sectionDivider" } ] I want to filter like this how can i get this response I have id for the check like id: "A", id :"B" should only filter A and B and inside A and B i also want to filter. [ { "id": "A", "children": [ { "id": … -
Django Mem Cache Through IIS - Not Working as Expected
I'm using Django with no caching options meaning it defaults to memory cache. Caching is simple: Set Cache cache.set('chart_' + str(chartId), chart, 3600) Reset Cache when model is saved @receiver(pre_save, sender=DashboardChart) def increment_dashboard_chart_version(sender, instance, **kwargs): instance.version = instance.version + 1 # Resets cache cache.set('chart_' + str(instance.pk), None, 3600) Access cache cache.get('chart_' + str(chartId)) I'm running Django in production through IIS. What I'm finding is if I save the Chart model, the cache gets reset as expected. However, when reloading the page a few times the chart varies at random between the old version and the new version. My suspicion is that the different IIS worker threads are keeping their own memory version of the cache. Meaning there is not one global cache shared between the different IIS worker threads. As I randomly reload the page, the worker access changes and the cache version I get back is different. Any idea if I'm on the right path and how to solve this issue ? -
Getting a use a thread or sync_to_async error
So Im working on a Django web chat. I just switched my db structure to be able to support groupchats. I changed the code so far and Im struggling to figure out how to fix the following error. django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. And here's my websocket_connect from consumers.py async def websocket_connect(self, event): print('connected', event) user = self.scope['user'] print(user.online) threads = Thread.objects.filter(participant__user=user).prefetch_related() for thread in threads: chat_room = f'user_chatroom_{thread.id}' self.chat_room = chat_room await self.channel_layer.group_add( chat_room, self.channel_name ) await self.send({ 'type': 'websocket.accept' }) I am happy for every answer! I tried to change the threads variable but I cannot change this since I need it. -
Django Adding to cart functionality
I have the model with the collection type and two collections. And now I am creating a button in js for it. But I am having difficulty getting the collection id and collection type into the view. This is the Order and OrderItem model class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=False) transaction_id = models.CharField(max_length=200, null=True) def __str__(self): return str(self.id) @property def get_cart_items(self): orderitems = self.orderitem_set.all() total = sum([item.quantity for item in orderitems]) return total def get_cart_total(self): total = 0 for item in self.orderitem_set.all(): total += item.get_total() return total class OrderItem(models.Model): ORDER_ITEM_TYPE = ( ('type1', 'Collection1'), ('type2', 'Collection2'), ) order = models.ForeignKey(Order, on_delete=models.CASCADE) collection_type = models.CharField(max_length=255, choices=ORDER_ITEM_TYPE) collection1 = models.ForeignKey(Collection1, on_delete=models.SET_NULL, null=True, blank=True) collection2 = models.ForeignKey(Collection2, on_delete=models.SET_NULL, null=True, blank=True) quantity = models.IntegerField() def get_total(self): if self.collection_type == "type1": return self.collection1.price * self.quantity elif self.collection_type == "type2": return self.collection2.price * self.quantity This is the view that update the cart Items def updateItem(request): data = json.loads(request.body) collection_id = data['collectionId'] collection_type = data['collection_type'] action = data['action'] customer = request.user.customer if collection_type == 'type1': collection = Collection1.objects.get(id=collection_id) elif collection_type == 'type2': collection = Collection2.objects.get(id=collection_id) order, created = Order.objects.get_or_create(customer=customer, complete=False) order_item, created = OrderItem.objects.get_or_create(order=order, collection_type=collection_type, collection1=collection, collection2=collection) … -
Django: Confusion with accessing database model's foreign key data
This is my first time working with Django and while working I have encountered with a confusion to create a particular statement in views that leads to my desired output. I have created a model 'Parents' which has data of a specific student (Foreign Key), and I am confused to access that student id for further process like working with Attendance, or Results of that specific student. Below are necessary codes and my trial to fetch data. Models.py class Students(models.Model): id = models.AutoField(primary_key=True) admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE) gender = models.CharField(max_length=50) address = models.TextField() course_id = models.ForeignKey(Courses, on_delete=models.DO_NOTHING, default=1) session_year_id = models.ForeignKey(SessionYearModel, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() def __str__(self): return self.admin.first_name + " " + self.admin.last_name class Parents(models.Model): id = models.AutoField(primary_key=True) admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE) gender = models.CharField(max_length=50) **student = models.ForeignKey(Students, on_delete=models.CASCADE)** relation = models.CharField(max_length=255) address = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() def __str__(self): return self.admin.first_name + " " + self.admin.last_name Here I have two models, Students model has all information regarding student and the other model is Parent model which has parent information with its specific student id. Below is the views file code where I am trying to fetch … -
nginx giving 502 Bad Gateway
I'm following this tutorial (with this repository) to deploy my Django project. I added nginx configuration as described, with all the files and directories seeming to match. The project I'm trying to deploy also has other dependencies like celery or selenium, but those work okay with docker-compose. When I run docker-compose up the app seems to start without errors (celery tasks are executed, etc.), and the proxy gives this log: suii-proxy-1 | 2023/01/26 08:43:00 [notice] 8#8: using the "epoll" event method suii-proxy-1 | 2023/01/26 08:43:00 [notice] 8#8: nginx/1.23.3 suii-proxy-1 | 2023/01/26 08:43:00 [notice] 8#8: built by gcc 12.2.1 20220924 (Alpine 12.2.1_git20220924-r4) suii-proxy-1 | 2023/01/26 08:43:00 [notice] 8#8: OS: Linux 5.15.49-linuxkit suii-proxy-1 | 2023/01/26 08:43:00 [notice] 8#8: getrlimit(RLIMIT_NOFILE): 1048576:1048576 suii-proxy-1 | 2023/01/26 08:43:00 [notice] 8#8: start worker processes suii-proxy-1 | 2023/01/26 08:43:00 [notice] 8#8: start worker process 9 suii-proxy-1 | 2023/01/26 08:43:00 [notice] 8#8: start worker process 10 suii-proxy-1 | 2023/01/26 08:43:00 [notice] 8#8: start worker process 11 suii-proxy-1 | 2023/01/26 08:43:00 [notice] 8#8: start worker process 12 suii-proxy-1 | 2023/01/26 08:43:00 [notice] 8#8: start worker process 13 But when trying to access to http://127.0.0.1 I get a 502 Bad Gateway like this: With this log error: suii-proxy-1 | 2023/01/27 07:10:28 … -
authenticate() is not validate data properly django
When I try to click on login button it always execute the invalid credentials instead of redirect to the index page.. What I did is that in database create table name signup and wants to validate all the data from that table.. Here signup_data function is works well but in login_data cannot authenticate the user. Models.py from django.db import models class signup(models.Model): username = models.CharField(max_length=10) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) email = models.EmailField() password = models.CharField(max_length=10) Forms.py from django.forms import ModelForm from . models import signup from django import forms class signupform(ModelForm): username= forms.CharField(max_length=10,widget=forms.TextInput(attrs={'class':'form-control'})) first_name = forms.CharField(max_length=20, widget=forms.TextInput(attrs={'class': 'form-control'})) last_name = forms.CharField(max_length=20,widget=forms.TextInput(attrs={'class': 'form-control'})) email = forms.EmailField(max_length=20,widget=forms.EmailInput(attrs={'class': 'form-control'})) password = forms.CharField(max_length=10,widget=forms.PasswordInput(attrs={'class':'form-control'})) class Meta: model = signup fields = '__all__' Views.py from django.shortcuts import render,redirect from . forms import signupform from . models import signup from django.contrib import messages from django.contrib.auth import login,authenticate def index(response): return render(response,'login_module/index.html') def signup_data(response): if response.method == 'POST': form = signupform(response.POST) if form.is_valid(): username = form.cleaned_data['username'] first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] email = form.cleaned_data['email'] password = form.cleaned_data['password'] if signup.objects.filter(username=username).exists(): # messages.add_message(response,messages.WARNING,'Username is already taken') messages.error(response,'Username is already taken') return redirect('signup') elif signup.objects.filter(email=email).exists(): messages.error(response,'Email is already taken') # messages.add_message(response,messages.WARNING,'Email is already taken') return redirect('signup') else: register_instance … -
Why does Docker compose work with local build and Dockerfile but fails when I use image
I am trying to dockerize a Django, Gunicorn, Nginx and PostgreSQL application. Everything works when I use local Dockerfile of my Django Project files using Docker Compose. enter image description here But when I built the image and push it to the Docker Hub and this time try to use image, it fails: enter image description here It gives me this error: enter image description here and when I try to check the app folder, it shows nothing there. This image works perfectly fine when I use the docker run -td armughanahmad/djangoapp:1.0 it works perfectly fine and even files are there: enter image description here enter image description here What could be the issue here? I was expecting to run as smoothly as local Dockerfile but it didn't work -
unknown field error don't know where it is , django.core.exceptions.FieldError: Unknown field(s)
class ManageKnowledgeProductTrainingType(models.Model): training_type = models.CharField(max_length=200, blank=False, null=False,default='', verbose_name="Training Type") product = models.ForeignKey(ManageProductName, on_delete=models.SET_NULL, blank=False, null=True, verbose_name="Product") nature_of_training = models.CharField(max_length=200, blank=False, null=False,default='', verbose_name="Nature of Training") training_name = models.CharField(max_length=200, blank=False, null=False,default='', verbose_name="Training Name") title = models.CharField(max_length=200, blank=False, null=False, default='', verbose_name="Title") purpose = models.CharField(max_length=200, blank=False, null=False,default='', verbose_name="Purpose of Training") start_date = models.DateField(blank=True, null=True, verbose_name="Start Date") upload_documents = models.FileField(upload_to='product_training/%Y/%m/%d/',null=True, verbose_name="Upload Documents") is_active = models.BooleanField(default=1, verbose_name="Is Active") added = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.training_type class Meta: db_table = "manage_knowledge_product_training_type" unique_together= ('training_type', 'product', 'nature_of_training', 'training_name') django.core.exceptions.FieldError: Unknown field(s) (chapter) specified for ManageKnowledgeProductTrainingType -
How to write file docker-compose and dockerfie for Django connect Kong api
I'm doing a graduation project, and I'm about to put my project up to the server, but I'm having trouble with docker-compose and dockerfile files, could you please advise me where I should fix it? I experimented with writing, but there are still problems in the kong image docker. It crashes, doesn't always work. How should I fix this? Can you suggest writing these files for me? Thank you. dockerfile files WORKDIR /app COPY requirements.txt . RUN pip install -r requirements.txt EXPOSE 8000 CMD ["python3", "manage.py", "runserver", "0.0.0.0:8000"]``` docker-compose files ```version: '3.9' services: kong-database: image: postgres:latest container_name: kong-database restart: always ports: - 15432:5432 networks: - default volumes: - db:/var/lib/postgresql/data environment: - POSTGRES_DB=kong - POSTGRES_USER=kong - POSTGRES_PASSWORD=kong kong: image: kong:latest container_name: kong restart: always ports: - 18000:8000 - 18443:8443 - 127.0.0.1:8001:8001 - 18444:8444 links: - kong-database:kong-database networks: - default environment: - LC_CTYPE=en_US.UTF-8 - LC_ALL=en_US.UTF-8 - KONG_DATABASE=postgres - KONG_PG_HOST=kong-database - KONG_PG_USER=kong - KONG_PG_PASSWORD=kong - KONG_CASSANDRA_CONTACT_POINTS=kong-database - KONG_PROXY_ACCESS_LOG=/dev/stdout - KONG_ADMIN_ACCESS_LOG=/dev/stdout - KONG_PROXY_ERROR_LOG=/dev/stderr - KONG_ADMIN_ERROR_LOG=/dev/stderr - KONG_ADMIN_LISTEN=0.0.0.0:18001, 0.0.0.0:18444 ssl konga: image: pantsel/konga container_name: kong-konga restart: always ports: - 1337:1337 networks: - default volumes: - data:/app/kongadata links: - kong:kong environment: - NODE_ENV=production networks: default: driver: bridge volumes: db: driver: local data: driver: local setting.py ```DATABASES … -
Autocomplete from jQuery returns Label values, I would like to return the values
I am having trouble getting the auto-complete wrapper getting filled with the values, not the labels $(document).ready(function() { $('#id_name').autocomplete({ source: function(request, response) { $.ajax({ url: "{% url 'proiecte:autocomplete' %}", dataType: "json", data: { term: request.term }, success: function(data) { response($.map(data.name, function(value, key) { return { value: data.name[key], label: data.id[key], } })); } }); },[enter image description here][1] }) }); I've added an image for example, the auto-complete should show text values not numbers -
Getting photo url in Django backend and displaying the photo in React frontend
I'm trying to get the url of my photos in the Django backend and send it to the react frontend using axios. I got the url printed in the console in the frontend but when I put the url as a src in an img tag, the image shows up as a blue question mark. What am I missing? Initially it was a cors error, I changed my backend configurations and even disabled cors on safari but nothing worked. I made the photo shareable and tried hard coding the link and that also didn't work. I think I'm supposed to pass the oauth to the frontend as well but I'm not exactly sure how -
Django: converting view function to class-based view. Error during login to Admin panel: matching query does not exist
I'm learning how to convert old view.py functions to class-based views. I started with a simple function that displayed a page with my essays, plus, I had a newsletter form and a draft of a comment form (but not attached to DB). I decided to not develop this comment form further in a simple function, but to rebuild all of it to class-based view to learn a better and cleaner approach. I've encountered a problem that I have no idea how to solve. Error: matching query does not exist. And Exception Value: EssayCls matching query does not exist. Most likely I break the logic that connects my model to my DB. I'm looking for suggestions on how to solve issues in my code and suggestions about topics I should learn more about to make this kind of development less cumbersome. Before I rebuild my view, things were working fine and looked like this: views.py: from django_user_agents.utils import get_user_agent from .models import EssayCls, SendMeMessage from .forms import CommentForm def my_essays(request, home_view_author_slug): user_agent = get_user_agent(request) try: selected_essay = EssayCls.objects.get(slug=home_view_author_slug) if request.method == 'GET': user_feeDBack = UserFeeDBack() else: """ The incoming request from Django will have a POST property which contains any submitted … -
Search results doesn't show in the template (Django)
I am new to Django and I am creating a very simple project. However, the "search" part of my project is having some issues. Every time I try to search, it redirect me to the search template but not showing the data from the database. No error message. Here's my code... models.py class Event(models.Model): eventname = models.CharField(max_length = 100) class months(models.TextChoices): JANUARY = 'January', _('January') FEBRUARY = 'February', _('February') MARCH = 'March', _('March') APRIL = 'April', _('April') MAY = 'May', _('May') JUNE = 'June', _('June') JULY = 'July', _('July') AUGUST = 'August', _('August') SEPTEMBER = 'September', _('September') OCTOBER = 'October', _('October') NOVEMBER = 'November', _('November') DECEMBER = 'December', _('December') month = models.CharField( max_length= 10, choices=months.choices, default=months.JANUARY, ) day = models.IntegerField() year = models.IntegerField() area = models.ForeignKey(Area, related_name = 'events', blank=True, null=True, on_delete = models.CASCADE) guest = models.ForeignKey(Guest, related_name = 'events', on_delete = models.CASCADE) recorded_by = models.ForeignKey(Userprofile, related_name = 'events', on_delete = models.CASCADE) def __str__(self): return self.eventname search_bar.html #the search bar in the template <div class="search"> <form method="post" action="{% url 'event_search' %}" autocomplete="off"> <br> {% csrf_token %} <input type="text" name="event_srch" placeholder="Search Event"> <input type="submit" name="submit" value="Search" style="width: 24%"></p> </form> </div> views.py def event_search(request): if request.method == "POST": event_search = request.POST.get('event_srch') events … -
How do i show related foreign key in django query set?
I'm new to django, and i want to show field that related to foreign key in another table. this is the table. i want to career table got the career_tag_name and hex_code from table color. i've tried the Career.objects.raw() this is the query in views.py: careers = Career.objects.raw('''SELECT website_career_tag.career_tag_name,website_color.hex_code, website_career.* from website_career INNER JOIN website_career_tag on website_career_tag.id = website_career.career_tag_id_id LEFT JOIN website_color on website_career_tag.color_id_id = website_color.ID''') it works perfectly, until i want to use filter() by career_tag_name. when i use query set it's more easy than make it raw to filter. how do i make those raw query to query set? -
Django keyword error but print kwargs shows the key
I have this URL and I send the currently logged in user's id (viewer (33)) and the id of the user being looked at (user (1)) in the URL: path("users/<int:viewer>/<int:user>/profile/", OtherProfile.as_view()), Here is the view handling that URL: class OtherProfile(generics.RetrieveAPIView): permission_classes = [permissions.IsAuthenticated] serializer_class = ProfileSerializer name = "other-profile" lookup_field = "user" def get_queryset(self): breakpoint() viewer = self.kwargs["viewer"] user = self.kwargs["user"] return Profile.objects.all().filter(user_id=user) There is a breakpoint here and the result of print(self.kwargs["viewer"]) gives 33 which is correct print(self.kwargs["user"]) gives 1 which is also correct Here is the profile serializer as specified in the serializer_class: class ProfileSerializer(serializers.ModelSerializer): location = serializers.SerializerMethodField() user = UserSerializer() followers = serializers.SerializerMethodField() class Meta: model = Profile fields = [ "id", "background", "photo", "first_name", "middle_name", "last_name", "birthdate", "gender", "bio", "occupation", "is_verified", "verification", "website", "location", "user", "followers", "created_at", "updated_at", ] def get_location(self, obj): location_obj = Location.objects.filter(profile=obj.id) if location_obj: location_obj = Location.objects.get(profile=obj.id) location = LocationSerializer(location_obj) return location.data def get_followers(self, obj): breakpoint() followers = Follow.objects.filter(followee=obj.user.id) return followers.count() I put a breakpoint on the get_followers method so I can look at the data. print(self.context["view"].kwargs) - prints ["viewer", "user"] My question: Why does print(self.context["view"].kwargs["user"]) print 33 when on the view the kwargs user should be 1? Why does it give me … -
I can´t publish MQTT messages after a few days
I'm using "mqttasgi" as library with Django justo to listen and posting many messages. However, for some reason after a few days it is no longer possible to continue posting messages. It should be noted that I am using the amazon login with "mqttasgi" and a level 1 of QO(because AWS doesn't allow a level 2 of QO). This is my procfile mqttasgi -H $MQTT_URL -p $MQTT_PORT -v 2 -C $TLS_CERT -K $TLS_KEY -S $TLS_CA iot_stracontech.asgi:application``` and this is my consumer.py from mqttasgi.consumers import MqttConsumer from mqtt_handler.tasks import processmqttmessage import json class MyMqttConsumer(MqttConsumer): async def connect(self): await self.subscribe('tpx/things/+/uplink', 0) await self.channel_layer.group_add("stracontech", self.channel_name) async def receive(self, mqtt_message): print('Received a message at topic:', mqtt_message['topic']) print('With payload', mqtt_message['payload']) print('And QOS:', mqtt_message['qos']) dictresult = json.loads(mqtt_message['payload']) jsonresult = json.dumps(dictresult) processmqttmessage.delay(jsonresult, mqtt_message['topic']) pass async def publish_results(self, event): data = event['result'] await self.publish("stracontech/procesed/" + event['result']['device_id'] + "/result", json.dumps(data).encode('utf-8'), qos=1, retain=False) async def disconnect(self): await self.unsubscribe('tpx/things/+/uplink') I want to know if exist a way to know why does it stop publishing messages, anyway to do a debug or see the logs? Pd: @Santiago Ivulich maybe you can give me a hand with that. -
how can i filter variants (size - color ) when select size product show color product ,who saved in database in django?
yacine amateur in django welcome everybody I'm about to complete my first project, in webbing I ran into a problem, frankly, that I couldn't solve I simply face a problem when I open the page for a specific product, and select a specific size, the colors do not change according to what is stored in databases according to each size for example **product 1** **size**: s l m xl **color**: red black yellow if i save variant for **product 1** as **size**: xl with **color**: red when i select **size** in product-sidebare.html i can not show just **color** red that is my code model.py class Add_Product(models.Model): STATUS = ( ('True', 'True'), ('False', 'False'), ) VARIANTS = ( ('None', 'None'), ('Size', 'Size'), ('Color', 'Color'), ('Size-Color', 'Size-Color'), ) article_author = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Category, max_length=200, on_delete=models.CASCADE) title = models.CharField('العنوان', max_length=9500) slug = models.SlugField(max_length=250, allow_unicode=True, unique =True) image = models.FileField( upload_to = 'Images', blank=True) price = models.DecimalField(max_digits=12, decimal_places=2,default=0) variant=models.CharField(max_length=10,choices=VARIANTS, default='None') posted_on = models.DateTimeField(auto_now=False, auto_now_add=True) updated_on = models.DateTimeField(auto_now=True, auto_now_add=False) read = models.PositiveIntegerField(default=0, verbose_name='Vu') publish = models.DateTimeField(default=timezone.now) def __str__(self): return self.title def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Add_Product, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('home:show_product', kwargs={'id':self.id, 'slug': self.slug}) class PostImage(models.Model): post_images …