Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django How to display data from a view context inside a formset
Let's say I have a django template that contains the following form: {% if evidence_formset %} <form id="evidence-formset" action="{% url 'variants:interpret-criteria' %}" method="post"> <div class="form-group row mt-3 justify-content-between"> <!-- I would like to display my content here --> </div> <div class="form-group row mt-3 justify-content-between"> <div class="col-auto"> <ul class="nav nav-pills" id="evidence-formset-tab" role="tablist"> {% for evidence_form in evidence_formset %} {% with index=forloop.counter|stringformat:'s' %} {% with id='evidence-form-'|add:index|add:'-tab' href='#evidence-form-'|add:index aria_controls='evidence-form-'|add:index %} <li class="nav-item"> {% if not current_tab and forloop.first or current_tab == index %} <a class="nav-link active" id="{{ id }}" data-toggle="pill" href="{{ href }}" role="tab" aria-controls="{{ aria_controls }}" aria-selected="true">{{ forloop.counter }}</a> {% else %} <a class="nav-link" id="{{ id }}" data-toggle="pill" href="{{ href }}" role="tab" aria-controls="{{ aria_controls }}" aria-selected="false">{{ forloop.counter }}</a> {% endif %} </li> {% endwith %} {% endwith %} {% endfor %} </ul> </div> </div> {% csrf_token %} {{ evidence_formset.management_form }} <input type="hidden" name="current_tab" value="{{ current_tab }}" /> <div class="tab-content" id="evidence-formset-tabContent"> {% for evidence_form in evidence_formset %} {% with index=forloop.counter|stringformat:'s' %} {% with id='evidence-form-'|add:index aria_labelledby='evidence-form-'|add:index|add:'-tab' %} {% if not current_tab and forloop.first or current_tab == index %} <div class="tab-pane fade show active" id="{{ id }}" role="tabpanel" aria-labelledby="{{ aria_labelledby }}"> {% include "variants/interpretation_form.html" %} </div> {% else %} <div class="tab-pane fade" id="{{ id }}" … -
How to detect if a Tiktok account has liked a video/post in Python?
I've been working on a project has a feature that needs to check if a user has liked a post(video, which I already have detail about this post). I'm using this https://github.com/davidteather/TikTok-Api but seems like doesn't work. Thank you all in advance, -
Get current logged in user in JSON Format from views.py
I'm trying to build a follow and unfollow button, I want to show the button only For any other user who is signed in, a user should not be able to follow themselves. How can I return from my views.py the currently logged-in user as a JSON format to my JS file? I'm building the button in the JavaScript file and not in the template, I tried to return as JSON format but didn't succeed views.py def display_profile(request, profile): try: profile_to_display = User.objects.get(username=profile) profile_to_display_id = User.objects.get(pk=profile_to_display.id) except User.DoesNotExist: return JsonResponse({"error": "Profile not found."}, status=404) # Return profile contents if request.method == "GET": return JsonResponse(profile_to_display.profile.serialize(), safe=False) else: return JsonResponse({ "error": "GET or PUT request required." }, status=400) models.py from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): pass class NewPost(models.Model): poster = models.ForeignKey("User", on_delete=models.PROTECT, related_name="posts_posted") description = models.TextField() date_added = models.DateTimeField(auto_now_add=True) likes = models.IntegerField(default=0) def serialize(self): return { "id": self.id, "poster": self.poster.username, "description": self.description, "date_added": self.date_added.strftime("%b %d %Y, %I:%M %p"), "likes": self.likes } class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) following = models.ManyToManyField(User, blank=True, related_name="following") followers = models.ManyToManyField(User, blank=True, related_name="followers") def serialize(self): return { "profileID": self.user.id, "following": int(self.following.all().count()), "followers": int(self.followers.all().count()), } index.js function load_user_info(user_clicked_on){ document.querySelector('#page-view').style.display = 'none'; document.querySelector('#posts-view').style.display = 'none'; document.querySelector('#show-posts').style.display … -
use drf with django_auth_ldap
I use django_auth_ldap with the Django Restframework. But, sometimes I get a HTTP 401 error. sometimes I can get a jwt token. I do not know which problem cause that. Is there anybody can help me. enter image description here enter image description here enter image description here enter image description here -
How to get django-all auth to pass data to custom user model
I'm making a site in Django using django-allauth for authentication. I've created a custom user class in account.models to add a custom field, UserExtraFiledSignup , i have added image field so user can upload profile photo for his account during signup but i got issue The issue I have is that the when user create account and upload photo Actually it's don't uploaded i don't know what is the error my app | models.py : class UserExtraFiledSignup(models.Model): Profile_photo = models.ImageField(default='', upload_to='images/') def save(self, *args, **kwargs): super(UserExtraFiledSignup, self).save(*args, **kwargs) my app | forms.py : from allauth.account.forms import SignupForm from .models import User from blog_app.models import UserExtraFiledSignup from django.contrib.auth import get_user_model class CustomSignupForm(SignupForm): first_name = forms.CharField(required=True,label='First Name',widget=forms.TextInput(attrs={'class': 'form-control','placeholder':' Enter First Name '}) ) last_name = forms.CharField(required=True,label='Last Name',widget=forms.TextInput(attrs={'class': 'form-control','placeholder':' Enter Second Name '}) ) Profile_photo = forms.ImageField(label='Profile photo') class Meta: model = get_user_model() def signup(self, request, user): user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.Profile_photo = self.cleaned_data['Profile_photo'] user.save() return user my app | adapters.py : from django.conf import settings from allauth.account.adapter import DefaultAccountAdapter class AccountAdapter(DefaultAccountAdapter): def save_user(self, request, user, form, commit=False): data = form.cleaned_data user.first_name = data['first_name'] user.last_name = data['last_name'] user.Profile_photo = data['Profile_photo'] if 'password1' in data: user.set_password(data['password1']) else: user.set_unusable_password() self.populate_username(request, user) user.save() return … -
How to remove the margins added by bootstrap
Im working on a page utilizing django that has a navbar plus a 3x3 grid that fills the rest of the page. My issue is when I add the bootstrap style-sheet (above my custom style-sheet) i get some white space on the right and the left of both the grid and the navbar. I assume this can be overridden by a custom style-sheet but as im learning I cant figure it out. Following advice from other posts I have messed around a lot with trying to override box-sizing (which changes nothing) and margins (which sticks everything to one side or the other but wont stretch to both sides). I assume something is constraining the size of .container but I dont know. I have used inspect element to try to isolate the problem but no luck. Here the css that works when I exclude the bootstrap stylesheet. /* Master styles*/ body { margin: 0px; font-family: 'Fira Sans', sans-serif; } .container { display: grid; grid-template-columns: 1fr; } /* Nav styles*/ #cart-icon{ width:50px; display: inline-block; margin-left: 15px; } #cart-total{ display: block; position: absolute; top: 10px; right: 20px; text-align: center; color:#fff; background-color: red; width: 18px; height: 18px; border-radius: 50%; font-size: 14px; } .nav-wrapper { … -
How to count a a filtered result in Django?
I'm so far able to get a QuerySet of what I want, but I can't however include the .count() statement in there. I do know I could use len(students) here but I'd like to stick to the Django ORM. student_count = Student.objects.filter(last_online__range=[last week, this week]) How to do it? -
How do I filter a model field case insensitive and unaccent?
I need to make a query that return results ignoring case and accents. Example: I search for 'atacadao' and as a possible answer would be Atacadão, atacadão, Atacadao and atacadao. -
return Database.Cursor.execute(self, query, params) django.db.utils.ProgrammingError: Cannot operate on a closed cursor
from django.db import connection from EmployeeData.models import markAttendance def markAttendance(Name,inTime,InDate): with connection.cursor() as cursor: sql = '''INSERT INTO markAttendance(Name,inTime,InDate) VALUES(%s, %s, %s)''' val=(Name,inTime,InDate) cursor.execute(sql,val) connection.commit() -
Error Django Multiples Values for keyword argument
Can someone please help me? I'm trying to do a simple django api and it's not working really well, I keep having this error: django.db.models.manager.BaseManager._get_queryset_methods..create_method..manager_method() got multiple values for keyword argument 'group' my models are: class Group(models.Model): name = models.CharField(max_length=255) scientific_name = models.TextField() class Characteristic(models.Model): characteristic = models.TextField() class Animal(models.Model): name = models.CharField(max_length=255) age = models.FloatField() weight = models.FloatField() sex = models.CharField(max_length=255) group = models.ForeignKey(Group, on_delete=models.CASCADE) characteristics = models.ManyToManyField(Characteristic) and my serializers: class GroupSerializer(serializers.Serializer): id = serializers.IntegerField(required=False, read_only=True) name = serializers.CharField() scientific_name = serializers.CharField() class CharacteristicsSerializers(serializers.Serializer): id = serializers.IntegerField(required=False, read_only=True) characteristic = serializers.CharField() class Meta: model = Characteristic fields = ('characteristic') class AnimalSerializer(serializers.Serializer): id = serializers.IntegerField(required=False, read_only=True) name = serializers.CharField() age = serializers.FloatField() weight = serializers.FloatField() sex = serializers.CharField() group = GroupSerializer() characteristic_set = CharacteristicsSerializers(many=True) and my view, I know it's ugly but I just can figure out what I'm doing wrong here class AnimalView(APIView): def post(self, request): serializer = AnimalSerializer(data=request.data) if not serializer.is_valid(): return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) group_pop = serializer.data.pop('group') queryset = Group.objects.all() serializer_group = GroupSerializer(queryset, many=True) for group in serializer_group.data: if group_pop['name'] == group['name']: animal = Animal.objects.create(**serializer.data, group=group) else: group = Group.objects.create(**group_pop) animal = Animal.objects.create(**serializer.data, group=group_pop) characteristic_set = serializer.data.pop('characteristic_set') for characteristic in characteristic_set: Characteristic.objects.create(**characteristic, animal=animal) serializer = AnimalSerializer(animal) return … -
error auctions.models.Listing.DoesNotExist: Listing matching query does not exist. I am just starting learning django, what is wrong in my code?
Here is my views.py file: from django.contrib.auth import authenticate, login, logout from django.db import IntegrityError from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.urls import reverse from .models import * def index(request): return render(request, "auctions/index.html" , { "listings" : Listing.objects.all() }) def login_view(request): if request.method == "POST": # Attempt to sign user in username = request.POST["username"] password = request.POST["password"] user = authenticate(request, username=username, password=password) # Check if authentication successful if user is not None: login(request, user) return HttpResponseRedirect(reverse("index")) else: return render(request, "auctions/login.html", { "message": "Invalid username and/or password." }) else: return render(request, "auctions/login.html") def logout_view(request): logout(request) return HttpResponseRedirect(reverse("index")) def register(request): if request.method == "POST": username = request.POST["username"] email = request.POST["email"] # Ensure password matches confirmation password = request.POST["password"] confirmation = request.POST["confirmation"] if password != confirmation: return render(request, "auctions/register.html", { "message": "Passwords must match." }) # Attempt to create new user try: user = User.objects.create_user(username, email, password) user.save() except IntegrityError: return render(request, "auctions/register.html", { "message": "Username already taken." }) login(request, user) return HttpResponseRedirect(reverse("index")) else: return index(request) @login_required(login_url='login') def create(request): if request.method == "POST": title = request.POST["title"] description = request.POST["description"] price = request.POST["price"] picture = request.POST["picture"] user = User.objects.get(username=request.user) try: listing = Listing(item= title,description= description,price= price,image= … -
Count number of instances which have a parameter in a list in common
I'm building an app to keep track of a school and I'm trying to figure out how many students each course has. The way my app is structured is like this: class Course(models.Model): LEVELS = ( ('A0', 'A0'), ('A1', 'A1'), ('B0', 'B0'), ('B1', 'B1'), ('C1', 'C1'), ('C2', 'C2'), ) name = models.CharField(max_length=32) level = models.CharField(max_length=2, choices=LEVELS) class Student(models.Model): name = models.CharField(max_length=32) school = models.ForeignKey(School, on_delete=models.CASCADE) course = models.ManyToManyField(Course) So, the students in the API look something like this: [ { "id": 1, "name": "Diego", "school": 2, "course": [8] }, { "id": 2, "name": "Garry", "school": 2, "course": [1] }, { "id": 3, "name": "Dr Henrick", "school": 2, "course": [8] }, ] Now the question comes in my serializer, where I'd like to get a count for each course, ideally in a dict structure that would look something like this: { 8: 2, 1: 1} What I've done consists of getting all of the students from the db and looping over their courses list, but I wonder if I could do something like that with Django's query system. -
how I can change Django Allauth email verification through OTP instead of activation link
I am working on a project I need that the Django All-Auth email verification through OTP Instead of activation link. Currently and Default Behaviour of Django all-auth to confirm email using activation link.i want to replace the Django email verification method and use OTP verification -
How to run a function with an infinite loop after rendering a page in Django
I'm writting a Django web application which will work as a tweet bot. At some point in the app the user will have to fill up a form which will decide what kind of tweets will be posted. When the user submits the form I want to render a web page to inform the user that the app is running in the background and after that I want to run the infinite loop that actually do the tweeting. My question is, how can I render a web page (from the views file) and then run the actual function (which lives in another file)? Passing the info of the form to the posting view: random_object = Random.objects.create(quotes=quotesSwitch, jokes=jokesSwitch, chuckNorris=chukNorrisSwitch, movieReview=movieReviewsSwitch, periodicityNumber=periodicityNumber, periodicity=periodicity) atributes = { 'random_object': random_object } return render(request, 'posting.html', {'random_object': atributes}) and the posting view: def posting(request): obj = Random(request.POST) random_func(obj) #This is the function with the infinite loop return render(request, 'posting.html') -
django manytomany user auto fill the user field
so what im trying to do is i have 2 tables in my models.py im trying to auto fill the user filed in the second table whatever user i select in my first table i tried to override the save_model in admins.py but didnt work here is my models.py file class Company(models.Model): company_name = models.CharField(max_length = 50) slug = models.SlugField(unique = True) user = models.ManyToManyField(User, related_name='company_user') objects = models.Manager() published = PublishedManager() def __str__(self): return self.company_name class Group(models.Model): company_name = models.ForeignKey(Company, related_name = 'co_name', on_delete=models.CASCADE) count = models.CharField(max_length = 50) real_count = models.CharField(max_length = 50) entry_date = models.DateTimeField() exit_date = models.DateTimeField() code = models.CharField(max_length = 10) code_date = models.DateTimeField() manifest = models.ImageField(upload_to='manifest/%m/%y', blank=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) user = models.ManyToManyField(User, related_name='group_user', blank=True) objects = models.Manager() published = PublishedManager() class Meta: ordering = ('-code_date',) def __str__(self): return str(self.id) my admins.py file @admin.register(Group) class GroupAdmin(admin.ModelAdmin): list_display = ['id', 'company_name', 'code', 'code_date', 'count', 'real_count', 'entry_date', 'exit_date', 'manifest', 'created' ] autocomplete_fields = ('user',) @admin.register(Company) class CompanyAdmin(admin.ModelAdmin): list_display = ['company_name'] autocomplete_fields = ('user',) prepopulated_fields = {'slug': ('company_name',)} im trying to get the user in the Company class to be auto inserted in my Group class any advice -
Django and multi tenancy, data sharing
I'm working on a small project (CRM) using Django and I'm using Django-tenant-schemas, so each user have his own Schema, I would like to know how can I share some data between users ( ex: share user contact list between two users) I was thinking to create a table in the public schema but I don't think is the right solution since I'm isolating data -
How to use the data about objects modifications in Django?
Django stores a history of the modification for every object, it is something we can access to through the Django admin: It contains data about when the object was created/modified, the user who performed the action and the timestamp of the action: By giving a look at the database, I can guess this data is stored in a default table called django_admin_log: I am wondering if we can make use of this data in any way through the instance of a model ? I got used to adding manually my timestamps on every models through an Abstract Base Class, but I am wondering if it is useful in any way ? Or this table records only the modification taking place in the Django admin panel, which would makes the custom timestamp still needed for when the models instance were to be updated outside it. -
Original exception text was: 'QuerySet' object has no attribute 'customer_name'
Please check me this error with serializers. I have two model Customer and Factor: models.py: class Customer(models.Model): customer_name = models.CharField(max_length=120 ,verbose_name='بنام') final_price = models.DecimalField(max_digits=20, decimal_places=0, default=0, verbose_name='مبلغ کل فاکتور') def __str__(self): return f'{self.customer_name}' class Factor(models.Model): title = models.CharField(max_length=120 ,verbose_name='صورتحساب') name = models.ForeignKey(Customer,on_delete=models.CASCADE,verbose_name='بنام' ,related_name='factor_set') description = models.CharField(max_length=200 ,verbose_name='شرح کالا') price = models.DecimalField(max_digits=20, decimal_places=0, default=0.0,verbose_name='قیمت واحد') count =models.DecimalField(max_digits=20,decimal_places=0, default=1,verbose_name='تعداد') date = models.DateTimeField(default=datetime.datetime.now,null=True,verbose_name='تاریخ') def __str__(self): return f'{self.name}' serializer.py: class FactorModelSerializer(serializers.ModelSerializer): name = serializers.StringRelatedField(many=True) class Meta: model = Factor fields = '__all__' class CustomerModelSerializer(serializers.ModelSerializer): factor_set=FactorModelSerializer(many=True) class Meta: model = Customer fields = '__all__' views.py: class GetAllData__(APIView): def get(self,request): query = Customer.objects.all() serializer=CustomerModelSerializer(query) return Response(serializer.data ,status=status.HTTP_200_OK) urls.py : from factor.views import GetAllData,GetAllData__ urlpatterns = [ path('get-all-data--', GetAllData__.as_view()), ] error : AttributeError at /get-all-data-- Got AttributeError when attempting to get a value for field customer_name on serializer CustomerModelSerializer. The serializer field might be named incorrectly and not match any attribute or key on the QuerySet instance. Original exception text was: 'QuerySet' object has no attribute 'customer_name'. -
What is a good way to store guest user information that may be saved to a permanent user after registration in django?
I have a RESTful django webapp that allows users to take quizzes in a progressive system where the quizzes become increasingly difficult. Their progress is saved when they answer a question. I'm using django-rest-framework. class User(AbstractUser): pass class IntervalsProfile(models.Model): # Belongs to User model in 1-to-1 relationship # If User is deleted, then the corresponding IntervalsProfile will be deleted as well user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile', on_delete=models.CASCADE) level = models.IntegerField(default=0) current_level = models.IntegerField(default=0) # Level the user is currently viewing/on I would like users to be able to play as a guest, and if they so choose, register in order to save their progress. I cannot figure out how to save this guest information or how to save it once they register. I've searched thoroughly and all the solutions I see are either several years old or seem too cumbersome (such as adding a check for authentication in every view and having 2 cases for each view). Any advice or guidance would be much appreciated. -
Open and validate files to Django (Wagtail) admin before upload
thanks in advance, I'm currently trying to create some data types which are pretty much just Wagtail's default document type (implemented on the admin similar to Django's FileField) with a custom clean (validation) method. However, the problem I'm getting is when I'm uploading the file, I get an IOError when my program tries to open the file to process. Validating the extension is easy enough, but the problem lies when I actually have to open the file. I'm guessing when I try to open it the document isn't uploaded on the server yet when it tries to validate all the information, so opening it would be impossible. I wasn't able to find any information identifying whether this is even possible, and this seemed like a core Django constraint, not just Wagtail. P.S. I'm intentionally not showing code because it doesn't really clear to much up, but if you'd like to see it I'd be happy to provide it or anything else. -
create an api rest from django project and use it in flutter app
Hello am new in django and flutter .I'm working in a new project with this technologies and using firebase as a database: actually I have an ocr code in django that recognize the names of medecines : def ocr_title(im): image = cv2.imread(im, 0) img = cv2.resize(image, (500, 500)) img = cv2.GaussianBlur(img, (5, 5), 0) img = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 21, 4) himg, wimg = img.shape maxw = 0 text = '' title = pytesseract.image_to_data(img, config='--psm 6 --oem 3') for x, b in enumerate(title.splitlines()): if x != 0: b = b.split() if len(b) == 12 and len(b[11]) >= 4: if (int(b[8]) > maxw): maxh = int(b[9]) maxx = int(b[6]) maxy = int(b[7]) maxw = int(b[8]) text = b[11] #remove symboles from text text = re.sub(r'[^\w]', '', text) text = str(text) return (text) so my question is how can I create an API rest from this Django project so I can use these functions in a flutter -
How to override verification email function in dj-rest-auth and all-auth?
I want to override the email verification method and put it in a Celery queue as it takes up quite some time (2-3 seconds) for the email to send. My question is, where can I find the function with sends the email? -
Use value of text field in same HTML file
I want to use the value of input text of name='t0' in the same HTML file. Here is the code - <!DOCTYPE html> <head> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css"> <title>Insert Account</title> </head> <body> <form action="{% url 'account_select' %}" method="GET"> <div class="text-center"> Id: <input type="text" name="t0"><br> <div class="one"> <button type="submit" class="btn btn-outline-primary" name="b1" value="Select">Select</button> </div> </div> </form> </body> </html> I want to use the value inserted in <input type="text" name="t0"> in place of "HERE" <form action="{% url 'account_select' "HERE" %}" method="GET"> Value has to be used in same HTML file because it will be directed to the the link. -
I want a storage for my django project but all the platforms that provide it require credit card details [closed]
Want storaje for django media but all the platforms that provide it require credit card details like AWS,google cloud storage,etc. is there any alternative to it?? -
django - DecimalField max_digits, decimal_places explained
So I'm just starting out with Django and using it to store forex prices which are represented as 1.21242, 1.20641, etc... model.py from django.db import models # Create your models here. class ForexPrice(models.Model): openPrice = models.DecimalField(max_digits=6, decimal_places=6) highPrice = models.DecimalField(max_digits=6, decimal_places=6) lowPrice = models.DecimalField(max_digits=6, decimal_places=6) closePrice = models.DecimalField(max_digits=6, decimal_places=6) My Question Is: How do the max_decimal and decimal_places attributes work? I'm using 6 for both fields assuming max_digits=6 will allow values to be stored up to 6 digits ie: 123456.000000 while decimal_palces=6 will support values up to 000000.123456. Is this assumption correct or am I missing something? Getting the following error when I save the record to the DB: A field with precision 6, scale 6 must round to an absolute value less than 1.