Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use Django roles for a SaaS product with an admin portal?
I would try to explain our desired product idea as clear as possible but feel free to ask further questions. So, basically what we want to build is a SaaS product that will be used by multiple clients. For now, we're not interested in custom domains like (cust1.myproduct.com, cust2.myproduct.com) and we will simply be using one database to manage all customers' data. So far so good. Our SaaS product will be sold to enterprise organizations which will then be used by their employees. So for any one customer organization, there are three types of roles that we would like to provide their users, as follows: Admin: An organization's admin that should be able to do all the settings for that particular organization Manager: An organization's manager that can manage the users that are under his/her team Employee: A normal user with bare minimal permissions that can only manage his own data Now, to provision customers for this SaaS product and to set their global settings (e.g. maximum allowed users, license type etc), we also plan to create an admin portal and APIs that will be used by our internal employees only. For this portal, we also want to define roles … -
VPS is unaccessible through ssh and cant connect website
the problem is the connection to my vps is lost on daily basis multiple times like 20 mins. When the server is down i can't connect website so i get the error: Err connection timed out. and i try connecting through ssh and it outputs a log: Connection refused. Nothing more nothing less i should solve this because it causes lots of trouble the only solution i came up with its restarting from the server provider site. But this happens frequently not one in a month or a year it happens 10 times a day. How should i debug the problem or how can i find a real solution. Any help is appreciated. Thanks. -
NoReverseMatch at /project/836d5772-26da-4a9b-811c-806af5b10a41/
.I got this error on the projects page; Reverse for 'edit-project' with arguments '('',)' not found. 1 pattern(s) tried: ['edit\-project/(?P[^/]+)/$']. I'm trying to create an edit view for the projects My views.py from django.shortcuts import render, redirect from .models import Project, Skill from .forms import ProjectForm # Create your views here. # rendering our home template def homePage(request): projects = Project.objects.all() skills = Skill.objects.exclude(body="") otherSkills = Skill.objects.filter(body="") context = { "Projects": projects, "Skills": skills, "Others": otherSkills, } return render(request, "base/home.html", context) # creating a view for the projects template def projectsPage(request, pk): project = Project.objects.get(id=pk) # querying the object by its id context = { "Project": project, } return render(request, "base/projects.html", context) # creating a view for project_form template def addProject(request): form = ProjectForm() # If request method is equal to POST, submit this form if request.method == "POST": # pass in the original post data and any files send from the frontend(we're sending files right to enctype) form = ProjectForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect("home") context = { "Form": form, } return render(request, "base/project_form.html", context) # creating a view for project_form template def editProject(request, pk): project = Project.objects.get(id=pk) form = ProjectForm(instance=project) if request.method == "POST": form = ProjectForm(request.POST, … -
How to set an owner of created object by default in DRF?
I want to save my car object with request.user as owner (field in Car model). My code: views.py class CarViewSet(viewsets.ModelViewSet): serializer_class = CarSerializer queryset = Car.objects.all() lookup_field = 'slug' permissions_classes = [IsAuthenticated] def perform_create(self, serializer): serializer.save(owner=self.request.user) def get_queryset(self, *args, **kwargs): print(self.request.user.email) print(self.request.user.is_authenticated) return self.queryset.filter(owner=self.request.user.pk) When I visit my frontend page, I have a list of my cars displayed. email and is_authenticated (True) fields are printed correctly. Everything is ok until I try to refresh the page - the data disappears and I get an error: print(self.request.user.email) AttributeError: 'AnonymousUser' object has no attribute 'email' is_authenticated field is set to False respectively. I have also tried including owner field to CarSerializer: owner = serializers.HiddenField(default=serializers.CurrentUserDefault()) But nothing changed. How can I fix that? -
ValueError("No text section for incoming WebSocket frame!") Swift to DRF
Im trying to make a realtime messaging app using swift and django's rest framework. To make the app 'real time', I am incorporating Django channels. Right now when I send message data to my consumer, I get the error ValueError("No text section for incoming WebSocket frame!") Here is my django code: class MessageConsumer(AsyncJsonWebsocketConsumer): #connect to client async def connect(self): await self.accept() await self.send_json(content="Pong") query_string = self.scope['query_string'] self.conversation_id = int(query_string[16:].strip()) self.new_group_name = 'Conversation_' + str(self.conversation_id) await self.channel_layer.group_add(self.new_group_name, self.channel_name) # all_msgs = await self.get_conversation_messages() # await self.send_json(content=all_msgs) @database_sync_to_async def get_conversation_messages(self): conversation = Conversation.objects.get(conversation_id=self.conversation_id) messages = conversation.message_set.all() serializer = GetMessagesSerializer(messages,many=True) return serializer.data @database_sync_to_async def send_message(self, data): serializer = SendMessageSerializer(data=data) if serializer.is_valid(): serializer.save() return serializer.data raise ValueError('serializer is not valid') async def receive_json(self, content): serialized_message = await self.send_message(data=content) await self.send_json(content=serialized_message) async def disconnect(self, code): await self.channel_layer.group_discard(self.new_group_name, self.channel_name) await self.close() Here is my swift code: private func encodeMessageData(_ data: SendMessageStruct) -> Data? { guard let encodedData = try? JSONEncoder().encode(data) else { print("failed to encode message data") return nil } return encodedData } let webSocketMessage = URLSessionWebSocketTask.Message.data(encodedData) webSocketTask.send(webSocketMessage) { error in guard error == nil else { if let error = error { print("error in websocket task ERROR: \(error.localizedDescription)") } completion(.failure(AuthErrors.taskFailed)) return } print("sent websocket data") … -
can not upload image using Django-CKEditor (Error 400)
when I want to upload an image in CKEditor, it gives me the Error "HTTP error occurred during file upload (error status: 400)." enter image description here inside urls.py from django.contrib import admin from django.urls import path,include from django.conf import settings from django.conf.urls import url from django.conf.urls.i18n import i18n_patterns from django.conf.urls.static import static urlpatterns = i18n_patterns( url(r'^admin/clearcache/', include('clearcache.urls')), path('admin/', admin.site.urls), path('', include('frontpages.urls')), path('ckeditor/',include('ckeditor_uploader.urls')), path('i18n/', include('django.conf.urls.i18n')), prefix_default_language=False, ) handler404='frontpages.views.error_404_view' if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) inside settings.py ---> for CKEDITOR #Ckeditor CKEDITOR_IMAGE_BACKEND = "pillow" CKEDITOR_UPLOAD_PATH="uploads/" CKEDITOR_CONFIGS={ 'myconfig':{ 'toolbar':"Custom", 'toolbar_Custom':[ ['Styles','Format','Font','FontSize','BidiLtr','BidiRtl'], ['JustifyLeft','JustifyCenter','JustifyRight','NumberedList', 'BulletedList','Bold','Italic','Underline','Strike','Undo','Redo'], ['Link','Unlink','Anchor'], ['TextColor','BGColor'], ['Smilely','SpecialChar'], ['Source','Scayt','Maximize'], ['Table','Templates','Iframe'], ], 'height': 100, }, } would you please help me with that -
How can I use function based view to make operations in a object with a modal?
I'm creating a website with a list of candidates where staff members can increment the grade of candidates by clicking in validate. I would like to increment the value of grade when I click on validate in the modal. It works because I can see in the admin panel that the grade of the candidate has been incremented but it does not redirect me in the list of candidates that was before. How can I do to redirect to the list of candidates that was before ? Here is the template displaying the list of candidates and the script displaying the modal : <table id="students-table" class="table"> <thead> </thead> <tbody> {% for student in student_list %} <tr> <td> <button type="button" class="validate-student bs-modal btn btn-sm btn-primary" data-form-url="{% url 'students:validate_grade' student.pk %}"> <span class="fa fa-eye"></span> </button> </td> </tr> {% endfor %} </tbody> <script type="text/javascript"> $(function () { $(".validate-student").each(function () { $(this).modalForm({ formURL: $(this).data("form-url")}); }); }); Here is the modal : {% load widget_tweaks %} <form method="POST" action=""> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel"><strong>{{ student.user.firstname }} {{ student.user.lastname }}</strong></h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <p>Are you sure to validate this candidate ? ? </p> </div> <div class="modal-footer"> <button type="submit" … -
Image print issue in HTML using Django
I have recently started working with Python Django. I created a home page and it worked fine. But now I created another html template product.html and followed the same steps but the images weren't loading even though both the html files were in the same directory. I tried printing image product-1.jpeg in home page and it worked but in the other html page it isn't working. All the CSS are working fine. I don't know what am I doing wrong here. product.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="shortcut icon" type="image/png" href='{% static "images/favicon.ico" %}'/> </head> <body> <p style="color:red;">Hello</p> <img src="static/images/product-1.jpeg" alt="Product 1"/> </body> </html> Terminal Response It's showing Product/static/images/product-1.jpeg but what I typed was static/images/product-1.jpeg I don't know where's the error. [17/Oct/2021 00:42:21] "GET /Product/ HTTP/1.1" 200 416 Not Found: /Product/static/images/product-1.jpeg [17/Oct/2021 00:42:21] "GET /Product/static/images/product-1.jpeg HTTP/1.1" 404 2899 [17/Oct/2021 00:42:22] "GET /static/images/favicon.ico HTTP/1.1" 200 15406 [17/Oct/2021 00:49:31] "GET /Product/ HTTP/1.1" 200 442 Website Display Web Page View Let me know, if I need to upload other codes (urls.py, views.py, settings.py, etc. Btw home.html was working fine) -
How can i send mail to class values
how can I send the field information in my form on django as an e-mail at the same time? def gcreate(request): if request.method == 'POST': gmember = gunluk( adsoyad=request.POST['adsoyad'], adsoyad2=request.POST['adsoyad2'], vardiya=request.POST['vardiya'], aciklama=request.POST['aciklama'], incident=request.POST['incident'], alinanaksiyon=request.POST['alinanaksiyon'], ulasilmayanekip=request.POST['ulasilmayanekip'], ulasilmayanbilgisi=request.POST['ulasilmayanbilgisi'],) try: gmember.full_clean() except ValidationError as e: pass gmember.save() messages.success(request, 'Ekleme İşlemi Başarılı!') return redirect('/gunlukistakibi') else: return render(request, 'gcreate.html') -
queries of Foreinkey
i am currently trying to make a django project but i am stuck class Klasse(models.Model): klasse = models.CharField(max_length=60, null=True) def __str__(self): return self.klasse class Lehrer(models.Model): Name_und_Nachname = models.CharField(max_length=200, null=True) Klassenlehrer_von = models.ForeignKey(Klasse, max_length=200, null=True, on_delete=models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.Name_und_Nachname class Schüler(models.Model): name_und_Nachname = models.CharField(max_length=200, null=True) Klasse = models.ForeignKey(Klasse, max_length=200, null=True, on_delete=models.SET_NULL) Klassenlehrer = models.ForeignKey(Lehrer, max_length=200, null=True, on_delete=models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.name_und_Nachname class Punkte(models.Model): punkte_ang = (("0", 0),("1", 1), ("2", 2), ("3", 3), ("4", 4), ("5", 5)) punkte_norm = (("0", 0),("1", 1)) Soziales_angagement = models.CharField( max_length=200, null=True, choices=punkte_ang,) Lernverhalten = models.CharField(max_length=200, null=True, choices=punkte_norm, ) Sozialverhalten = models.CharField(max_length=200, null=True, choices=punkte_norm,) konfliktlösung = models.CharField(max_length=200, null=True,choices=punkte_norm, ) eingentum_anderer = models.CharField( max_length=200, null=True, choices=punkte_norm,) date_created = models.DateTimeField(auto_now_add=True, null=True) so to the code i wanna say i know its not the most beautiful and not the best one. So back to my question i need a way to connect the foreinkeys betwen the students = Schüler and the Teachers = Lehrer i thaught i could make this with querying the Klasses and if the student and the teacher have the same class they get linked. is there any way to do this? -
Django problem accessing a field from view in the autocomplete
I'm using django-autocomplete-light in my project, but I'm with some problems passing an argument from my view (the argument is also in my URL) to the autocomplete Select2QuerySetView. What is the correct way to do it? My view has a period_id that I'm passing to my form by this way: def add_equipment_config(request, tower_id, period_id): ... form = EquipmentConfigForm(period_id=period_id) ... return render(request, 'add_equipment_config.html', {'form': form, 'tower_id': tower_id, 'period_id': period_id, 'conf_period': conf_period}) In my form I get the period_id inside the init: class EquipmentConfigForm(ModelForm): class Meta: model = EquipmentConfig fields = '__all__' period_id = 0 def __init__(self, *args, **kwargs): period_id = kwargs.pop('period_id') ... calibration = forms.ModelChoiceField( queryset=Calibration.objects.all().order_by('-id'), widget=autocomplete.ModelSelect2(url='calibration-autocomplete', forward=['period_id'], attrs={'style': 'width:100%'}) ) But I'm not able to pass the period_id inside the forward. Inside the Select2QuerySetView I'm always getting the value as None: class CalibrationAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): print(self.forwarded.get('period_id', None)) // Here I get None ... Can someone please help me with this? How can I get the period_id inside the Select2QuerySetView? Im struggling to find this solution. -
Django REST (DRF) - How to setup nice execptions in api_views?
I have the following API view and serializer to change a users password: views.py @api_view(['POST']) @permission_classes([AllowAny]) def user_create(request): exception_handler = UserUnavailable success_handler = UserCreated if request.method == 'POST': creation_serializer = UserCreateSerializer(data=request.data) try: if creation_serializer.is_valid(raise_exception=True): creation_serializer.save() user_serializer = NewUserSerializer(instance=creation_serializer.instance) return JsonResponse( {"status_code": success_handler.status_code, "default_detail": success_handler.default_detail, "default_code": success_handler.default_code, "new_user": user_serializer.data, }, status=status.HTTP_201_CREATED, safe=False) except APIException: return Response( {"status_code": exception_handler.status_code, "default_detail": exception_handler.default_detail, "default_code": exception_handler.default_code}, status=status.HTTP_400_BAD_REQUEST ) serializers.py class UserPasswordSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) password = serializers.CharField(max_length=128, write_only=True, required=True, validators=[validate_password]) password2 = serializers.CharField(max_length=128, required=True) old_password = serializers.CharField(max_length=128, required=True) class Meta: model = get_user_model() fields = ('user', 'password', 'password2', 'old_password') extra_kwargs = {'password': {'write_only': True}} def validate_old_password(self, value): user = self.context['request'].user if not user.check_password(value): raise serializers.ValidationError( ({'old_password': _("Your old password was entered incorrectly. Please enter it again..")}) ) return value def validate(self, data): if data['password'] != data['password2']: raise serializers.ValidationError({'password2': _("The two password fields didn't match.")}) password_validation.validate_password(data['password']) return data def save(self, **kwargs): password = self.validated_data['password'] user = self.context['request'].user user.set_password(password) user.save() return user If I update a users password I simply get back http200 and the password has been set, nice! But if I send the same request a second time I just get back: { "status": "error", "error": "Bad Request" } Actually I would expect to … -
Conditional rendering of the Bookmark Button in React + Django Rest Framework
Hello? I am working on an ecommerce project and I want to render the Bookmark button conditionally to display that if a user saves a product the Bookmark button innerHTML changes from "Not Saved" to "Saved" in the frontend (React). The backend (Django) is working and user's bookmarks are being saved in the backend. In React I have used the following approach. {product.bookmarks && product.bookmarks.find(bookmark => bookmark.id === user.id) ? <p>Saved</p> : <p>Not Saved</p>} So it matches the Bookmark ID with the logged User's ID. The button is working and if a user saves a product it returns "Saved" in the frontend and if not saved it returns "Not Saved". Is this the best approach to use or there's a better method? I have also tried this approach in Django and it returns the data but I'm not sure how to use the data in React to render the button. @api_view(['POST']) @permission_classes([permissions.IsAuthenticated]) def add_bookmarks(request, id, *args, **kwargs): saved = bool product = get_object_or_404(Product, id=id) if product.bookmarks.filter(id=request.user.id).exists(): saved = False product.bookmarks.remove(request.user) else: saved = True product.bookmarks.add(request.user) data = { 'saved': saved } print(data) return Response(data, status=status.HTTP_200_OK) -
Django: counts forms submitted
What I'd like to do with my model is to have and HTML page where to show my users how many question form they have submitted and how much they are still missing (I've five in my original template here I'm repoprting only two) and also for the admin to see how many users in total submitted the forms so this is my code: **HTML** {% extends "base.html" %} {% block content %} <main> <div class="container"> <div class="table-responsive text-nowrap"> <h2>Submission</h2> Total: {{ quest_done }}/2 {% if user.is_superuser %} Total Question 1: {{ question1_count }} Total Question 2: {{ question2_count }} {% endif %} </div> </main> {% endblock %} **question.models.py** class QuestionOne(models.Model): user = models.OneToOneField(UserInformation, blank=True, null=True, on_delete=models.CASCADE) question_1a = models.CharField(max_length=250, choices=point) question_2a = models.CharField(max_length=250, choices=point) question_3a = models.CharField(max_length=250, choices=point) quest_1_submitted = models.BooleanField(default=False) def __str__(self): return self.name + '_question_1' class QuestionTwo(models.Model): user = models.OneToOneField(UserInformation, blank=True, null=True, on_delete=models.CASCADE) question_1b = models.CharField(max_length=250, choices=point) question_2b = models.CharField(max_length=250, choices=point) question_3b = models.CharField(max_length=250, choices=point) quest_2_submitted = models.BooleanField(default=False) def __str__(self): return self.name + '_question_2' **question.views.py** quest_done = 0 quest_count = 0 def question_one(request): if request.method == 'POST': form = QuestionOneForm(request.POST, request.FILES) if form.is_valid(): questionnairename.quest_1_submitted = True question1_count = QuestionOne.objects.all().count() form.instance.user = request.user form.save() messages.success(request, 'Form submitted') if … -
?: (urls.E006) The STATIC_URL setting must end with a slash
I was trying to migrate my new schema for my database in django when I got this error: AttributeError: 'PosixPath' object has no attribute 'startswith' I looked online and I saw that if you wrap your paths with str(), the error goes away. But then I got this error: ?: (urls.E006) The STATIC_URL setting must end with a slash. I tried doing the obvious thing and changing STATIC_URL = BASE_DIR.parent / "svelte" / "public"(what I think was causing the error) That didn't work, so I tried STATIC_URL = BASE_DIR.parent / "svelte" / "public" /. That also didn't work, so know I need help. -
Getting ValueError rending my Django CreateView
I am trying to render out my generic create view for django and I cannot do so as I am getting the error "ValueError at /teacher/add/" "Field 'id' expected a number but got 'add'." I am not sure what the problem would be here. models.py from django.db import models from django.urls import reverse # Create your models here. DEPARTMENT_CHOICES = [ ('Social Studies', 'Social Studies'), ('Math', 'Math'), ('Science', 'Science'), ] class Department(models.Model): name = models.CharField(choices=DEPARTMENT_CHOICES, max_length=300) def __str__(self): return self.name class Teacher(models.Model): name = models.CharField(max_length=300) # delete dept == delete teacher department = models.ForeignKey(Department, on_delete=models.CASCADE) tenure = models.BooleanField() def __str__(self): return f'{self.name} teaches {self.department}' # dont need success url if get_absolute_url on create and update view def get_absolute_url(self): return reverse('teacher-detail', kwargs={'pk': self.pk}) urls.py urlpatterns = [ path('teacher/add/', TeacherCreateView.as_view(), name='teacher-add'), ] views.py class TeacherCreateView(CreateView): model = Teacher fields = ['name'] -
Django Invalid block tag on line 17: 'provider_login_url', expected 'endblock'. Did you forget to register or load this tag?
I am using the following tutorial:. As the topic name suggests , I got an error : Invalid block tag on line 17: 'provider_login_url', expected 'endblock'. Did you forget to register or load this tag? The following div has the error . <div class="signin text-center"> <a href="{% provider_login_url 'google' %}" class="text-dark"> <!--Error is here--> <img src="{% static "btn_google_signin_light_normal_web@2x.png"%}"style="width:14rem; height:auto"> </a> </div> Thanks. -
How can i send mail form submittion in Django
I want to send the data I added to the table as an e-mail at the same time, how can I do this? When i put the "send_mail(adsoyad, aciklama, alinanaksiyon, ['admin@example.com'])" after try methot in view its getting error with definitions. views; from django.core.mail import send_mail def gcreate(request): if request.method == 'POST': gmember = gunluk( adsoyad=request.POST['adsoyad'], adsoyad2=request.POST['adsoyad2'], vardiya=request.POST['vardiya'], aciklama=request.POST['aciklama'], incident=request.POST['incident'], alinanaksiyon=request.POST['alinanaksiyon'], ulasilmayanekip=request.POST['ulasilmayanekip'], ulasilmayanbilgisi=request.POST['ulasilmayanbilgisi'],) try: gmember.full_clean() send_mail(subject, message, from_email, ['admin@example.com']) except ValidationError as e: pass gmember.save() messages.success(request, 'Ekleme İşlemi Başarılı!') return redirect('/gunlukistakibi') else: return render(request, 'gcreate.html') settings.py; EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'XX' EMAIL_HOST_PASSWORD = 'XX' -
pivottable.js not showing properly in django project
I am testing pivottable.js in a django project, here is the code I am using in the HTML template: {% load static %} {% block content %} <script src={% static 'js/jquery-3.6.0.min.js' %}></script> <script src={% static 'js/jqueryui/jquery-ui.min.js' %}></script> <script type="text/javascript" src={% static 'pivot/dist/pivot.min.js' %}></script> <script type="text/javascript"> $(function() { $("#output").pivotUI( [ {color: "blue", shape: "circle"}, {color: "red", shape: "triangle"}, {color: "red", shape: "triangle"}, {color: "red", shape: "circle"}, {color: "red", shape: "circle"}, {color: "red", shape: "triangle"}, ], ); }); </script> <div id="output" style="margin: 10px;"> </div> {% endblock %} The following is the output: Any idea why it is not showing properly like the screenshot below from the website? Even though, I have all the files of the pivottable.js project locally in my django project? -
makemigration - Create model and insert data only once
I've a model as below: from django.db import models class Country(models.Model): cid = models.SmallAutoField(primary_key=True) label = models.CharField(max_length=100) abbr = models.CharField(max_length=3) countries = { "AFG": "Afghanistan", "ALB": "Albania", "DZA": "Algeria", "ASM": "American Samoa", "AND": "Andorra", "AGO": "Angola", "AIA": "Anguilla" }; for c in countries: row = Country(label = countries[c], abbr = c) row.save() Now whenever I run the following command: python manage.py makemigrations The first time, it creates the table and populates it. The 2nd, 3rd and so on times, it keeps inserting the same data (It is definitely possible that I will be using the makemigration command many times, so I don't want it to insert it everytime the command is run) Any way to achieve this? Create and insert once? -
Please how can I create url using slug in my url.py django 3?
I am sorry for long explanation I am newbie to Django and come across a book titled "Tango with Django" version 1.9 but I am coding mine in the latest version of Django i.e 3.2. But when I came to chapter 6 I get stucked because slug. I tried my level best to resolve but merely spent hours without anything. So this is a brief of what I want to do, I have a django project called tango_with_django_project, and I created new app called rango so inside the rango app in mode.py I created my models including slug. The problem I am getting is whenever I write the route in urls.py it raises an exception of TypeError at /rango/category/other-frameworks/ cannot unpack non-iterable Category object Request Method: GET Request URL: http://127.0.0.1:8000/rango/category/other-frameworks/ Django Version: 3.2.7 Exception Type: TypeError Exception Value: cannot unpack non-iterable Category object Exception Location: C:\Users\Userpc\code\env\lib\site-packages\django\db\models\sql\query.py, line 1283, in build_filter Python Executable: C:\Users\Userpc\code\env\Scripts\python.exe Python Version: 3.8.5 Python Path: ['C:\Users\Userpc\code\tango_with_django_project', 'C:\Program Files (x86)\Python38-32\python38.zip', 'C:\Program Files (x86)\Python38-32\DLLs', 'C:\Program Files (x86)\Python38-32\lib', 'C:\Program Files (x86)\Python38-32', 'C:\Users\Userpc\code\env', 'C:\Users\Userpc\code\env\lib\site-packages'] Server time: Sat, 16 Oct 2021 14:20:06 +0000 #my urls.py from django.urls import path from rango import views urlpatterns = [ path('', views.index, name='index'), path('about/', views.about), path('index/', … -
Create django query from string
I have a list of strings that come in a strange format like this: OR(EQUAL(id,111),EQUAL(id,222)) AND(EQUAL(id,333),EQUAL(name,"John")) I want to parse these strings and run them as a filter in Django like this: from django.db.models import Q People.objects.filter(Q(id=111) | Q(id=222)) People.objects.filter(Q(id=333) & Q(name="John")) Is there a parser that can help me with this? Or would I have to write one from scratch? -
OperationalError (1366, "Incorrect string value: '\\xE2\\x80\\x8ESen...') MySQL Django
I develop django website on cpanel with MySQL database. I have a function that pull feeds from this website https://travelcommunication.net/feed/ and create an object from that (web scraping using beautifulsoup4). But when I try to grab the content section, the error appears. But that only happens with certain items, not all. I try on my local (with sqlite database) and all working fine. I have also tried on heroku (with PostgreSQL database) and all working fine. Here is my code: #views.py def pull_feeds(request, pk): if request.user.is_superuser: source = Autoblogging.objects.get(pk=pk) url = requests.get(source.url) soup = BeautifulSoup(url.content, "html.parser") length = source.items items = soup.find_all('item')[:length] contents = soup.find_all('content:encoded')[:length] for i in range(length-1, -1, -1): content = contents[i].text title = items[i].title.text body = content[content.find('<p>'):] #the problem is here .. when i comment this, everything works fine category = Category.objects.get(pk=source.category.id) if not Post.objects.filter(title=title).exists(): post = Post(title=title, body=body, #the problem is here .. when i comment this, everything works fine category=category) link = content[content.find('src=')+5:content.find('alt')-2] img_data = requests.get(link).content with open('temp_image.jpg', 'wb') as handler: handler.write(img_data) with open('temp_image.jpg', 'rb') as handler: file_name = link.split("/")[-1] post.cover.save(file_name, files.File(handler)) os.remove("temp_image.jpg") return redirect("news:autoblogging") else: return HttpResponse("Sorry you are not allowed to access this page") Does anyone know how to fix this error? Thanks. -
What should be the error code 400 or 500, for the given scenario?
I am just starting on Django rest framework and i was creation a function based Rest API as below: @api_view('POST') def temp_view(request): #do something ..... ..... ..... command to copy a static file from a server if command fails: return Response ..... ..... return Response If my API fails at the 'copy command line' then what should be the status code for the response(400 or 500). And if 500 should i send error message as: command to copy ...file failed or is this not recommend to share any message with 500 error code? I know its a very naive question but i am bit confused. Thanks in advance. -
ChoiceFields to give two different forms or different fields in html template and django
I am trying to make a registration form for a dentist and a student, where I have a choice field for a dentist and a student. What I want to happen is, when dentist is picked, I should be able to see the specialties field in the html as well as Django to pick that form, and for student, to pick student_email and institution. I am confused to how to write its code in the template and I looked almost everywhere and couldn't find anything that could help with what I want. I also included an image with what the registration image looks like. form.py from django import forms from django_countries.fields import CountryField class RegistrationForm(forms.Form): Specialties = [ ('pediatric','Pediatric'), ('oral surgeon','Oral Surgeon'), ('periodontist','Periodontist (Restorative; Esthetic)'), ('orthodontist','Orthodonsit'), ('endodontist','Endodontist'), ('prosthodontist','Prosthodontist'), ('oral pathologist','Oral Pathologist'), ('oral radiologist','Oral Radiologist'), ('public health dentist','Public Health Dentist'), ('research and academics','Research and Academics'), ] username = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}), required=True, unique=True) email = forms.EmailField(widget=forms.EmailInput(attrs={'class':'form-control'}), required=True, unique=True) student_email = forms.EmailField(widget=forms.EmailInput(attrs={'class':'form-control'}), required=True, unique=True) password = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control'}), required=True) password_repeat = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control'}), required=True) first_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}), required=True) last_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}), required=True) date_of_birth = forms.DateField(label = "Date of Birth", widget=forms.SelectDateWidget([x for x in range(1920,2021)]), required=True) country = CountryField().formfield(required=True) gender = forms.ChoiceField(widget=forms.RadioSelect, choices=[('male','Male'),('female','Female')], required=True) specialty = forms.CharField(widget=forms.Select(choices= …