Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the best way to create a 'list' associated with a model?
I want to be able to associate a company name in my models with a list of 'milestone' percentage points, in order to calculate how far each company is from the nearest milestone. For example: List_Of_Milestones = [5, 10, 15, 20, 25] Current_Progress = 9.5% Example Output = "Company A is 0.5% away from the 10% milestone, and 4.5% above the 5% milestone." The logic is simple from a Python standpoint, but I can't get my brain around how I would create this in a model setup and allow the user to set their own list of milestones. -
Incorrectly Configured lookup_field error in ```HyperlinkedModelSerializer```
Myself Dhinesh. But I'm a beginner at Django Rest Framework. Here, I'm trying to change the lookup_field from pk to a custom field (IP_Address). But I'm getting this error again and again. Help to resolve this issue. Getting ImproperlyConfigured at /api/nodes/192.168.1.200/ Could not resolve URL for hyperlinked relationship using view name "nodemaster-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. Models.py class NodeMaster(models.Model): Device_Manufacturer = models.CharField(max_length=50, choices = MANUFACTURER) Device_Type = models.CharField(max_length=50, choices = DEVICE_TYPE) Physical_Location = models.CharField(max_length= 50, null= True) IP_Address = models.CharField(max_length=50,unique = True ) Community_String = models.CharField(max_length = 50, null = False) def __str__(self): return self.IP_Address Serializers.py class NodeSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = NodeMaster fields = '__all__' lookup_field = "IP_Address" views.py class NodeViewSet(viewsets.ModelViewSet): serializer_class = NodeSerializer queryset = NodeMaster.objects.all() lookup_field = "IP_Address" urls.py node_list = NodeViewSet.as_view({ 'get':'list', 'post' : 'create' }) node_detail = NodeViewSet.as_view({ 'get':'retrieve', 'put' : 'update', 'patch' : 'partial_update', 'delete' : 'destroy' }) urlpatterns = format_suffix_patterns([ path('', node_list, name = 'nodemaster-list'), path('<str:IP_Address>/', node_detail, name='nodemaster-detail') ]) -
pdf kit generating extra blank page
I'm using python pdf kit to generate pdf from html. Page contents are coming correctly to pdf but there is one extra blank page coming. How to get rid of this? I'm using Django def verify(request): try: import pdfkit pdf_options = { #'page-size': 'Letter', 'orientation': 'Portrait', 'page-width': '19in', 'page-height': '14in', 'margin-top': '0.15in', 'margin-right': '0.15in', 'margin-bottom': '0.15in', 'margin-left': '0.15in', 'encoding': "UTF-8", # 'custom-header': [ # ('Accept-Encoding', 'gzip') # ], # 'no-outline': None } pdf_url = APP_URL + '/certificate?c=QWEPR5P' out_put_dir = BASE_DIR /'website/static/certificates/certificate.pdf' pdfkit.from_url(pdf_url, str(out_put_dir) , options=pdf_options) except OSError as e: return str(e) return HttpResponse("pdf genereated") -
I have a problem in user redirecting in django
I am a beginner and I am creating a forum using html, css, bootstrap, python and django. I created a view for deleting posts: class DeletePost(DeleteView): model = Post success_url = '/' def get_queryset(self): queryset = super().get_queryset() return queryset.filter(author_post_id=self.request.user.id) When a user will click the "Confirm button", when he need to remove a post, i would like to redirect him to the same discussion's page in which there was the post that he deleted, but i don't know how. Can somebody help? Thanks in advance -
Using Jinga2 Loop Control extension
I would like to break out of a for loop in a template. I understand this is not possible in DTL, but according to the docs it is possible if using Jinja2 (with the Loop Control extension) as the template engine. So I have updated my settings.py to include { 'BACKEND': 'django.template.backends.jinja2.Jinja2', 'DIRS': [os.path.join(BASE_DIR, 'templates/jinja2')], 'APP_DIRS': True, 'OPTIONS': { 'environment': 'project4.jinja2.environment'}, }, I define the Jinja environment in jinja2.py: from jinja2 import Environment from django.contrib.staticfiles.storage import staticfiles_storage from django.urls import reverse def environment(**options): env = Environment(**options, extensions=['jinja2.ext.loopcontrols']) env.globals.update({ 'static': staticfiles_storage.url, 'url': reverse, }) return env In my views.py is point to the jinja template file: return render(request, "jinja2/index.html", { "pages": page_obj, "liked": liked_posts }) But when I try to use the break statement in my loop like so: {% for like in liked %} {% if like.liked_post == page %} <span><button class="btn btn-secondary" id="unlike">Unlike</button></span> {% break %} {% else %} <span><button class="btn btn-secondary" id="unlike">Like</button></span> {% endif %} {% endfor %} I receive the following error: Invalid block tag on line 30: 'break', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag? What am I missing? Should the Jinja2 environment be be created in my views.py? -
can anyone tell me why pagination doesn't woek
How do I use pagination with Django ? this code is using django and this is the code i try alot of ways to do it but it doesn't work this website is blog website please help me with How can I do that? home.html <nav aria-label="Page navigation example"> <ul id='pagination' class="pagination justify-content-end container-fluid"> <li id='hasPrevious' class="page-item"> <a class="page-link" href="#" aria-label="Previous"> <span aria-hidden="true">&laquo;</span> </a> </li> <li id='hasNext' class="page-item"> <a class="page-link" href="#" aria-label="Next"> <span aria-hidden="true">&raquo;</span> </a> </li> </ul> </nav> </div> views.py def home(request): context = {"blogs" : BlogModel.objects.all()} context["services"] = Service.objects.all() context["works"] = RecentWork.objects.all() return render(request,"home.html", context) def blogs_pagination(request,page_number=1): blogs_query = BlogModel.objects.all().order_by("-created_at") blogs_query = Paginator(blogs_query, 3) blogs = blogs_query.page(page_number) current_page_pagination = blogs_query.page(page_number) has_next = current_page_pagination.has_next() has_previous = current_page_pagination.has_previous() total_pages = blogs_query.num_pages return JsonResponse( { "blogs": [blogs.serialize() for blog in blogs], "totalPages": total_pages, "hasNext": has_next, "hasPrevious": has_previous, },safe=False ) -
In Django REST framework, how do I call my serializer's validate method and also validate the required fields are submitted?
I'm using Python 3.9 with the Django REST framework (v 3.12.2). In a view, I validate that the object fields were submitted properly like so ... @api_view(('POST',)) def save_to_sheet_from_form(request): valid_ser = ValidateNewCoopSerializer(data=request.data) if valid_ser.is_valid(): ... do valid actions ... return Response(post_data, status=status.HTTP_201_CREATED) else: return Response(valid_ser.errors, status=status.HTTP_400_BAD_REQUEST) My serializer is set up like below ... class ValidateNewCoopSerializer(serializers.Serializer): # Set all fields as not required and allow_blank=true, so we can combine all validation into one step id=serializers.CharField(required=False, allow_blank=True) coop_name=serializers.CharField(required=False, allow_blank=True) street=serializers.CharField(required=False, allow_blank=True) address_public=serializers.CharField(required=False, allow_blank=True) city=serializers.CharField(required=False, allow_blank=True) state=serializers.CharField(required=False, allow_blank=True) zip=serializers.CharField(required=False, allow_blank=True) county=serializers.CharField(required=False, allow_blank=True) country=serializers.CharField(required=False, allow_blank=True) websites=serializers.CharField(required=False, allow_blank=True) contact_name=serializers.CharField(required=False, allow_blank=True) contact_name_public=serializers.CharField(required=False, allow_blank=True) contact_email=serializers.CharField(required=False, allow_blank=True) contact_email_public=serializers.CharField(required=False, allow_blank=True) contact_phone=serializers.CharField(required=False, allow_blank=True) contact_phone_public=serializers.CharField(required=False, allow_blank=True) entity_types=serializers.CharField(required=False, allow_blank=True) scope=serializers.CharField(required=False, allow_blank=True) tags=serializers.CharField(required=False, allow_blank=True) desc_english=serializers.CharField(required=False, allow_blank=True) desc_other=serializers.CharField(required=False, allow_blank=True) req_reason=serializers.CharField(required=False, allow_blank=True) def validate(self, data): """ Validation of start and end date. """ errors = {} # required fields required_fields = ['coop_name', 'websites', 'contact_name', 'contact_name_public', 'entity_types', 'req_reason'] for field in required_fields: if not data[field]: errors[field] = 'This field is required.' # contact info contact_email = data['contact_email'] if 'contact_email' in data else None contact_phone = data['contact_phone'] if 'contact_phone' in data else None if not contact_email and not contact_phone: errors['contact'] = 'Either contact phone or contact email is required.' if errors: raise serializers.ValidationError(errors) return data The … -
Change assign Django field with only the string as a key
I want to change the data of a Django field with only the string as a key. Example: person = Person.objects.get(pk=1) person['name'] = 'John' person.save() My Code: changes: dict[str, Any] = json.loads(request.body) user: User = User.objects.get(id=user_id) for key in changes.keys(): user[key] = changes.get(key) user.save() response = json.dumps([{ 'Success' : 'User changed successfully!'}]) return HttpResponse(response, content_type='application/json') I get the following error message: TypeError: 'User' object does not support item assignment How should I do this? Thank you! -
Function to resend otp not working in django project
I have madefunction that resends otp when the 'resend Otp' lick is clicked. This is django project. The following are the codes that I wrote. html (this page extends base.html) <a class="resend-otp" href="#" onclick="ReSendOTP('{{user.username}}', 'resendOTPmess')" ><i id="resendOTPmess">Resend</i>OTP?</a> <script type="text/javascript" src="{% static 'jquery-3.6.0.min.js' %}"></script> <script type="text/javascript" src="{% static 'regd_ajax.js' %}"></script> js file function ReSendOTP(username, mess_id){ mess = document.getElementById(mess_id); mess.innerText = "Sending..."; $.ajax({ type: 'GET', url: '/user/resendOTP', data: {usr:username}, success: function(data){ mess.innerText = data; } }) } views.py def resend_otp(request): if request.method == 'GET': get_user = request.GET['usr'] if User.objects.filter(username = get_user).exists() and not User.objects.get(username = get_user).is_active: user = User.objects.get(username=get_user) user_otp = random.randint(100000, 999999) UserOtp.objects.create(user = user, otp = user_otp) mess = f"Hello, {user.first_name}, \nYour OTP is {user_otp}\n Thanks!" send_mail( "Welcome to Solve Litigation - Verify your Email", #subject mess, #message settings.EMAIL_HOST_USER, # sender [user.email], #reciever fail_silently= False ) return HttpResponse("Resend") return HttpResponse("Can't Send OTP") urls.py from .views import resend_otp path('resendOTP', resend_otp) So here I am requesting a resend otp for the "username: rick.bhardwaj27@gmail.com" but I am getting the follwing error in the console jquery-3.6.0.min.js:2 GET http://127.0.0.1:8000/user/resendOTP?usr=rick.bhardwaj27%40gmail.com 404 (Not Found) -
check if quiz time ended in django
I want to check if time if the quiz is ended while the user is answering the quiz and if time is finished user will be redirected to another page the problem is that I can't find a way to start the check process without reloading the page if there is a way to make it work or if there is another way better than this I am all ears thanks in advanced models.py class Quiz(models.Model): name = models.CharField(max_length=30) start_date = models.DateField(null=True, blank=True) start_time = models.TimeField(null=True, blank=True) duration = models.IntegerField(null=True,blank=True) quiz_images = models.ImageField(upload_to=PathAndRename("images\\quiz_images"), default="images\\quiz_images\\default.png") slug = models.SlugField(max_length=8, null=True, blank=True) course = models.ForeignKey(Course, on_delete=models.CASCADE) prof = models.ForeignKey(User, on_delete=models.SET_NULL, null=True,limit_choices_to={'is_prof':True}) class Meta(): constraints = [ models.UniqueConstraint(fields=['name','course'],name='unique course') ] def __str__(self): return f"{self.name}/{self.course.name}" def save(self, *args, **kwargs): if not self.slug: self.slug = slug_generator(self) super().save(*args, **kwargs) image_resize(self.quiz_images.path) def get_absolute_url(self): return reverse('create-quiz-question', kwargs={'slug': self.slug}) @property def get_end_time(self): q_time=datetime.combine(self.start_date,self.start_time) return q_time+timedelta(minutes=self.duration) @property def is_open(self): if datetime.utcnow() > self.get_end_time: return False return True @property def get_quiz_grade(self): total = 0 for question in self.questions.all(): total += question.grade return total views.py def quiz_view(request,slug): quiz = Quiz.objects.filter(slug=slug).first() form = AnswerQuizForm(questions=quiz.questions.all()) # if not quiz.is_open: # if form.data: # form = AnswerQuizForm(data=request.POST,questions=quiz.questions.all(),user=request.user) # if form.is_valid(): # attemp=form.save() # attemp.quiz=quiz # attemp.save() … -
How do i build a web application with django? [closed]
Okay so i am meant to build an online consultation app for my project in school and ive done some small apps over time with Django but i dont know the first thing on how to create a full stack web application. I dont really have that much time to the deadline so i just want to ask. If i were to start learning now to start creating a full stack app, which way do you think i should go about learning it. option1 (learn how to combine javascript and bootstrap with django without the use of rest framework), option2(django and rest framework with javascript and bootstrap), option 3(learning django and React without the use of rest_ framework) and option 4(learning django, react and rest_framework). I really just want to know which way would be faster and easier to learn and create my app with. Keep in mind that django is the only constant option because that is the only language i am familiar with. if there are any other easier and better ways or languages to learn other than django then pls suggest. Thank you. -
Django admin site: Unable to lookup 'child model' on 'parent model or 'parent modelAdmin'
This one's really difficult to write as a question since I'm not exactly sure how to ask this in the first place. But I'll try. Basically, I'm experiencing an AttributeError when I'm visiting the parent model in my django admin site. My current django database has 2 tables (except the prebuilt tables): a parent table / model for activity, and a child table / model for instruction. This is the structure of my models: class activity(models.Model): title = models.CharField(max_length=30,default=None) date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) author = models.ForeignKey(User,on_delete=models.CASCADE,default=None) def __str__(self): return self.__class__.__name__ class instruction(models.Model): detail = models.CharField(max_length=50,default=None) date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) author = models.ForeignKey(User,on_delete=models.CASCADE,default=None) activity = models.ForeignKey(activity,on_delete=models.CASCADE,default=None) def __str__(self): return self.__class__.__name__ So, if I add a new activity in the django admin site, say: Push-ups, then, I should be able to select this newly added parent record in the instruction form. However, when I try to add a new instruction record and select a saved activity record, the activity dropdown shows the name of the model only(in this case, activity). It doesn't show Push-ups. What I did next was to add some modelAdmins for the activity and instruction. Here's the code: class activityAdmin(admin.ModelAdmin): list_display = [field.name for field … -
TypeError: expected str, bytes or os.PathLike object, not FieldFile while show pdf from DB
VIEW: def get_book(request, book_id): book = Book.objects.filter(book_id=16).first() return FileResponse(open(book.pdf, 'rb'), content_type='application/pdf') HTML: <embed src="{% url 'user-get-book' 16 %}" type="application/pdf" height="700px" width="500"> URL: path('get_book/<int:book_id>', views.get_book, name='user-get-book') Data is stored in the DB but not able to show on HTML. The error I get is this. TypeError at /get_book/16 expected str, bytes or os.PathLike object, not FieldFile Request Method: GET Request URL: http://127.0.0.1:8001/get_book/16 Django Version: 3.2.5 Exception Type: TypeError Exception Value: expected str, bytes or os. Help is much appreciated. -
Please My Logout redirects properly but does not truly logout from Django admin
I am building a simple notebook application and I want to include authentication. I have successfully added login, logout and registration. However, when I click on logout from the restricted app, it does successfully redirects but the restricted page can still be access through it's url. If I logout through the django admin only then will the restricted page not be access through the url until I log out. ** Normally, I expected that when I clicked on the logout link in note.html it will log me out also from the django admin panel. ** Why is this behaviour? url.py from django.urls import path from . import views from django.contrib.auth import views as auth_views from .forms import UserLogin app_name = 'accounts' urlpatterns = [ path('login/', views.loginUser, name = 'login'), path('logout/', views.logoutUser, name = 'logout'), path('register/', views.account_register, name = 'register'), path('profile/', views.profile, name ='profile'), ] views.py # from ..notebooks.models import Notes from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from .forms import RegisterForm from django.contrib import messages # Create your views here. @login_required def profile(request): return render(request,'accounts/profile.html', {'section' : 'profile'}) def loginUser(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, … -
How to filter multiple fields using Django-filter?
I want to retrieve data filtered by user and category. I'm using Django Rest Framework. models.py class Practice(models.Model): practice_id = models.BigAutoField(primary_key=True) user = models.ForeignKey('User', models.DO_NOTHING, default=None) subcategory = models.ForeignKey('Subcategory', models.DO_NOTHING, default=None) score = models.SmallIntegerField(null=True) def __str__(self): return str(self.practice_id) class User(models.Model): user_id = models.BigAutoField(primary_key=True) fullname = models.CharField(max_length=50) def __str__(self): return self.fullname class Subcategory(models.Model): subcategory_id = models.BigAutoField(primary_key=True) category = models.CharField(max_length=30) def __str__(self): return f"{ self.category }" serializers.py class PracticeSerializer(serializers.ModelSerializer): subcategory = SubcategorySerializer() class Meta: model = Practice fields = ('practice_id', 'user', 'subcategory', 'score', ) views.py @api_view(['GET']) def practiceFilter_User(request): if request.method == 'GET': exercises = Practice.objects.all() user = request.GET.get('user', None) if user is not None: practice_filtered = exercises.filter(user__user_id__icontains=user) exercises_serializer = PracticeSerializer(practice_filtered, many=True) return JsonResponse(exercises_serializer.data, safe=False) urls.py urlpatterns = [ url(r'^api/practice-filter-user$', views.practiceFilter_User), ] In my database I have 3 practice data as below : [ { practice_id: 1, user: 1, subcategory: { subcategory_id: 1, category: "Math", }, score: 7, }, { practice_id: 2, user: 1, subcategory: { subcategory_id: 1, category: "Math", }, score: 8, }, { practice_id: 3, user: 1, subcategory: { subcategory_id: 2, category: "History", }, score: 9, } ] If the above code is executed to get practice data by user id = 1, the result is as below : api/practice-filter-user?user=1 [ … -
Related Field got invalid lookup: level - while getting less than
I am building a easy Q&A site, And I am trying to get all the posts which have zero votes. So I tried using lt (less than). But After using lt it is not showing posts which have zero votes. It is showing nothing. Than, i tried to put 1 with lte (less than or equal to) instead of 0 lt but than it showing posts which have 1 votes , but it should show posts which have 1 or less votesbut it is not even including the posts which have0` votes. models.py class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30) votes = models.ManyToManyField(User, on_delete=models.CASCADE, related_name='votes') views.py def questions(request): posts = Question.objects.filter(votes__lt=0) context = {'posts':posts} What have i tried :- I tried by filtering lte=1 , I mean it will show posts which have 1 or less than 1 votes like :- posts = Question.objects.filter(votes__lte=1) But it is not showing which have 0 votes. Than i tried level posts = Question.objects.filter(votes__level__lt=0) But it is keep showing Related Field got invalid lookup: level I will really appreciate you Help. -
Django-Celery database update
I have a celery task for updating a part of my database. The problem is that if I delay the task (hand it to celery), it gets processed, but does not update the db. When I call the task manually (e.g. refresh_printfuldb() rather than refresh_printfuldb.delay()), it works fine and I see the changes when I query the db. The celery worker log looks like this: [2021-09-05 16:48:48,541: INFO/MainProcess] Task t_well.tasks.refresh_printfuldb[55eb39eb-f1e4-4b7d-b509-a87affe0535b] received [2021-09-05 16:48:49,069: INFO/SpawnPoolWorker-32] child process 47336 calling self.run() [2021-09-05 16:48:49,081: INFO/SpawnPoolWorker-33] child process 42852 calling self.run() The file tree: -mysite/ celery.py settings.py ... -app/ models.py tasks.py printfulapi.py ... celery.py: import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', "mysite.settings") app = Celery('mysite') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() settings.py: ... CELERY_BROKER_URL = 'redis://192.168.1.188:6379' CELERY_RESULT_BACKEND = 'django-db' ... models.py: As I've said, if I query the db after manually calling refresh_printfuldb(), I see the changes, so I suppose the problem is not with the models. tasks.py: from celery import shared_task from . import printfulapi ... @shared_task def refresh_printfuldb(): printfulapi.refresh_orders(orders_in_api_page) #other calls to the printfulapi module ... ... printfulapi.py: from .models import Product, Variant, SyncProduct, SyncVariant, Order def refresh_orders(orders_in_api: List[Dict]) -> None: for order_in_api in orders_in_api: order_id = order_in_api["id"] order = get_object_with_id(Order, order_id) order.status = order_in_api["status"] … -
why the Customer data is not show in template profile.html in django
models.py ( considering all required data ) Customer is not Django Default User how to display in template the customer class Customer(models.Model): first_name = models.CharField(max_length=50) last_name = models.TextField(max_length=50) phone = models.CharField(max_length=15) email = models.EmailField(max_length=100 ,default='') password = models.CharField(max_length=500) views.py ( considering all required done ) def profile(request): data= Customer.objects.all() return render(request,'profile.html' ,{'data':data}) profile.html ( considering making urls) and all doing requirement {% if data %} <h2>{{ data.email }}</h2> {% endif %} -
DC motor connected to motor shield and raspberry pi didn't move when controlled through web server
I am very new to this stuff so bear with me :). So I had to continue my senior's project which is to control a raspberry pi car from a website running on local server. I recently received the assembled components and all, and as I turn on the raspberry pi I managed to connect to his web server by entering the raspi IP address and the 8000 port (e.g: http://XXX.XXX.XXX.XXX:8000). However, the move forward button on the page that supposed to move the tire doesn't work as it supposed to. the web interface and the post request sent from the forward button The project works fine before it arrive to me and move as it supposed to. Here some things I've discovered while troubleshooting: The project auto detect the changes of IP address which means connected to another different wifi would not be the problem. I believe there's also no problem with the connection of the page and the project since I already try edit something in the project file in the raspberry pi and it appears on the web page on my computer. Connection between the motor shield and the raspberry pi is not a probem since I've … -
how to display os.environ.get value in ubuntu using python/django
i have the following OS" (env) ubuntu@ip-xxxxxx:~/test/test_app$ lsb_release -a No LSB modules are available. Distributor ID: Ubuntu Description: Ubuntu 20.04.3 LTS Release: 20.04 Codename: focal now to set the env variable i have accessed nano ~/.profile and edited the file with: export TEST="johndoe" then exited nano and did chmod a+x ~/.profile and ~/.profile to apply the changes now in django views.py when i try to access the variable: views.py ... import os @api_view(["GET"]) def index(request): if request.method == "GET": env_var = os.environ.get("TEST") context = {"response": "Welcome: {}".format(env_var)} return Response(context) result { "response": "Welcome: None" } PS: I dont' intend to use any os variable in the views.py, i was just testing it there so i can use it in the settings.py Is there any reason why the value None is returned (why it's not picking up the actual value)? Thank you in advance -
how to fit image inside a div?
I am building an instagram clone & currently working in posts so my question is that, i have created a card and inside of that i have created a div containing posts(images) but the problem is that, when i upload images with multiple size it straches my card & it doesn't get fit inside of that div. Also my right div changes according images... This is small image This is big image Code: <div class="mx-auto w-75"> <div class="card my-3"> <div class="card-body p-0"> <div class="row"> <div class="col-sm-8 ms-2 mb-0 ps-1 pe-0"> <div id="carouselExampleFade" class="carousel m-0 slide carousel-fade" data-bs-ride="carousel"> <div class="carousel-inner"> <div class="carousel-item active"> <img src="{% static 'images/post-1.jpg' %}" style="height:auto;" class="d-block w-100 img-fluid" alt=""> </div> <div class="carousel-item"> <img src="{% static 'images/profile-1.jpg' %}" style="height:auto;" class="d-block w-100 img-fluid" alt=""> </div> <div class="carousel-item"> <img src="{% static 'images/profile-2.jpg' %}" style="height:auto;" class="d-block w-100 img-fluid" alt=""> </div> </div> <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleFade" data-bs-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="visually-hidden">Previous</span> </button> <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleFade" data-bs-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="visually-hidden">Next</span> </button> </div> </div> <div class="col-sm-3 p-0"> <div class="card pt-0" style="width:325px; height:72px; padding:16px; margin-top:-1px;"> <div class="card-body"> </div> </div> </div> </div> </div> </div> </div> -
How can I handle selenium and geckodriver install error?
I ran the following code by installing selenium and django module. from selenium import webdriver browser = webdriver.Firefox() browser.get('http://localhost:8000') assert 'Django' in browser.title For the selenium module, I need geckodriver for firefox browser. So, I installed geckodriver by different ways - 1. npm, 2. brew, 3. direct install (download from here and move it to /usr/local/bin or /usr/bin. All the ways did not work for the above test code. I got the following error message: Traceback (most recent call last): File "functional_tests.py", line 3, in <module> browser.get('http://localhost:8000') File "/Users/kiyeonj/opt/anaconda3/envs/tdd_practice/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 333, in get self.execute(Command.GET, {'url': url}) File "/Users/kiyeonj/opt/anaconda3/envs/tdd_practice/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute self.error_handler.check_response(response) File "/Users/kiyeonj/opt/anaconda3/envs/tdd_practice/lib/python3.8/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: Reached error page: about:neterror?e=connectionFailure&u=http%3A//localhost%3A8000/&c=UTF-8&d=Firefox%20can%E2%80%99t%20establish%20a%20connection%20to%20the%20server%20at%20localhost%3A8000. Please let me know what the problem is.. -
Django doesn't raise ValidationError on ModelChoiceField (widget RadioSelect) if user didn't select any choice
I have a form that contains a ModelChoiceField poller_category class PollersForm(forms.Form): # Poller Category poller_category = forms.ModelChoiceField(widget=forms.RadioSelect(attrs={ 'class': 'poller-category-radio', }), queryset=Categories.objects.all().order_by('poller_category'), label='Select a Category') which is rendered as follows: <!-- Poller Categories --> <div class="fieldWrapper"> <div class="label">{{ form.poller_category.label_tag }}</div> <div class="category-ctn"> {% for category in form.poller_category %} <div class="category-wrapper">{{ category }}</div> {% endfor %} </div> </div> Now if the user doesn't select any category and tries to submit the form, nothing just happens. That actually means that the form is valid, doesn't it? If so, why doesn't it trigger the redirect? Also If I select a choice and submit, redirect is called, but the category isn't populated in the DB. # create a form instance and populate it with data from the request: form = PollersForm(request.POST) # check whether it's valid: if form.is_valid(): # process the remaining data in form.cleaned_data as required poller_text = form.cleaned_data['poller_text'] poller_category = form.cleaned_data['poller_category'] poller_choice_one = form.cleaned_data['poller_choice_one'] poller_choice_two = form.cleaned_data['poller_choice_two'] # Get the user created_by = request.user # Save the poller to the database p = Pollers(poller_text=poller_text, poller_choice_one=poller_choice_one, poller_choice_two=poller_choice_two, poller_category=poller_category, created_by=created_by) p.save() # redirect to a new URL: return redirect(poller_success) # if a GET (or any other method) we'll create a blank form else: form = … -
Total Price Django
How can i get "total" from these models down below? I tried doing something in views but I get attribute error that QuerySet' object has no attribute 'total'. views.py def cart(request): cart = Cart.objects.filter(order_user=request.user) order_items = OrderItem.objects.filter(cart__in=cart) total = 0 for i in order_items: total = i.quantity * i.item.price + cart.total cart.update(total=total) models.py class OrderItem(models.Model): cart = models.ForeignKey('Cart', on_delete=CASCADE, null=True) item = models.ForeignKey(Item, on_delete=CASCADE, null=True) quantity = models.IntegerField(default=1) class Item(Visits, models.Model): title = models.CharField(max_length=150) price = models.IntegerField(default=1000) image = models.ImageField(upload_to='pictures', default='static/images/man.png') description = models.TextField(default="Item") visits = models.IntegerField(default=0) class Cart(models.Model): order_user = models.OneToOneField(User, on_delete=CASCADE) ordered = models.BooleanField(default=False) total = models.IntegerField(default=0, help_text="100 = 1EUR") order_items = models.ManyToManyField(Item, related_name='carts', through=OrderItem ) -
Resend OTP ajax function not working in a django project
I have made an ajax function that resends otp when the 'resend Otp' lick is clicked. This is django project. The follwing are the codes that I wrote. html <a class="resend-otp" href="#" onclick="ReSendOTP('{{user.username}}', 'resendOTPmess')" ><i id="resendOTPmess">Resend</i>OTP?</a> js file function ReSendOTP(username, mess_id){ mess = document.getElementById(mess_id); mess.innerText = "Sending..."; $.ajax({ type: 'GET', url: '/user/resendOTP', data: {usr:username}, success: function(data){ mess.innerText = data; } }) } views.py def resend_otp(request): if request.method == 'GET': get_user = request.GET['usr'] if User.objects.filter(username = get_user).exists() and not User.objects.filter(username = get_user).is_active: user = User.objects.get(username=get_user) user_otp = random.randint(100000, 999999) UserOtp.objects.create(user = user, otp = user_otp) mess = f"Hello, {user.first_name}, \nYour OTP is {user_otp}\n Thanks!" send_mail( "Welcome to Solve Litigation - Verify your Email", #subject mess, #message settings.EMAIL_HOST_USER, # sender [user.email], #reciever fail_silently= False ) return HttpResponse("Resend") return HttpResponse("Can't Send OTP") urls.py from .views import resend_otp path('resendOTP', resend_otp) So I am requesting a resend otp for the "username: rick.bhardwaj27@gmail.com" but I am getting the follwing error in the console jquery-3.6.0.min.js:2 GET http://127.0.0.1:8000/user/resendOTP?usr=rick.bhardwaj27%40gmail.com 404 (Not Found) What should I do to rectify it, please suggest.