Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I have two form to get email in my webpage but whenever i submit the form the message form is not valid is displayef
urls.py from django.urls import path, include from . import views urlpatterns = [ path('', views.home, name='home'), path('home', views.home, name='home'), path('about', views.about, name='about'), path('contact', views.contact, name='contact'), path('email-submit/form1/', views.email_submit, name='email-submit1'), path('email-submit/form2/', views.email_submit, name='email-submit2'), ] forms.py from django import forms from .models import EmailSubscription class EmailSubscriptionForm(forms.ModelForm): class Meta: model = EmailSubscription fields = ['email'] models.py from django.db import models class EmailSubscription(models.Model): email = models.EmailField(unique=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.email views.py from django.shortcuts import render from django.http import HttpResponse, JsonResponse from django.contrib import messages from .forms import EmailSubscriptionForm def home(request): return render(request, 'maincontent/home.html') def about(request): form1 = EmailSubscriptionForm() form2 = EmailSubscriptionForm() return render(request, 'maincontent/about.html', {'form1': form1, 'form2': form2}) def contact(request): return render(request, 'maincontent/contact.html') def email_submit(request): if request.method == 'POST': form_id = request.POST.get('form_id') if form_id == 'form1': form = EmailSubscriptionForm(request.POST) elif form_id == 'form2': form = EmailSubscriptionForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] form.save() messages.success(request, f'Thank you for subscribing with email: {email} ({form_id.capitalize()})') else: messages.error(request, f'Form {form_id.capitalize()} is not valid.') form1 = EmailSubscriptionForm() form2 = EmailSubscriptionForm() return render(request, 'maincontent/about.html', {'form1': form1, 'form2': form2}) email_form_1.html <form class="email-submit" id="data-form-1" method="post" action="{% url 'email-submit1' %}"> {% csrf_token %} <input type="hidden" name="form_id" value="form1"> <input type="email" placeholder="Enter your email..." name="{{ form.email_address.name }}" id="{{ form.email_address.id }}" required/> <button type="submit"> Sign … -
How Post Amount Number From React to Django py script
hello i want send data from my react app.jsx to django script file that scirpt have amount variable and need number to give to him in my script from django.db import models from django.contrib.auth.models import User from rest_framework import routers, serializers, viewsets from . serializer import * from azbankgateways import (bankfactories,models as bank_models,default_settings as settings,) import logging from django.urls import reverse from django.shortcuts import render from django.http import HttpResponse, Http404 from django.http import JsonResponse # Bank from azbankgateways.exceptions import AZBankGatewaysException from azbankgateways.models.banks import Bank # API # Create your models here. # ViewSets define the view behavior. class BankViewSet(viewsets.ModelViewSet): queryset = Bank.objects.all() serializer_class = BankSerializer # Bank Functions def go_to_gateway_view(request): # خواندن مبلغ از هر جایی که مد نظر است amount = 5000 # تنظیم شماره موبایل کاربر از هر جایی که مد نظر است user_mobile_number = '+989112221234' # اختیاری factory = bankfactories.BankFactory() try: bank = factory.auto_create() # or factory.create(bank_models.BankType.BMI) or set identifier bank.set_request(request) bank.set_amount(amount) # یو آر ال بازگشت به نرم افزار برای ادامه فرآیند bank.set_client_callback_url('/callback-gateway') bank.set_mobile_number(user_mobile_number) # اختیاری # در صورت تمایل اتصال این رکورد به رکورد فاکتور یا هر چیزی که بعدا بتوانید ارتباط بین محصول یا خدمات را با این # پرداخت برقرار کنید. bank_record = … -
CSRF verification error from dockerized Django behind dockerized nginx
I have two docker containers running together, one for a Django app using gunicorn, and one for nginx serving static files and redirecting requests to the Django app. I have used different ports for the Django/gunicorn server, exposed only to nginx (8000), the nginx server, exposed in the docker container (80), and externally when using the docker container (so I mapped the port to a different one, say 8888). I also access it with a "xyz.local" host name from the device where docker runs. This is all happening in a home network, no HTTPS involved. Now when I submit a form, e.g. the admin interface's login form, I get a CSRF verification failure saying xyz.local:8888 is not a trusted origin. I understand that I can add "http://xyz.local:8888" to the CSRF_TRUSTED_ORIGINS to make it work, or disable CSRF protection altogether, but I'm wondering if that is the correct/best way in this setup. I would like to have the Django docker container be as unaware of the outside world as possible, so that I can just run it on another device having a different host name or with a different docker-compose configuration using a different port, without having to rebuild the docker … -
Django Unit Test for class with TokenAuthentication
this is my first time writing unit test so in my Django Project I have this class from views.py class AllClientProfilesView(generics.ListAPIView): authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] serializer_class = ClientProfileSerializer def get_queryset(self): return ClientProfile.objects.all() and my test code is class AllClientProfilesViewTest(APITestCase): def setUp(self): call_command('flush', interactive=False) self.user = User.objects.create_user(id='2' , phone_number=506879765) self.token = Token.objects.create(user=self.user) self.profile1 = ClientProfile.objects.create(name='Profile 1', ) self.profile2 = ClientProfile.objects.create(name='Profile 2', ) self.profile3 = ClientProfile.objects.create(name='Profile 3', ) def test_view_requires_authentication(self): url = reverse('myURL') response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) def test_get_all_client_profiles(self): url = reverse('myURL') self.client.credentials(HTTP_AUTHORIZATION=f'Token {self.token.key}') response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) expected_profiles = ClientProfile.objects.all() self.assertEqual(len(response.data), expected_profiles.count()) for data, expected_profile in zip(response.data, expected_profiles): serializer = ClientProfileSerializer(expected_profile) self.assertEqual(data, serializer.data) but when I run it I got this error and I don't know how to fix it return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: UNIQUE constraint failed: authtoken_token.user_id -
{'sales@mydomain.co': (553, b'5.7.1 <abc@gmail.com>: Sender address rejected: not owned by user sales@mydomain.co')}
I have a contact form on my website where users fill in their name, email and message to contact support which in this case is sales@mydomain.co and say the sender's email is abc@gmail.com. When a user submits the form, the form yields an error {'sales@mydomain.co': (553, b'5.7.1 <abc@gmail.com>: Sender address rejected: not owned by user sales@mydomain.co')} The form works if the sender's email belongs to the organization sales@mydomain.co. Is it possible to for a user to send an email(using a different organization email, such as Gmail) through the online form? here is my forms.py class ContactForm(forms.Form): name = forms.CharField(label='Your name', max_length=100) email = forms.EmailField(label='Your email', max_length=100) message = forms.CharField(max_length=600, widget=forms.Textarea) def send_mail(self): logger.info("Sending email to customer service") subject = "Site message" message = f"From: {self.cleaned_data['name']} <{self.cleaned_data['email']}>\n{self.cleaned_data['message']}" sender_email = self.cleaned_data['email'] # Use the user's email as the sender recipient_list = ['sales@mydomain.co'] # My domain email address send_mail( subject, message, sender_email, recipient_list, fail_silently=False, ) -
Attempting to migrate an Django ImageField, but failing to migrate
I am currently facing a problem with trying to migrate a Django Image field from a folder named media_root located inside a folder named static_cdn inside of my current project here is what my current file structure looks like as that may help; veganetworkmain -----profiles -------static_cdn ---------media_root ----------test.png Test.png is a png file that is generated using a picture generation algorithm using Pillow, here is what Test.png actually looks like: However what actually happens when I try to implement the code to get the picture into my program using a Django Image Field is that it just becomes white as seen here: I had tried methods like using python manage.py makemigrations, python manage.py migrate, changing the static by changing url_patterns and setting and even python ./manage.py makemigrations profiles. Here are the links to each method that I had tried: Django - makemigrations - No changes detected Page not found 404 Django media files And finally here is my code that I am currently working with during this time: models.py from django.db import models from django.shortcuts import reverse from django.contrib.auth.models import User from .utils import get_random_word from django.template.defaultfilters import slugify from django.db.models import Q -------------------------------------------------- class Profile(models.Model): first_name = models.CharField(max_length=200, blank=True) … -
400 Bad Request Error in an application using Django, Gunicorn, and Nginx
I've been trying to troubleshoot my issue with no success for a while now, so I hope posting here helps. I am developing an application using Django REST Framework, Gunicorn, and Nginx. The idea is to have Gunicorn serve the Django applicaiton, and have Nginx be used as a reverse proxy that holds the SSL certs. I've referenced multiple guides on hosting applications using these three technologies, with little success. I have my Django application connected to gunicorn using a sock file on port 80, and my Nginx server blocks listen for both port 80 and 433 (for SSL purposes). I have tried just about everything I can think of, and yet I am still getting a 400 - Bad Request error whenever I navigate to the domain that should serve the API. This is my Nginx sites-available file, with just a couple of names changed for security purposes: server { listen 80; server_name www.querymarketplace.net; return 301 http://querymarketplaceapi.net$request_uri; } server { listen 80; server_name querymarketplaceapi.net 157.245.10.103; location /static/ { root /home/jbisc/qm_marketplace/; } location / { include proxy_params; proxy_pass http://unix:/home/jbisc/qm_marketplace.sock; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Host $host; proxy_set_header X-Forwarded-Host $server_name; } } server { listen 443 ssl; listen [::]:443 ssl; # Optional: … -
How do I pass a Javascript variable to my Django framework to be used in template or via get_context?
I have been working to pass form values to a modal using Django. I have gotten most of the way there, but I can't quite make out how to connect the two.... Here is my AJAX... $("#avail").on("click", function(event) { var modalavail = document.getElementById("myModalavail"); var markedCheckbox = document.querySelectorAll('input[type="checkbox"]:checked'); event.preventDefault(); $(window).unbind('beforeunload'); $.ajax({ method: 'get', headers: { "X-CSRFToken": token }, url: "", processData: false, contentType: false, cache: false, enctype: 'multipart/form-data', success: function(resp) { modalavail.style.display = "block"; for (var checkbox of markedCheckbox) { console.log(checkbox.value + ' '); } }, error: function (request, status, error) { console.log(request.responseText); showAjaxFormErrors(JSON.parse(request.responseText)); $('html, body').animate({ scrollTop: 0 }, 50); }, }); }); Here is my HTML... <button class="button209" id="avail">Check Availability</button> <div id="myModalavail" class="modal"> <div class="modal-content"> <span class="close"></span> <img class="logo4" src="/static/images/threecircles.svg"> <div class="table56"> {% for entry in form.approvers %} <table class="table57"> <thead> <tr> <th class="title156">Name</th> <th class="title118">Available?</th> </tr> </thead> <tbody> <tr> <td class="title156">{{ entry.name }}</td> <td class="title117">Yes</td> </tr> </tbody> </table> {% endfor %} </div> <input type="hidden" id="modal-approvers"> <button type="button" class="button210" id="modalcloseavail">Close</button> </div> </div> Obviously, form.approvers is going to give me all of the eligible approvers in my form....However I'm just trying to pass the selected approvers... This line of code is working flawlessly.... var markedCheckbox = document.querySelectorAll('input[type="checkbox"]:checked'); It is getting the … -
A function working in a custom file but not in a "custom migration" on Django
I am beginner in Django and just started learning migrations. In a DB table, I am trying to remove a row that has a specific field value. When I create a custom file which uses Django settings, the function properly deletes the row. But when I use the snippet in another function in a custom migration file, the deletion doesn't take place. It is possible that I am missing something elementary as a beginner. So I am trying to delete all orders the status of which is cancelled. The function that works in a separate file is: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "orm_skeleton.settings") django.setup() from main_app.models import Order def delete_test_fnc(): all_orders = Order.objects.all() for i in range(len(all_orders) - 1, -1, -1): order = all_orders[i] if order.status == "Cancelled": order.delete() delete_test_fnc() The custom migration where delete doesnt work (other two modifications work without issues) is: from datetime import timedelta from django.db import migrations CURRENT_ORDERS = [] def modify_delivery_warranty(apps, schema_editor): global CURRENT_ORDERS orders = apps.get_model("main_app", "Order") all_orders = orders.objects.all() CURRENT_ORDERS = all_orders for i in range(len(all_orders) - 1, -1, -1): order = all_orders[i] if order.status == "Cancelled": order.delete() elif order.status == "Pending": order.delivery = order.order_date + timedelta(days=3) elif order.status == "Completed": order.warranty = "24 months" order.save() … -
anyone face this issue in django?
enter image description here when i created a employee form and view the form it show like as image. <tr> <td>{{ form.employee_name.label }}</td> <td>{{ record.employee_name }}</td> </tr> <tr> <td>{{ form.dob.label }}</td> <td>{{ record.dob }}</td> </tr> <tr> <td>{{ form.age.label }}</td> <td>{{ form.age }}</td> </tr> only age field show like this, i review all my code , it didnt find and issue, if face same issue please help me -
How to clear validation error in django when the value is in timezone and it must be an decimal value?
I am a beginner in django and in fact,now only i started my learning process about django Now i faced an error in my program I created an app and assigned some textfields in it After that i do some modulations and at a particular time,it asks for an argument to be given in my function to run properly and it shows some examples of how the argument be like And i mistakenly give the timezone.now() for a decimalvalue function Now it shows error like "current date time"value must be a decimal number and i am frustrated upon this error So can someone help me to clear this so that i can continue my journey seemlessly I tried to run a program app called products and i give a decimalvalue() in it with a missing argument and it shows an argument must ve given and asks Would you gonna give now? With for an example "timezone.now" And i give the same example as my argument and i get an error which is "current date time" value must be a decimal number And i want to clear the timezone.now function and wanna put some value or something to run the programthis … -
How to hide password field from request.user in django?
i am learning django currently and i have a question about request.user. I have made an custom user model and i use django's built in authentication. When i use login function, everything works right. When i print request.user it returns the current user. When i print request.user.password it returns the user's hashed password. I know that it is not safe to expose user's password in any form. So my question is how can i exclude password field form request.user I have tried to write a serializer but with no success. User's model from django.db import models from django.conf import settings from django.contrib.auth.models import AbstractUser, BaseUserManager from post.models import Post class UserManager(BaseUserManager): def create_user(self, email, username, fullName, password): if not email: raise ValueError("User must provide Email") if not username: raise ValueError("User must provide username") if not fullName: raise ValueError("User must provide full name") user = self.model( email=self.normalize_email(email), fullName=fullName, username=username ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email, full_name, password=None): """Create user and give Superuser privilages""" user = self.create_user( email=email, full_name=full_name, username=username, password=password ) user.is_active = True user.is_staff = True user.is_superuser = True print("Superuser privilages activated.") user.save(using=self._db) return user class User(AbstractUser): email = models.EmailField("Email", unique=True) username = models.TextField("Username", max_length=100, unique=True) fullName … -
Running DRF endpoints in a venv with gunicorn
I have some APIs implemented with DRF and I want those to run in a venv. I am using gunicorn. I run gunicorn like this: /path_to_venv/bin/gunicorn But in the API code I log os.getenv('VIRTUAL_ENV') and it's None. Is that valid evidence that the code is not running in the venv? If so, how can I force it to run in the venv? If not, how can I validate that it is running in the venv? -
Extract Musical Notes from Audio to array with FFT
I'm trying to create a project in which I upload an audio file (not necessarily wav) and use FFT endpoint to return an array with the names of the sounds. Currently, I have such code, but even though I upload a file with only the sound A, it receives the value E-10, and when uploading, for example, title, I receive only one sound. Would anyone be able to help me? import os from django.shortcuts import render from django.http import JsonResponse from pydub import AudioSegment import numpy as np from noteQuiz import settings #Names of the notes NOTE_NAMES = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"] def freq_to_number(f): return 69 + 12*np.log2(f/440.0) def number_to_freq(n): return 440 * 2.0**((n-69)/12.0) def note_name(n): return NOTE_NAMES[n % 12] + str(int(n/12 - 1)) def find_top_notes(fft, xf): if np.max(fft.real) < 0.001: return [] lst = [x for x in enumerate(fft.real)] lst = sorted(lst, key=lambda x: x[1], reverse=True) idx = 0 found = [] found_note = set() while (idx < len(lst)) and (len(found) < 1): f = xf[lst[idx][0]] n = freq_to_number(f) n0 = int(round(n)) name = note_name(n0) if name not in found_note: found_note.add(name) s = [note_name(n0)] found.append(s) idx += 1 return found def … -
Django broken pipe error when handling large file
A server developed using the Django framework is hosted in a local environment, and a broken pipe error occurs in the process of processing large files. The current problem is the code below, which is to respond by changing the DICOM file to the png extension through a separate view to deal with the DICOM file. There is no problem in normal cases, but a broken pipe error occurs when processing about 15MB of files. # javascript code for request file data in html template function loadImages(images, fileType, index) { event.preventDefault(); if (index < images.length) { var image = images[index]; var fileName = image.image_url.split('/').pop(); var imageData = { fileName: fileName, }; imageInfoArray.push(imageData); var img = new Image(); img.onload = function() { var filePreviewHTML = ` <li class="add-image-${index}"> <a href="javascript:void(0)" class="img-wrap" data-id="${index}"> <img src="${(fileName.endsWith('.DCM')) ? '/dicom/' + fileName : image.image_url}" alt="ask-file-img"/> <button class="remove-file" onclick="disableImage('${image.image_url}')"><i class="material-icons">close</i></button> </a> <p class="file-name">${fileName}</p> </li> `; var filePreview = $('.file-preview[data-file="' + fileType + '"]'); filePreview.append(filePreviewHTML); loadImages(images, fileType, index + 1); } img.src = (fileName.endsWith('.DCM')) ? '/dicom/' + fileName : image.image_url; } // view code for handling DICOM file def show_dicom(request, file_path): file_path = os.path.join(settings.MEDIA_ROOT, "xray_images", file_path) dicom = pydicom.dcmread(file_path) image_array = apply_voi_lut(dicom.pixel_array, dicom) image_array_2d = image_array[0] if … -
Flutter Web: Assets Not Loading Correctly from main.dart.js Using Current Relative URL Instead of Base HREF
I'm currently working on hosting a Flutter web application using a Django web server on an Ubuntu 20.2 environment. The Flutter version I'm using is 3.13.5, channel stable, and my project structure has the Flutter web project located in the static folder. I've been facing an issue where the Flutter web application cannot locate the FontManifest.json file. It seems like this file is being sought using the current URL (relative) instead of the base URL defined in the index.html file. Assets loaded from index.html work correctly with the base href directed to static directory, but those loaded from main.dart.js and are using the current URL. Has anyone encountered a similar issue or has insights on how to ensure that all assets, including FontManifest.json, loaded from main.dart.js use the base URL as intended? I am almost inclined to reference the missing visual assets in main.dart through the Network module but I think Flutter should have a configuration option to determine the static-uri-location where the app will be hosted with all it's static files instead of just having to rely on the relative-uri for static files. 1.I tried fetching those 2 files (AssetManifest.bin + FontManifest.json) through the main.dart.js but that does not … -
Django not saving data with post
I have this view: class TaskApiView(APIView): def post(self, request): serializer = TaskSerializer(data=request.data) print(request.data) if serializer.is_valid(): print("valid") serializer.save() return Response(status=status.HTTP_201_CREATED) else: print(serializer.errors) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) request body: { "content": "asd" } log: {'content': 'asd'} valid [21/Oct/2023 11:33:19] "POST /api/task/create HTTP/1.1" 201 0 But when I try to get all tasks with this view class TaskListAPIView(generics.ListAPIView): queryset = Task.objects.all() serializer_class = TaskSerializer I get just the id: [ { "id": 25 } ] Serializer: class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = "__all__" Model id: models.UUIDField(unique=True, auto_created=True) content: models.CharField(default="") creationDate: models.DateField(auto_now_add=True) author: models.ForeignKey(User, on_delete=models.CASCADE) status: models.CharField( choices=StatusEnum, max_length=5, default=StatusEnum.TODO, ) def __str__(self): return self.id + self.content I want to create a task with content -
how to pass domain name to the container in Container Instances, OCI?
I am running Django application image in container that requires "CSRF_TRUSTED_ORIGINS" to be passed as env variable, but it looks like container instances generate the domain after the deployment; or how can I set the env variable of container DJANGO_CSRF_TRUSTED_ORIGINS="container instance domain" before running the container. -
Getting a 404 error when sending a POST request with APIClient in Django test case
I'm writing a test case for a Django REST Framework API using the APIClient from the rest_framework.test module. I'm trying to send a POST request to the wordOftheDay/ endpoint with the provided data, but I keep getting a 404 error. The server is running and accessible at http://127.0.0.1:8000, and the endpoint is correctly defined in the server's code. I'm not sure what is causing the 404 error in the test case. def test_valid_post_request(self): client = APIClient() print(client) response = client.post('wordOftheDay/', self.valid_data, format='json') print('response',response) self.assertEqual(response.status_code, 200) print('response.status_code',response.status_code) # Check if the model is created with the expected data self.assertTrue(WordModel.objects.filter(device_id=self.valid_data['device_id']).exists()) This is the error - Traceback (most recent call last): File "/home/k/Desktop/project/wordOfTheDay/tests/test_wordOfTheDay.py", line 88, in test_valid_post_request self.assertEqual(response.status_code, 200) AssertionError: 404 != 200 -
How to Save The Form We Created
Form.save not working Hello guys, I created a form myself without using ModelForm self fields to design it on my own by using css and html but at the end form.save not using ı have no idea what to do /////////////////////////////////////////////////////////////////////////////////////////////// This is my view, class ContactView(View): def get(self,request,*args,**kwargs): return render(request,'contact.html') def post(self,request,*args,**kwargs): form = Form(request.POST) if form.is_valid(): newUser = form.save() return redirect('homepage') return render(request,'contact.html',{'form':form}) This is my html, <form method="post"> {% csrf_token %} <div> <h2 style="margin-bottom: 40px; width: 100%; text-align: center;">Get İn Touch</h2> <div><input type="text" placeholder="Name" name="Name"> {% for err in form.name.errors %} <small class="text-danger"> {{ err }} </small> {% endfor %} </div> <div><input type="text" placeholder="E-mail" name="E-mail"> {% for err in form.name.errors %} <small class="text-danger"> {{ err }} </small> {% endfor %} </div> <div><input type="text" placeholder="Subject" name="Subject"> {% for err in form.name.errors %} <small class="text-danger"> {{ err }} </small> {% endfor %} </div> <div><textarea name="" id="" cols="66" rows="10" style="display: block;" placeholder="Message" name="Message"></textarea> {% for err in form.name.errors %} <small class="text-danger"> {{ err }} </small> {% endfor %} </div> <div class="button"> <button type="submit" value="Submit">Send an email</button> </div> </div> </form> this is my form, class Form(forms.ModelForm): Name = forms.CharField(max_length=50) Email = forms.CharField(max_length=100) Subject = forms.CharField(max_length=50) Message = forms.CharField(widget=forms.Textarea) class Meta: model … -
Reverse for 'posts-details-page' with arguments '('',)' not found. 1 pattern(s) tried: ['all_posts/(?P<slug>[-a-zA-Z0-9_]+)$']
I have build the basic Django project but getting error while trying to retrive all the post from the project. you can download the code from github to create the issue, Please guide me how to resolve this issue if anyone can help. https://github.com/techiekamran/BlogProject.git and branch name is starting-blog-project urls.py from django.urls import path from blogapp import views urlpatterns = [ path("",views.starting_page,name='starting-page'), path("posts",views.posts,name="posts-page"), path("all_posts/<slug:slug>",views.post_details,name='posts-details-page'), #posts/my-first-post ] views.py from datetime import date from django.shortcuts import render def get_date(all_posts): return all_posts['date'] def starting_page(request): sorted_post = sorted(all_posts,key=get_date) latest_post = sorted_post[-3:] return render(request,'blogapp/index.html',{'posts':latest_post}) def posts(request): return render(request,'blogapp/all-posts.html',{'all_posts':all_posts}) def post_details(request,slug): identified_post=next(post for post in all_posts if post['slug']==slug) return render(request,'blogapp/post-details.html',{'post':identified_post}) index.html {% extends "_base.html" %} {% load static %} {% block title %} Home {% endblock %} {% block css_files %} <link rel="stylesheet" href="{% static 'blogapp/post.css' %}"/> <link rel="stylesheet" href="{% static 'blogapp/index.css' %}"/> {% endblock %} {% block content %} <section id="welcome"> <header> <img src="{% static 'blogapp/images/max.png' %}" alt="Max= The author of this Blog"/> <h2>Demo blog des</h2> </header> <p>Hi, this is the our first blog</p> </section> <section id="latest-posts"> <h2>My latest thoughts</h2> <ul> {% for post in posts %} {% include 'blogapp/includes/post.html' %} {% endfor %} </ul> </section> <section id="about"> <h2>What I do </h2> <p>I love programming</p> … -
Efficient way of rank update based on points
User_team=User_team.objects.filter().values(), User_team=[{team_id:1, points:50},{team_id:2, points:30},{team_id:3, points:70}] I already migrate New model and key is (rank,point) stored rank and points in this model. User_team_event=User_team_event.objects.filter().values(). I'm expecting answer is without using loops: User_team_event=[{team_id:3,rank:1, points:70},{team_id:1,rank:2, points:50},{team_id:2, points:30}] -
What is the Sever IP Address
Hi sir i have hosted my python application on pythonanywhere and i am using external api which required ip whitelisting for payment processing , I would like to know the sever ip and is it static or dynamic I am unable to locate the sever ip from my dashboard. -
This field is required error in the "Form" class
I have a problem in my form. When I print the error it says "The field is required". can anyone tell me what I am missing. here is my code forms.py: from django import forms class LoginAuth(forms.Form): Email= forms.EmailField() Password= forms.CharField(max_length=300) views.py: from django.shortcuts import render from .forms import LoginAuth def login(request): if request.method=="POST": form = LoginAuth(request.POST) if form.is_valid(): Email= form.cleaned_data['email'] Password= form.cleaned_data['pass'] request.session['user']= Email request.session.set_expiry(2) print("The form is validated") else: print(form.errors) return render(request, "login.html") login.html: {% extends 'base.html' %} {% block content %} <form method="post"> {% csrf_token %} <input type="email" name="email" placeholder="Enter Email"> <br> <input type="password" name="pass" placeholder="Enter Password"> <br> <br> <input type="submit"> </form> {% endblock %} -
raise TypeError( TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use groups.set() instead
while creating a custom user through the postman api on django im facing this repetedly. please help me to resolve this models.py ROLES = ( (1, 'admin'), (2, 'customer'), (3, 'seller'), ) STATE_CHOICES = ( ('Odisha', 'Odisha'), ('Karnataka', 'Karnataka') ) class UserManager(BaseUserManager): def create_user(self, email, password, **extra_fields): if not email: raise ValueError('The email is not given') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.is_active = True user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if not extra_fields.get('is_staff'): raise ValueError('Superuser must have is_staff = True') if not extra_fields.get('is_superuser'): raise ValueError('Superuser must have is_superuser = True') return self.create_user(email, password, **extra_fields) class Roles(models.Model): role = models.SmallIntegerField(choices=ROLES) class Custom_User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=100, unique=True) password = models.CharField(max_length=100) first_name = models.CharField(max_length=100, null=True, blank=True) last_name = models.CharField(max_length=100, null=True, blank=True) role = models.ForeignKey(Roles, on_delete=models.CASCADE) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) def add_to_group(self): role_instance = self.role group_name = None if role_instance.role == 4: group_name = 'admin' elif role_instance.role == 5: group_name = 'customer' elif role_instance.role == 6: group_name = 'seller' if group_name: group, created = Group.objects.get_or_create(name=group_name) self.groups.set([group]) return self USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['role'] objects = UserManager() def __str__(self): return self.email def has_module_perms(self, app_label): return True def …