Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to ADD registration email verifiction to my Django app
How to ADD registration email verifiction to my django app? I want to add an email registration verification and email and password reminder? my big problem solving -
Cannot resolve keyword 'slug' into field
Im making comment and reply system in my blog using Django. Now im trying to get queryset of comments that dont have reply comments(if I dont do this, reply comments will be displayed on a page as regular comments). Here is error that i got: FieldError at /post/fourh-news Cannot resolve keyword 'slug' into field. Choices are: comm_to_repl, comm_to_repl_id, comment_content, created, id, post, post_of_comment, post_of_comment_id, replies, user_created_comment, user_created_comment_id Request Method: GET Request URL: http://127.0.0.1:8000/post/fourh-news Django Version: 4.1.2 Exception Type: FieldError Exception Value: Cannot resolve keyword 'slug' into field. Choices are: comm_to_repl, comm_to_repl_id, comment_content, created, id, post, post_of_comment, post_of_comment_id, replies, user_created_comment, user_created_comment_id Exception Location: D:\pythonProject28django_pet_project\venv\lib\site-packages\django\db\models\sql\query.py, line 1709, in names_to_path Raised during: blog.views.ShowSingleNews Python Version: 3.10.4 Model: class Post(models.Model): title = models.CharField(max_length=150, verbose_name='Название') slug = models.CharField(max_length=100, unique=True, verbose_name='Url slug') content = models.TextField(verbose_name='Контент') created_at = models.DateTimeField(auto_now=True, verbose_name='Дата добавления') updated_at = models.DateTimeField(auto_now=True, verbose_name='Дата обновления') posted_by = models.CharField(max_length=100, verbose_name='Кем добавлено') photo = models.ImageField(upload_to='photos/%Y/%m/%d', verbose_name='Фото', blank=True) views = models.IntegerField(default=0) category = models.ForeignKey('Category', on_delete=models.PROTECT, verbose_name='Категория') tag = models.ManyToManyField('Tags', verbose_name='Тэг', blank=True) comment = models.ForeignKey('Comment', verbose_name='Комментарий', on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('single_news', kwargs={'slug': self.slug}) class Meta: ordering = ['-created_at'] class Category(models.Model): title = models.CharField(max_length=150, verbose_name='Название') slug = models.CharField(max_length=100, unique=True, verbose_name='category_url_slug') def __str__(self): return self.title def … -
How to access queryset values in a dictionary - Python
I'm trying to access the queryset of this dictionary with no success: {'post': <Post: alta papa>, 'distance': '0'} I've tried for thing in post... but is giving me a str value... instead of the queryset... Any help will be welcome. -
Django send password reset link via email when new user account added
I am working on an application where admins will create new user accounts. A randomized password is auto-generated when the user is added. Ideally an email will be automatically sent to the new user with a link to reset their password (It will not include the autogenerated password). I could figure out how to send an email with link to a page to enter an email to get a password reset link. However, I would like to avoid the extra steps and simply send the link to reset the password. Any suggestions about how to trigger and send this link? The model: from django.db import models from django.contrib.auth.models import AbstractUser from django.contrib.auth.models import Group from django.contrib import admin from django.db.models import Count from django.db.models.signals import post_save class CustomUser(AbstractUser): full_name = models.CharField(max_length=250, null=True) age = models.PositiveIntegerField(null=True, blank=True) employee_type = models.ForeignKey(Group, null=True, on_delete=models.SET_NULL, default=1) employee_start_date = models.DateField(null=True, blank=True) is_active = models.BooleanField(null=False, default=True) The view: class AddCompanyEmployee(CreateView): model = CustomUser template_name = 'manage/add_employee.html' form_class = BrowserCreateUserForm success_url = reverse_lazy('directory') def form_valid(self, form): password = CustomUser.objects.make_random_password() account = form.save(commit=False) account.password = make_password(password) account.save() return super().form_valid(form) The form: class BrowserCreateUserForm(forms.ModelForm): class Meta: model = CustomUser fields = ['username','full_name', 'email', 'employee_type', 'employee_start_date', 'is_active'] widgets = { … -
Python script inside of html <script> tag
this is html template in Django. I have Mapbox map and i need to pass markers from Django database via forcycle "{% for address in addresses %}... " ` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src='https://api.mapbox.com/mapbox-gl-js/v2.1.1/mapbox-gl.js'></script> <link href='https://api.mapbox.com/mapbox-gl-js/v2.1.1/mapbox-gl.css' rel='stylesheet' /> <title>Document</title> </head> <body> <h1>Django Home</h1> <form method='POST'> {% csrf_token %} {{ form }} <input type="submit" value="submit address" /> </form> <div id='map' style='width: 100%; height: 600px;'></div> <script> mapboxgl.accessToken = '{{ mapbox_access_token }}'; var map = new mapboxgl.Map({ container: 'map', // container ID style: 'mapbox://styles/mapbox/streets-v11', // style URL center: [-111.061854, 45.695711], // starting position [lng, lat] zoom: 11 // starting zoom }); {% for address in addresses %} var marker = new mapboxgl.Marker() .setLngLat([{{ address.long }}, {{ address.lat }}]) .setPopup(new mapboxgl.Popup().setHTML("<p>{{ address.address }}</p>")) .addTo(map); {% endfor %} </script> </body> </html> ` Source code: https://github.com/Simonm17/mapbox_demo/blob/master/templates/addresses/home.html This code above from Github works fine for author in Youtube video, but i got red underline text and nothing happens. How i can combine python script inside html tag and pass markers from python? Thx! -
Passing variable to inherited template in Django
I want to list servers in the sidebar. Server data comes from database. All the pages will have the sidebar and sidebar is in the inherited template. I found one solution: Passing via middleware I can write a custom middleware, so I can pass the servers to request object. But at this point I have to pass servers variable again and again to the templates and inherited template in each view. This is a lot of repeated code. Is there a cleaner solution? -
Django - issue with Not Null constraint
Hi in my program I keep receiving the above exception and am unsure why. The issue happens when my requestLessons_view method tries to save the form. Views.py def requestLessons_view(request): if request.method == 'POST': form = RequestLessonsForm(request.POST) if form.is_valid() & request.user.is_authenticated: user = request.user form.save(user) return redirect('login') else: form = RequestLessonsForm() return render(request, 'RequestLessonsPage.html', {'form': form}) forms.py class RequestLessonsForm(forms.ModelForm): class Meta: model = Request fields = ['availability', 'num_of_lessons', 'interval_between_lessons', 'duration_of_lesson','further_information'] widgets = {'further_information' : forms.Textarea()} def save(self, user): super().save(commit=False) request = Request.objects.create( student = user, availability=self.cleaned_data.get('availability'), num_of_lessons=self.cleaned_data.get('num_of_lessons'), interval_between_lessons=self.cleaned_data.get('interval_between_lessons'), duration_of_lesson=self.cleaned_data.get('duration_of_lesson'), further_information=self.cleaned_data.get('further_information'), ) return request models.py class Request(models.Model): student = models.ForeignKey( User, on_delete=models.CASCADE ) availability=models.CharField(blank=False, max_length=5) num_of_lessons=models.CharField(blank=False,max_length=40) interval_between_lessons=models.CharField(blank=False,max_length=30) duration_of_lesson=models.CharField(blank=False,max_length=60) further_information=models.CharField(blank=False,max_length=300) is_fulfilled=models.BooleanField(default=False) The error I receive is: IntegrityError at /request_lessons/ NOT NULL constraint failed: lessons_request.student_id -
django how to generate commercial offers
I am developing a business website in django. and there was a task - to add the ability to generate commercial offers. it is necessary for the user to be able to select a product from the database, and after that the remaining fields (category, price, description, photo) would be automatically substituted. I do not quite understand how to implement it correctly. Is it possible to do this in the admin panel or do I need to create a new page and write all the logic in views. models.py: class product(models.Model): title = models.CharField(max_length = 100) slug = models.SlugField(max_length=100, unique=True, db_index=True, verbose_name="URL") category = TreeForeignKey(Catalog, on_delete=models.PROTECT) manufacturer = models.ForeignKey(manufacturer, on_delete = models.PROTECT) image = models.FileField(upload_to='photos/', blank=True) price = models.IntegerField() description = models.TextField() technikal_description = models.TextField() technikal_param = models.TextField() manufacturer_code = models.IntegerField() our_code = models.IntegerField() def __str__(self): return self.title def return_category(self): return self.category I assume that you need to make up a new page and link it to models.py -
How can I unit tests for this Django Form
I do coverage report and there are many place that not cover, do you have any idea how to I write test for th? this views.py was not cover def addreview(request, u_id, shop_id): url = request.META.get('HTTP_REFERER') shop = shop_detail.objects.get(id=shop_id) user = cs.objects.get(customer=u_id) if request.method == 'POST': form = ReviewForm(request.POST) if form.is_valid(): data = Review() data.review_text = form.cleaned_data['review_text'] data.review_rating = form.cleaned_data['review_rating'] data.shop = shop data.user = user data.save() return redirect(url) def rating(request): if not request.user.is_authenticated: return HttpResponseRedirect(reverse('customer_login')) if request.method == 'POST': form = RateUsForm(request.POST) if form.is_valid(): rate = RateUs() rate.rate_text = form.cleaned_data['rate_text'] rate.rating = form.cleaned_data['rating'] rate.user = request.user rate.save() return HttpResponseRedirect(reverse("index")) return render(request, 'shop/rate.html') models.py class Review(models.Model): user = models.ForeignKey(Profile,on_delete=models.CASCADE) shop = models.ForeignKey(shop_detail,on_delete=models.CASCADE) review_text = models.TextField(max_length=300) review_rating = models.IntegerField() def __str__(self): return f"{self.review_rating}" class RateUs(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) rate_text = models.TextField() rating = models.IntegerField() def __str__(self): return f"{self.rating}" forms.py class ReviewForm(forms.ModelForm): class Meta: model= Review fields= ["review_text", "review_rating"] class RateUsForm(forms.ModelForm): class Meta: model= RateUs fields= ["rate_text","rating"] This is what I write for rating def test_valid_rating(self): rateus1 = RateUs.objects.first() data={ "user": rateus1.user, "rate_text": rateus1.rate_text, "rating": rateus1.rating } response = self.client.post(reverse('rating'), data=data) self.assertEqual(response.status_code, 302) When I try to write test for addreview i got customer.models.Profile.DoesNotExist: Profile matching query does not exist. -
Allow users to create ingredients using a CreateView and ManyToMany field
I have a form where users can create ingredients using a jQuery Plugin for Custom Tags. Submitting the form results in the error Field 'id' expected a number but got 'b'. where each letter in the ingredient (vs the word) is being picked up as an item that's expected to already exist in the database. # form.py class EatForm(forms.ModelForm): notes = forms.CharField(widget=forms.Textarea(attrs={"rows":3}),required=False) ingredient = forms.CharField(widget=forms.TextInput(),required=False) allergen = forms.CharField(widget=forms.TextInput(),required=False) class Meta: model = Eat fields = ["name", "notes", "meal","ingredient","allergen","favorite","datetime"] # Models class Eat(models.Model): MEAL_CHOICES = ( ("breakfast", "Breakfast"), ("lunch", "Lunch"), ("dinner", "Dinner"), ("supper", "Supper"), ("snack", "Snack"), ("drink", "Drink"), ) id = models.BigAutoField(primary_key=True, editable=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=255) notes = models.CharField(max_length=255, blank=True, null=True) meal = models.CharField(choices=MEAL_CHOICES, max_length=20) ingredient = models.ManyToManyField(Ingredient,blank=True) allergen = models.ManyToManyField(Allergen,blank=True) favorite = models.BooleanField(default=False) datetime = models.DateTimeField() # View class EatFormAddView(LoginRequiredMixin, CreateView): model = Eat template_name = "dashboard.html" success_url = reverse_lazy("core:activity") form_class = EatForm # get user # def get_object(self): # return self.request.user # determine which submit button was pressed def form_valid(self, form): form.instance.user = self.request.user ingredients = form.cleaned_data['ingredient'].split(',') for ingredient in ingredients: try: ingredient_obj = Ingredient.objects.get(name=ingredient) except: ingredient_obj = Ingredient(name=ingredient) ingredient_obj.save() return super().form_valid(form) -
Django social-auth-app-django cannot login & show Authentication process canceled
There is a problem when I upload my django application to the hosting. That is, when I logged in using Google OAuth after selecting a Google account, an error suddenly appeared AuthCanceled at /auth/complete/google-oauth2/. But, I didn't do anything during the login process. So, why was the authentication process canceled? When run on localhost, the application runs smoothly. But, when run on hosting it will be like that. I don't know what happened. settings.py DEBUG = True ALLOWED_HOSTS = ['*', 'siadis.mydomain.sch.id'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'website.apps.WebsiteConfig', 'quiz.apps.QuizConfig', 'django.contrib.humanize', 'social_django' ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ BASE_DIR / "templates/" ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.template.context_processors.media', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] AUTHENTICATION_BACKENDS = ( 'social_core.backends.google.GoogleOAuth2', 'django.contrib.auth.backends.ModelBackend', ) SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = 'my id client' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'my secret cliend' LOGIN_REDIRECT_URL = '/' LOGIN_ERROR_URL = '/login/failed/' LOGIN_URL = '/login/' SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.social_auth.associate_by_email', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) SOCIAL_AUTH_GOOGLE_OAUTH2_AUTH_EXTRA_ARGUMENTS = { 'access_type': 'offline', 'approval_prompt': 'auto', 'redirect_uri': 'https://siadis.mydomain.sch.id/auth/complete/google-oauth2/' } error Request Method: GET Request URL: http://127.0.0.1:51457/auth/complete/google-oauth2/?state=4XEytKWxSU62AuZjlOr888SjzXe1XjEg&code=4%2F0AfgeXvvepRVcezejl-IwUwh6QVw9-AJnZzaz42my-QDlsEFWko2IFWwRml2UH9TRq_RZXw&scope=email+profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email&authuser=2&prompt=none Django Version: 3.2.14 Python Version: 3.8.9 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'website.apps.WebsiteConfig', 'quiz.apps.QuizConfig', 'django.contrib.humanize', 'social_django'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', … -
Django app.get_models giving partial model list
I have django app which contains model segregated such that models/new and models/old, where both have models.py in it. So when I try django.app.get_models it's returning models of models/old folder. What can be done to get all models from both folder? Django app.get_models giving partial model list. It should give all the models containing in each folder. -
UpdateView - save as new record
What's the best method of saving an existing record as a new record when in a specific view? models.py class videos(models.Model): title = models.CharField(max_length=250) fk_type = models.ForeignKey('mediaTypes',on_delete=models.CASCADE) b_template = models.BooleanField(default=False) class mediaTypes(models.Model): name = models.CharField(max_length=250) e.g. 1 - Football game - 4 - TRUE 2 - Superbowl X highlights - 4 - FALSE 3 - Superbowl XX highlights - 4 - FALSE 4 - Home movies - 2 - TRUE 5 - Finding Holy Gail under house - 2 - FALSE forms.py from django import forms from django.forms import ModelForm from .models import (videos) class create_football(ModelForm): class Meta: model = videos fields = '__all__' views.py from django.shortcuts import render, get_object_or_404, redirect from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from django.urls import reverse from django.contrib import messages from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.contrib.auth.models import User, AbstractBaseUser, BaseUserManager, PermissionsMixin from django.contrib.auth.decorators import login_required from django.db.models import Q # filter using operators '&' or '|'. from django.utils import timezone from users.models import Profile from django.forms import ModelForm from django.http import HttpResponseRedirect from .models import (videos) from .forms import (create_football) class templates(LoginRequiredMixin, ListView): model = videos template_name = 'videos/templates.html' context_object_name = 'video' def get_queryset(self): profile = get_object_or_404(Profile, user=self.request.user) queryset = videos.objects.filter(Q(fk_type="4") return … -
search data with multiple values in django
Want to filter data with multiple values in django.Currently i can only take two value from html but only one value filtering This is my views code p = request.GET.getlist('passout',[]) c = request.GET.getlist('course',[]) s = request.GET.getlist('skill',[]) search_variables = {} if p: for l in p: search_variables['passout__yearofpassing__contains'] = l print("@@@@@",p) if s: for j in s: search_variables['skill__skill_name__contains'] = j if c: for k in c: search_variables['course__course_name__contains'] = k print("@@kk",k) datas_list = Student.objects.filter( **search_variables, status="Active").order_by('id') This is html code <div class="col col-sm-3" style="margin-right:-80px;"> <select class="selectpicker" id="passout" name="passout" placeholder="Select YOP" multiple > {% for j in p %}<option value="{{ j }}" selected>{{i.yearofpassing}}</option> {% endfor %} {% for i in yr %} <option value="{{i.yearofpassing}}">{{i.yearofpassing}}</option> {% endfor %} </select> </div> <div class="col col-sm-3" style="margin-right:-80px;" > <select class="selectpicker" name="course" id="course" placeholder="Select Course" multiple > {% for j in c %}<option value="{{ j }}" selected >{{i.course_name}}</option> {% endfor %} {% for i in cr %} <option value="{{i.course_name}}">{{i.course_name}}</option> {% endfor %} </select> </div> <div class="col col-sm-3" style="margin-right: -350px;"> <select class="selectpicker" id="skill" name="skill" placeholder="Select Skills" multiple > {% for j in s %}<option value="{{ j }}" selected >{{i.skill_name}}</option>{% endfor %} {% for i in sl %} <option value="{{i.skill_name}}" >{{i.skill_name}}</option> {% endfor %} </select> </div> <button id="search4" style="margin-left: 320px; " … -
bootstrap padding from sidebar
I am creating a site from scratch using Django and bootstrap. I've created a sidebar as a Django template and used {% include 'website/components/sidebar.html' %} to include it on all pages. but for each new page, the padding between the sidebar and any other content is not aligned. How do add a margin all the way around so that any content is central to the space between the sidebar and the edge of the screen? The sidebar is using some custom CSS and the rest of the site is using bootstrap. I've wrapped the content of the next page in container-fluid but I'm not sure about the approach. -
Django YearArchiveView with date in related model
I have this one-to-one relationship between my models: class Training(models.Model): date = models.DateField(unique=True) class Report(models.Model): training = models.OneToOneField( Training, on_delete=models.CASCADE, primary_key=True ) and would like to have a yearly archive of Report: class ReportYearArchiveView(generic.YearArchiveView): queryset = Report.objects.all() date_field = "training_date" However, I get the following error: FieldError at /reports/2022/ Cannot resolve keyword 'training_date' into field. Choices are: ..., training, training_id And with date_field = "training__date" I get FieldDoesNotExist at /reports/2022/ Report has no field named 'training__date' Any ideas? -
How to retrieve 2 datas and integrate them into api view?
body I need a help please. I'm going to build a API for an abstract/easy, so I'm writing the code as following: Python3.9 Django 3.2 gunicorn psycopg2-binary requests #models.py from django.conf import settings class Abstracts(models.Model): title = models.TextField(max_length=100) first_author = models.CharField(max_length=100, blank=True, null=False) first_author_unit = models.CharField(max_length=100, blank=True, null=False) author_list = models.TextField(null=True) author_unit_list = models.TextField(null=True) #views.py from .models import Abstracts from django.shortcuts import get_object_or_404 from django.http import JsonResponse def api_abstract_view(request, id): # API get abstract apiabs = get_object_or_404(Abstracts, pk=id) datas = { "title": apiabs.title, "first_author":{"name":apiabs.first_author, "unit":[apiabs.first_author_unit]}, "author_list": {"name":apiabs.author_list, "unit":[apiabs.author_unit_list]}, } return JsonResponse({"abstract": datas}) #url.py from .views import api_abstract_view app_name = 'abstracts' urlpatterns = [ path("apiabstractview/<int:id>/", api_abstract_view, name="api_abstract_view"), ] The output of json The abstract has been created, the json I got after accessing the id by url: http://127.0.0.1:8000/apiabstractview/9/ API URL : http://127.0.0.1:8000/apiabstractview/9/ { "abstract": { "title": The name of Title, "first_author": { "name": "First Author", "unit": ["C School", "A School", "D School"] }, "author_list": { "name": "2 author, 3 author", "unit": ["A School, B School, C School"] }, } } HOWEVER.... Please help, what should I do? As the result below. The result JSON I hope as below: author_list must be separated as a property individually. { "abstract": { "title": The … -
django-allauth custom user not working properly
I am trying to use Extra Data from Social accounts but first i need to create custom user, this is my approach, fields are created but for some reason they are not set to custom_field2 = "hey" #forms.py from allauth.socialaccount.forms import SignupForm from django import forms from pprint import pprint class MyCustomSocialSignupForm(SignupForm): first_name = forms.CharField(label='First Name') last_name = forms.CharField(label='Last Name') custom_field1 = forms.IntegerField(label='Custom field 1') custom_field2 = forms.CharField(label='Custom field 2') def save(self, request): pprint(vars(request)) user = super(SignupForm, self).save(request) custom_field1 = 12 custom_field2 = "hey" user.custom_field1 = custom_field1 user.custom_field2 = custom_field2 user.save() return user #setting.py AUTH_USER_MODEL = 'MyUser.User' SOCIALACCOUNT_FORMS = {'signup': 'MyUser.forms.MyCustomSocialSignupForm'} #models.py from django.db import models from django.contrib.auth.models import AbstractUser from pprint import pprint class User(AbstractUser): custom_field1 = models.IntegerField(default=10) custom_field2 = models.CharField(max_length=20) #admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import User class CustomUserAdmin(UserAdmin): fieldsets = ( *UserAdmin.fieldsets, # original form fieldsets, expanded ( # new fieldset added on to the bottom 'Custom Field Heading', # group heading of your choice; set to None for a blank space instead of a header { 'fields': ( 'custom_field1', 'custom_field2' ), }, ), ) admin.site.register(User, CustomUserAdmin) -
Increment Integer Field in Django
I am creating a simple blogging application and would like users to be able to like a post. In terms of scalability I've decided it would be best to have likes as a separate table made up of pointers to both the user and post. I have managed to enable the post request adding a like to the model however the likes field in the post model is not incrementing. I've tried using a simple likes += 1 technique in the serializer but that made no changes and have now used an F string but still no changes are being made. I am still fairly new to Django and suspect it may be because I'm trying to update a field on a different model within a CreateAPIView serializer but I'm not sure. This is what I have so far # views.py class LikeView(generics.CreateAPIView): permission_classes = [ permissions.IsAuthenticated, ] queryset = Like.objects.all() serializer_class = LikeSerializer def like(self, request, format=None): serializer = self.serializer_class(data=request.data) if(serializer.is_valid()): user_id = serializer.data.get('user_id') post_id = serializer.data.get('post_id') l = Like(user_id=user_id, post_id=post_id) l.save() # likes field not updating with this post = Post.objects.get(id=post_id) post.likes = F('likes') + 1 post.save() return Response(LikeSerializer(l).data, status=status.HTTP_200_OK) return Response(serializer.errors(), status=status.HTTP_400_BAD_REQUEST) #models.py class Post(models.Model): id = … -
How can I save the username in the database as an email?>
I want a signup page with 3 fields (email, password and repeat password). My goal is that when the user enters the email address, it is also saved in the database as a username. I would be super happy if someone could help me, I've been sitting for x hours trying to solve this problem. Thanks very much! model.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email_confirmed = models.BooleanField(default=False) @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() forms.py class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] # Sign Up Form class SignUpForm(UserCreationForm): # first_name = forms.CharField(max_length=30, required=False, help_text='Optional') # last_name = forms.CharField(max_length=30, required=False, help_text='Optional') email = forms.EmailField(max_length=254, help_text='Enter a valid email address') class Meta: model = User fields = [ 'username', 'password1', 'password2', ] views.py from django.contrib import messages from django.contrib.auth.models import Group from django.contrib.sites.shortcuts import get_current_site from django.utils.encoding import force_bytes from django.utils.http import urlsafe_base64_encode from django.template.loader import render_to_string from .token import AccountActivationTokenGenerator, account_activation_token from django.shortcuts import render, redirect from .forms import * from django.contrib.auth import authenticate, login, logout from django.contrib.auth import get_user_model, login from django.utils.http import urlsafe_base64_decode from django.views.generic import View, UpdateView from django.contrib.auth.decorators import login_required from .decorators import * from django.urls … -
Pass audio from flutter to python?
I have a flutter app that converts a voice to text and I would like to pass the voice from flutter to python to convert it to text without saving the voice. I would like to transfer audio from the flutter to python without saving it -
what is the best way to create a custom admin panel in Django?
I want to create a custom admin panel in Django. what is the best way to do that ? I have found some ways : use some packages to customize that like jet, django-material-admin, django-cms, django-jazzmin create an admin app with python manage.py startapp admin and develop that with my own views and templates is there any better way to do that ? I want to know what professionals do. I would be grateful if you could introduce a clue or a helpful article. -
Can't install Django in visual studio code
So I'm creating a forum according to this tutorial: https://www.youtube.com/watch?v=YXmsi13cMhw&t=2594s I'm stuck at 2:10.I've successfully created a virtual enviroment, can't go past this error.enter image description here Where do I get project name?What on Earth is wrong here?Sorry if I got a little emotional. I tried to do everything exactly like in aforementioned tutorial. -
raise ParseError('JSON parse error - %s' % str(exc))
[views.py terminal errors page ](https://i.stack.imgur.com/YTK7f.png) myapp.py -
Checkbox ALWAYS returns False/ not in request.POST - Django
I have a checkbox on my django app, where user can add or remove a listing from their watchlist. However, this checkbox always returns False, and is never in request.POST, i have tried sooo many solutions from SO and all over the internet for literal days now and cant figure it out Models.py class Watchlists(models.Model): user = models.CharField(max_length=64, default='user') title = models.CharField(max_length=64, blank=True) watchlist = models.BooleanField(default=False, blank=False) def __str__(self): return f"{self.title}, {self.user}, {self.watchlist}" Forms.py class CheckForm(ModelForm): watchlist = forms.BooleanField(required=False) # watchlist = forms.DecimalField(widget=forms.CheckboxInput(attrs={"value":"watchlist"})) class Meta: model = Watchlists fields = ['watchlist'] Checkbox didnt have a value so i thought that was the issue and tried to give it one here on the commented line, it didnt help Views.py watchlist = CheckForm(request.POST or None) if request.method == 'POST': # if request.POST['watchlist']: # if 'watchlist' in request.POST: # if request.POST.get('watchlist', False): if request.POST.get('watchlist', '') == 'on': if watchlist.is_valid(): check = watchlist.cleaned_data['watchlist'] watchlist_data = Watchlists.objects.all().filter(title=title, user=username).first() if not watchlist_data: watchlisted = Watchlists.objects.create(title=title, user=username, watchlist='True') watchlisted.save() if watchlist_data: watchlist_data.delete() I have tried all the different solutions i could find Template <form action="listing" method="POST"> {% csrf_token %} {{ checkbox }} </form> It has a name and id attribute, label is fine too