Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to count reviews for a product in django?
I am building an ecommerce website with django. In my models I have a Product and review model. How should i connect the two for the number of reviews and average rating attribute? This is my current models file class Product(models.Model): name = models.CharField(max_length=200, null=True, blank=True) brand = models.CharField(max_length=200, null=True, blank=True) image = models.ImageField(null=True, blank=True, default='placeholder.png') description = models.TextField(null=True, blank=True) rating = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True) price = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True) countInStock = models.IntegerField(null=True, blank=True, default=0) id = models.UUIDField(default=uuid.uuid4, max_length=36, unique=True, primary_key=True, editable=False) numReviews = [Count the number of reviews where product.id matches self.id] averageRating = [Sum up the ratings in reviews for this product and divide them by their count] def __str__(self): return str(self.name) class Review(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) rating = models.IntegerField(null=True, blank=True, default=0) comment = models.TextField(null=True, blank=True) createdAt = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, max_length=36, unique=True, primary_key=True, editable=False) def __str__(self): return f'{self.user} review for {self.product}' As you can see the numReviews and average rating columns are meant to connect both tables. I have been trying to figure out how to do it correctly with no success. Any help would be greatly appreciated -
Why is my function get_absolute_url is merging my domain into my website name?
I'm using the Django sitemap framework, and I have to use the function get_absolute_url to render the site URL in the sitemap. However, I'm facing a problem because my link is becoming: exampleio.io instead of example.io. My function in my model is it: def get_absolute_url(self): return reverse('packages', args=[self.name]) My function in the sitemap.py class ExampleSitemap(Sitemap): protocol = "https" changefreq = "weekly" priority = 0.7 limit = 500 def items(self): return Example.objects.all() I'm getting: <sitemap> <loc>http://exampleio.io/sitemap-examples.xml</loc> </sitemap> -
how to convert my html string into its own datatype?
I'm fairly new to JS and HTML, Working on a Django project now makes me crazy about it . I have passed a variable from context from Django toward html. I noticed the datatype of the data is converted to string by defualt. views.py: context = {'segment': 'index', "service_data": data } html_template = loader.get_template('index.html') return HttpResponse(html_template.render(context, request)) HTML pages <div class="card-body"><canvas id="myAreaChart" width="100%" height="40"></canvas></div> <script type="text/javascript"> const service_data = "{{ service_data }}" </script> In Javasript, I can see the datatype of service_data is string. I'd like to traverse it as a array, but it is converted to string. const data = Array.from(service_data); //this is converted to objet not arrary.. function prepareChartData(data) { var chartData = []; for (var i = 0; i < 10; i++) { let timestampe = data[i][0] let dat_list = data[i][1] chartData.push([timestampe, dat_list]); My service_data is a fairly large data from django backend, hence, I do not want to use split or something to convert it. The service_data snipet: Please ignore those &gt, etc, not sure why HTML added them, but image the data itself is a very nested dictnary. [(datetime.datetime(2022, 10, 4, 18, 35, 1, 247336, tzinfo=&lt;UTC&gt;), [[{&#x27;kubernetes_pod_name&#x27;: &#x27;kafka-rawbus-bravo-3&#x27;, &#x27;value&#x27;: 7.5456592756413645}, {&#x27;kubernetes_pod_name&#x27;: &#x27;kafka-rawbus-bravo-5&#x27;, &#x27;value&#x27;: 6.988051860579239}, {&#x27;kubernetes_pod_name&#x27;: … -
Simple JWT Method Not Allowed on Django App deployed on Gcloud App Engine
I am fairly new to django and gcloud and I am currently stuck at this issue where I am trying deploy my Django App on Gcloud App Engine. When accessing the api for getting token I got this error. Error when accessing API from App Engine from django.contrib import admin from django.urls import include, path from rest_framework_simplejwt import views as jwt_views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('quitnow/', include('quitnow.urls')), path("admin/", admin.site.urls), path('api/token/', jwt_views.TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', jwt_views.TokenRefreshView.as_view(), name='token_refresh'), ] This is my urls.py. When I try to post my information to get token, the post requests doesn't return a response and hangs. I am stuck on this for days. Would really appreciate any help! -
The logic of if statement and (return redirect) in django
def set_default(request, id): Address.objects.filter(customer=request.user, default=True).update(default=False) Address.objects.filter(pk=id, customer=request.user).update(default=True) previous_url = request.META.get("HTTP_REFERER") if "delivery_address" in previous_url: return redirect("checkout:delivery_address") return redirect("account:addresses") This is a function that sets address to default and if the user came from checkout address page it sets default and return to same page.My question is about the logic of the if statment here.As far as I understand..If the condition is true return redirect("checkout:delivery_address") will be executed and it will exit the if condition then the last line will be executed return redirect("account:addresses") Why doesn't that happen and only the statment after if is executed when the condition is true? -
Best Python Framework suitable with Blockchain Database
As a side project, I have a web application idea, and I want to use Python at the backend. Firstly, I will use a conventional database. But after finishing the web application, I am planning to switch the database with a blockchain-based database like BigchainDB, or I will implement my blockchain. So my question is, which Python framework best suits this kind of database system? -
Update Django Formsets with data on many_to_many field
I feel like I've exhausted my google-fu on this subject. I've tried so many different ways, I can't remember what I've tried. I have a class "Recipe" which has 3 many_to_many fields. I've got an empty form using formsets for each many_to_many object for new. I'm now modifying the form to include "update", but I cannot seem to get the formsets to populate the data. I've tried "instance=", I've tried passing in a dictionary "model_to_dict", but I can't seem to figure this out. My current iteration looks like this: models.py: class Recipe(models.Model): def __str__(self): return self.name class Meta: unique_together = ('name', 'version') bs_file = models.FileField(storage=fs,null=True) name = models.CharField(max_length=75) dateCreated = models.DateField() dateUpdated = models.DateField(null=True, blank=True) version = models.IntegerField(null=True, blank=True) #type = models.CharField(max_length=30) #Cider, Mead, Wine, etc category = models.ForeignKey(BatchCategory,on_delete=models.CASCADE) brewer = models.CharField(max_length=30, null=True) batchSize = models.FloatField() #in Liters source = models.CharField(max_length=50, null=True) #Where did the recipe come from pairing = models.CharField(max_length=250, null=True) # Textfield listing various foods. TODO: Refactor notes = models.TextField() estOG = models.FloatField() estFG = models.FloatField() estABV = models.FloatField() fermentables = models.ManyToManyField(RecipeFermentable) adjuncts = models.ManyToManyField(RecipeAdjunct) yeasts = models.ManyToManyField(RecipeYeasts) You can see my 3 many_to_many fields at the bottom. views.py: def addRecipe(request,pk=None): if request.method == "GET": form = RecipeAddForm() … -
give a category using the action in django admin
can I use django actions to give a category to my articles? class Category(models.Model): name = models.CharField(max_length=155, db_index=True) class Woman(models.Model): title = models.CharField(max_length=255) content = models.TextField(blank=True) photo = models.ImageField(upload_to='img', blank=True) time_create = models.DateTimeField(auto_now_add=True) time_update = models.DateTimeField(auto_now=True) is_published = models.BooleanField(default=True) cat = models.ForeignKey(Category, on_delete=models.PROTECT,null=True) How can i create an action with the help of which it will be possible to give categories for several articles. I mean something like that https://docs.djangoproject.com/en/4.0/ref/contrib/admin/actions/ -
How to send emails from a contact form to recipient? Django
When I click the 'Send Message' button it gives me the message that it sent, but when I check my email the email is not there. Any help please? This is my first web application using Django. this is what it says in Git Bash after I send the message this is the index.html this is the views.py file this is the contact form, the contact form was made in index.html this is the settings.py file -
How to pass model instance pk to template from Django modelformset?
I have a model that I want to display in a template with a modelformset. I want to be able to delete instances of the model by pressing a button in the template, but I can't seem to pass the instance's pk. The "id" field only passes a huge boundfield that generates and error when I use it for the delete button. Is there any way to pass the instance's pk to the template? models.py class Activity(Model): user = ForeignKey(settings.AUTH_USER_MODEL, on_delete=CASCADE) activity = CharField(max_length=100, default='') number = IntegerField(default=1) def __str__(self): return self.activity Built in a formset: views.py activities = Activity.objects.filter(user=request.user) pre_formset = modelformset_factory(Activity, fields=('activity', 'number', 'id',)) formset = pre_formset(queryset=activities) template.html { formset.management_form }} {% for activity in formset %} {{ activity.id }} {{ activity.ORDER }} {{ activity.DELETE }} {% if not forloop.first %} <a class="btn" href="{% url 'activity_delete' activity.pk %}" onclick="return confirm('Are you sure you want to delete this activity?')">X</a> {% endif %} {% endfor %} -
json as table with django
I have modeled my database using models.py within my django project, one of the fields is a JSONField and I can save json data into that field without any problem. My doubt comes in how I can show that information as an html table. At the moment I have been using ListView to show that information in a template but I don't know how to transform it into a table. -
NGINX 403 (Forbidden) - Django React project
Hello i have problem with my Django React project .. i have 403 error on static files(js, css)..Error 403 NGINX Django -
Django Model Form field data not displaying
So I am trying to figure out why my dropdown menu will not display the list of collections for the user to pick from. IMAGE: [1]: https://i.stack.imgur.com/UIrq6.png Here is also the code for the 2 models here: class Collection(models.Model): title = models.CharField(max_length=255) def __str__(self) -> str: return self.title class Meta: ordering = ['title'] class listing(models.Model): image = models.ImageField(blank=True, null=True) name = models.CharField(max_length=255) description = models.TextField() unit_price = models.DecimalField(max_digits=6, decimal_places=2, validators=[MinValueValidator(1)]) inventory = models.IntegerField() last_update = models.DateTimeField(auto_now=True) collection = models.ForeignKey(Collection, on_delete=models.PROTECT, blank=True, null=True) vendors = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=False) IF I CAN GET ANY HELP IT WOULD BE NICE. -
How to check the current isolation level setting in Django?
I'm trying to check the current isolation level setting in Django. For example, the default isolation level setting in Django is READ COMMITTED so if there is transaction.current_isolation_level(), I can print READ COMMITTED on console to check the current isolation level setting in Django as shown below: # "views.py" from django.http import HttpResponse from django.db import transaction @transaction.atomic def test(request): # Here print(transaction.current_isolation_level()) # READ COMMITTED return HttpResponse("Test") And if I set REPEATABLE READ for the isolation level setting in Django as shown below: DATABASES = { 'default':{ 'ENGINE':'django.db.backends.postgresql', 'NAME':'postgres', 'USER':'postgres', 'PASSWORD':'admin', 'HOST':'localhost', 'PORT':'5432', }, 'OPTIONS': { # Here 'isolation_level': psycopg2.extensions.ISOLATION_LEVEL_REPEATABLE_READ, }, } I can print REPEATABLE_READ on console to check the current isolation level setting in Django as shown below: # "views.py" from django.http import HttpResponse from django.db import transaction @transaction.atomic def test(request): # Here print(transaction.current_isolation_level()) # REPEATABLE READ return HttpResponse("Test") So, are there such functions or variables to get the current isolation level setting in Django? If no, how to check the current isolation level setting in Django? -
Authentication verification message is not displaying as a hyperlink in the mail but rather displaying as a text in the email. please, help me
views.py under my views I have all my views for user authentication which includes: signin, signup, signout and other function views. from django.core.mail import EmailMessage,send_mail from django.shortcuts import render,redirect from django.contrib import messages from django.contrib.auth import authenticate,login,logout from my_site.settings import EMAIL_HOST_USER from django.core.mail import send_mail from django.contrib.sites.shortcuts import get_current_site from django.template.loader import render_to_string from django.utils.http import urlsafe_base64_encode,urlsafe_base64_decode from django.utils.encoding import force_bytes,force_str from .tokens import generate_token from .models import User # Create your views here. def all(request): return render(request,'authentication/all_signups.html') def signup(request): if request.method == "POST": username = request.POST.get("username") fname = request.POST.get("fname") lname = request.POST.get("lname") email = request.POST.get("email") password = request.POST.get("password") password2 = request.POST.get("password2") if User.objects.filter(username=username): messages.error(request, "Username already exist!") return redirect('home') if User.objects.filter(email=email): messages.error(request, "E-mail already exist!") return redirect('home') if len(username) > 15: messages.error(request, "Length of username too long!") return redirect('home') if password != password2: messages.error(request, "Passwords do not match!") return redirect('home') if not password.isalnum(): messages.error(request, "Password must be alphanumeric!") return redirect('home') user = User.objects.create_user(username=username,email=email,password=password) user.fname = fname user.is_active = False user.save() # Welcome E-mail subject = 'Welcome to ADi meals mobile!' message = f'Hello {fname.capitalize()}, welcome to ADi meals mobile!\n\nThank you for visiting our website.\n\nWe have also sent you a confirmation email, please confirm your email address to login into … -
Form returning not valid in django
In my django app I have a User model that has a Boolean field of is_manager. User model in models.py: class User(AbstractUser): name = models.CharField(max_length=15, null=True, blank=True) last_name = models.CharField(max_length=15, null=True, blank=True) title = models.CharField(max_length=50, null=True, blank=True) email = models.EmailField(unique=True) bio = models.TextField(null=True, blank=True) company = models.ForeignKey(Company, on_delete=models.DO_NOTHING, null=True) is_manager = models.BooleanField(default=False) can_assign = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] I've been trying to create an edit page in order for managers and users to be able to change some of their fields. Regular users should be able to change their bio and title, and the managers can change the can_assign Boolean. I have a form that deals with the logic of that in forms.py: class EditUserForm(ModelForm): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') if self.user.is_manager: super().__init__(**kwargs) else: super().__init__(**kwargs) del self.fields['can_assign'] class Meta: model = User fields = ['title', 'can_assign', 'bio'] views.py: @login_required def editUser(request, pk): user = User.objects.get(id=pk) if request.user.is_manager or request.user == user: #POST if request.method == 'POST': form = EditUserForm(request.POST, instance=user, user=request.user) if form.is_valid(): form.save() redirect('user-page', pk) else: print('nope') #GET form = EditUserForm(user=request.user, instance=user) context = {'user': user, 'form': form} return render(request, 'users/user_edit.html', context) else: return HttpResponse('<h1>Access Denied</h1>') template: {% extends 'main.html' %} {% block content … -
CircleCI config for django
I have this circleci config version: 2.1 orbs: python: circleci/python@0.2.1 jobs: build: executor: python/default docker: - image: circleci/python:3.9 environment: DATABASE_URL: postgresql://circleci@localhost/circle_test - image: circleci/postgres:13.3 environment: PGHOST: localhost PGUSER: circleci POSTGRES_USER: circleci POSTGRES_DB: circle_test POSTGRES_HOST_AUTH_METHOD: trust steps: - checkout - python/load-cache - run: name: Installing dependencies command: | python3 -m venv venv . venv/bin/activate pip3 install -r requirements.txt - python/save-cache - run: name: Running tests command: | . venv/bin/activate python manage.py test When i commit django-test with TestCase, only choose test with SimpleTestCase, circleci comlete, but when i uncomment TestCase i have this errors RuntimeWarning: Normally Django will use a connection to the 'postgres' database to avoid running initialization queries against the production database when it's not needed (for example, when running tests). Django was unable to create a connection to the 'postgres' database and will use the first PostgreSQL database instead -
How Do I Override GET in Django Detailview?
I have a FORMVIEW that is redirecting to a DETAILVIEW and that is working perfectly. The issue I'm having is when I try to combine Pagination with DetailView. When I try to leverage the pagination, the GET is essentially redirecting me to the FORMVIEW. I get why it's doing this...I'm telling it to. What I'm trying to work out is how I can put in some logic in my overridden GET. I tried to do a self.GET_OBJECT.pk...to see if I could determine if I'm on the current page and not the FORMVIEW but that didn't work... Here's my DetailView.... def get_context_data(self, **kwargs): context = super(SuggestionByNameDetailView, self).get_context_data(**kwargs) attachments = SuggestionFiles.objects.filter(suggestion=self.object.pk).all() comment_form = SuggestionCommentForm() response_form = SuggestionCommentReplyForm() activities= self.get_related_activities() context['suggestion_comments'] = activities context['page_obj'] = activities context['attachments'] = attachments context['comment_form'] = comment_form context['response_form'] = response_form return context def get_related_activities(self): queryset = self.object.suggestion_comments.all() paginator = Paginator(queryset,5) #paginate_by page = self.request.GET.get('page') activities = paginator.get_page(page) return activities def get_object(self, queryset=None): return get_object_or_404(Suggestion, id=self.request.GET.get("dropdown")) def get(self, request, *args, **kwargs): dropdown=self.request.GET.get("dropdown") if dropdown is not None: if Suggestion.objects.filter(Q(id=self.request.GET.get("dropdown"))).distinct(): self.object = self.get_object() context = self.get_context_data(object=self.object) return self.render_to_response(context) else: raise Http404 else: messages.add_message(self.request, messages.INFO, 'Suggestion is required.') return HttpResponseRedirect(reverse('Suggestions:suggestion_by_name')) As mentioned I did try to do something like...if DROPDOWN is … -
Insert multi selected option text into pg using django
For instance, I used Django to pull certain unique number data from my database. Then I created dropdown with search using select2. And used jQuery for search functionality. With this I could select multiple unique number at a time and with output printed in textarea field. my question is, how to insert multiple selected options in Postgrel using Django. I need help in backend as i m newbie in django I tried to served everywhere but I could see only php guide. this is my frontend code enter code here Search Models for CId {% csrf_token %} {% for x in searchmodels %} {{ x.cid }} {% endfor %} You can add multiple CID and click Add --> <br> <div class="resultbox"> <h2>Selected CIDs</h2> <textarea name="" id="cidresult" cols="70" rows="15"></textarea><br><br> <input type="button" id="addcid" value="Submit" onclick="searchresult();"> </div> </form> </tr> <style> .resultbox{ position: fixed; left: 30%; top: 10px; width: 550px; background-color: antiquewhite; padding-left: 30px; padding-right: 10px; } </style> Now here is my jQuery code $(document).ready(function() { $('#selectedcid').select2({ placeholder:'Search CID...', closeOnSelect:false }); $('#selectedcid').on('change',function() { var resultdisplay=$('#selectedcid option:selected').text(); $('#cidresult').val(resultdisplay).join(','); }) }); this is how it looks nowenter image description here -
Django custom permission not being assigned to newly created User
This seems pretty trivial but I can't figure out what I'm doing wrong. I've checked several SO posts that sounded similar but the issue apparently lies elsewhere. I have a custom permission on my model, can_key, and this is registered properly. When I try to add this permission to a newly created user, it's not added. from django.contrib.auth import get_user_model from django.contrib.auth.models import Permission def create_dummy_user(self, username): username = 'dummy_user' user = get_user_model().objects.create(username=username, password='asdf4321') user.save() user = get_user_model().objects.get(username=username) permission = Permission.objects.get(codename="can_key") print(permission) user.user_permissions.add(permission) user = get_user_model().objects.get(username=username) print(f"{user.username} is_active - {user.is_active}") print(f"{user.username} has perm {permission.codename} - {user.has_perm(permission)}") return user This is the print outputs test_web | main_app | record case | Can key record case test_web | dummy_user is_active - True test_web | dummy_user has perm can_key - False So the user was created and the permission exists / is retrieved, but the permission isn't being added. Why? -
The styles and javascript files aren't showing when deploy Django application to a2hosting CPanel
I've deployed my Django application to the a2hosting web hosting the styles aren't showing. Also, the page that has swagger documentation is blank and doesn't have anything. Here in the image, you can see how the Admin page is showing. admin page I've made collectstatic and here is the setting.py configurations: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') -
How to send emails using Django All auth?
I'm trying to send emails for signup/account verification etc using django allauth, and it has worked correctly during development using the console as the email backend, however now I'm trying to send emails in using gmail, I'm getting the below error: SMTPAuthenticationError at /accounts/password/reset/ (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials q1-20020adfdfc1000000b0022e049586c5sm11068760wrn.28 - gsmtp') I've tried following the steps in the article mentioned in the error message, but they haven't worked. Not sure what I'm doing wrong, any help would be much appreciated! EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = 'example@gmail.com' EMAIL_HOST_PASSWORD = '*****' -
Django Rest Framework: Not sending email from react form Error 400
I'm trying to send a form using the API endpoint beneath. The problem is that I get a 400 error when I use my react based application. If I'm using the api endpoint page it works. I checked the payload and the only difference seems to be that i'm not sending a csrf token in my react app. So far it was never neccesary when i used model serializers. I believe it is something inside the serializer but i cannot pin it down. Does anyone know what might be causing the 400 error? sendEmail.js const testmessage = "This is a test message" const testemail = "dsfds@dsfg.de" const clientnametest = "name" function sendProposal(values) { console.log("start sending proposal..."); setSendProp(true) const data = new FormData() data.append("Clientname", clientnametest || ""); data.append("Sender", testemail || ""); data.append("Message", testmessage || ""); axios.post(API.email.proposal, data, { headers: { "Authorization": `Bearer ${accessToken}`, 'Accept' : 'application/json', }, withCredentials: true, }) .then(res => { }) .finally(() => { setSendProp(false) }) success() } views.py class ProposalEmailView(APIView): permission_classes = [IsAuthenticated] serializer_class = ProposalEmailSerializer def post(self, request, *args, **kwargs): serializer_class = ProposalEmailSerializer(data=request.data) if serializer_class.is_valid(): data = serializer_class.validated_data ClientName = data.get('ClientName') Sender = data.get('Sender') Message = data.get('Message') send_mail('Contact Form mail from ' + ClientName, Message, Sender, … -
An admin view should be created to view the saved data.Create a employee database and create following api's
Add new employee Get employee by emp_id delete employee by id update employee salary -
How to validate unique attribute values of an object in respect to that object's other attributes?
I am making a school management system where each student takes 6 subjects. After trying to make dependent dropdown lists, I felt like it wasn't suited for what I was trying to achieve and I failed to implement them. I want to validate that each student's attributes concerning the subjects they're taking is unique, so that there aren't any subjects being taken twice (e.g. to prevent having Chemistry in science and Chemistry in science2) models.py from unittest.util import _MAX_LENGTH from django.db import models from django.utils.translation import gettext_lazy as _ from students.choices import * from django.core.exceptions import ValidationError # Create your models here. class Student(models.Model): def __init__(self, student_number, first_name, last_name, email, english, math, language, science, science2): self.student_number = student_number self.first_name = first_name self.last_name = last_name self.email = email self.english = english self.math = math self.language = language self.science = science self.science2 = science2 def __len__(self): return len(vars(self)) student_number = models.PositiveIntegerField() first_name = models.CharField(max_length=50) #Attribute containing student's first name, cannot exceed 50 characters last_name = models.CharField(max_length=50) #Attribute containing student's last name, cannot exceed 50 characters email = models.EmailField(max_length=100) #Attribute containing student's email, cannot exceed 100 characters #Subjects english = models.CharField(max_length=2, choices=English.choices, null=True, blank=False) math = models.CharField(max_length=2, choices=Math.choices, null=True, blank=False) language = models.CharField(max_length=1, …