Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Login Token in Django
hello I have a problem witch I have a User model in my Account app and I have a user inside it with this information { "id": 2, "username": "johndoe", "email": "example@gmail.com", "password": "password123" } my problem is when I POST this JSON data to my LoginView I get this error: (ValueError: Cannot query "johndoe": Must be "User" instance. { "email": "example@gmail.com", "password": "password123" } LoginView, Token code: user = User.objects.get(email=email) token, created = Token.objects.get_or_create(user=user) return Response(data={'token': token.key},status=status.HTTP_200_OK) my User model: class User(AbstractUser): id = models.AutoField(primary_key=True) email = models.EmailField(unique=True) full_name = models.CharField(max_length=255, default="") simple_description = models.CharField(max_length=255, default="tourist") biography = models.TextField(null=True, blank=True, default="") profile_picture = models.ImageField(null=True, blank=True) def __str__(self): return self.username I tried to set my User model as the default of the Django User model but when I wanted to create a superuser for my admin panel, it created a regular user with a long password that I didn't put that -
SyntaxError: Expected property name or '}' in JSON
I have a code with Django and JS. At fist I pass a json file to my JS with Django like this : from rest_framework.response import Response from rest_framework.views import APIView from rest_framework.viewsets import ModelViewSet from rest_framework.renderers import JSONRenderer import json from .models import Adam class AdamViewset(ModelViewSet): queryset = Adam.objects.all() class MainView(APIView) : def get(self, request) : data = json.dumps(list(Adam.objects.values())) return Response({'data' : data}, template_name='doroste.html') but important part is javascript const dataStr = '{{data}}'; const dataJson = JSON.parse(`${dataStr}`) console.log(dataStr) I expected to get a json but instead I got this error : SyntaxError: Expected property name or '}' in JSON I searched for it but I couldn’t find solution CAUSE MY LIST USES "" INSTEAD OF '' SO IT IS OKAY -
Don't buy namecheap shared hosting for DJANGO/PYTHON [closed]
I purchased namecheap sharedhosting plan for my django python app.It does support some functionality but there is a lot of django packages that need root access. Example : MySqlClient/DJOSER ETC. They provided me refund though but it took me a lot of time to finally come to this conclusion. So, I'm writing this thread as a soloution/to not waste your time on that shit. Just buy a VPS hosting and do whatever you want. Their website shows it's support python but it's just basic / not even basic as my experience. So if you're a beginer like me don't bother. It took more than 24 hours or maybe more to finally come to the conclusion. -
is this a valid option to verify the correct user logged in Django?
im learning Django from scratch and in a simple practice project i have a login for create new post. before i know about LoginRequiredMixin and UserPassesTestMixin, I wanted to try someting by myself in the template like this: {% if user.is_authenticated and user == post.author %} "Show forms and things like that and can edit or delete if is the author of the post" {% else %} "Ask the user for log in" {% endif %} but just out of curiosity, is this safe or is it a valid option? xd i try to implement a user permission and authentication in Django. just for curiosity, know whats happens -
Error 404 - HTML page not rendering for other apps than main application
So I've created several apps in my Django project and I have one main app called main_app. The other apps are called profile_app, settings_app, messages_app. The issue: The issues that I have is that whenever I try to run a certain view function from e.g profile_app in main_app using the app namespace and URL name (e.g profilepage_app:"profile-redirect"), I receive a 404 error stating "Page not found". I have done the following: Registret all apps. Linked the urls.py file in my settings URL. Tried to create a test view function inside the main_app and it works perfectly, but the same function does not work in the profile_app. Created another test app in order to see if I still have the same issue (I did). So the problem is that whatever link from all apps (except main_app) that I try to display in the browser generats the "Page not found"-error. My questions: Why does this happen? How can I resolve this issue? Has this something to do with my settings file? The error: My view: from django.conf import settings from django.shortcuts import render, redirect from django.views.generic import View from profile_app.forms import * from profile_app.models import * from messages_app.models import Message user = … -
Receive the value of an input field in the backend: Django
This is a follow-up to my previous question How to get the value of input field entered in navigation . I'm trying to get the value of an input field in the backend- Django. In views.py, I've included the following: Code: def vis(request): if request.method == 'POST': examples = request.POST.get('examples') # Process the value of examples print(examples) # not getting printed on the terminal return render(request, "vis.html") To get the value assigned for the placeholder, I used the below. function getExampleValue() { const fid = document.getElementById("examples").value; console.log(fid) const fpath = `/path/${fid}.json`; fetch(fpath) .then(response => response.json()) .then( data => { var x = data.x }) However, I cannot directly specify the filename in fetch since it fails to load from the file system in Django. So I want to receive the value and pass it to fetch, the value received (filename) will be used for loading a file from the path using fetch. So I specified form in vis.html. <form class="form" id="myForm" action="{% url 'visualization' %}" method="post"> But I am not able to receive the value in the backend. I want to receive the value set for the placeholder in examples: <input id="examples" class="input" name="examples" placeholder=" " onfocusout=getExampleValue() /> Complete HTML … -
Trouble deleting customer record in django using Bootstrap5 Modal/Jquery
I'm trying to delete a customer record when clicking on the modal popup delete button in bootstrap 5 but when I click on 'Yes, I want to delete' , nothing happens and I'm not sure where I'm going wrong. i've checked some of the other queries around this topic but still unable to get it to work. Below is what I have so far. Really appreciate any help on this! Customer record card with button <div class="p-3 text-primary-emphasis bg-primary-subtle border border-primary-subtle rounded-3"> <div class="card"> <div class="card-header"> <strong>{{ customer_record.first_name }} {{ customer_record.last_name }}</strong> </div> <div class="card-body"> <p class="card-text"> <strong>Email: </strong> {{ customer_record.email }} </p> <p class="card-text"> <strong>Phone: </strong> {{ customer_record.phone }} </p> <p class="card-text"> <strong>Address: </strong> {{ customer_record.address }} </p> <p class="card-text"> <strong>City: </strong> {{ customer_record.city }} </p> <p class="card-text"> <strong>Postcode: </strong> {{ customer_record.postcode }} </p> <p class="card-text"> <strong>Created At: </strong> {{ customer_record.created_at }} </p> <p class="card-text"> <strong>Company: </strong> {{ company_info.name }} </p> <p class="card-text"> <strong>ID: </strong> {{ customer_record.id }} </p> </div> </div> </div> <br/><br/> <a href="{% url 'update_customer' customer_record.id %}" class="btn btn-primary btn-sm">Update Customer Information</a> <a href="{% url 'delete_record' customer_record.id %}" class="btn btn-danger btn-sm deleteCustomer" data-bs-toggle="modal" data-bs-target="#deleteCustomer{{customer_record.id}}">Delete Customer</a> Delete customer modal <div class="modal fade" id="deleteCustomer{{ customer_record.id }}" tabindex="-1" aria-labelledby="deleteCustomerLabel" aria-hidden="true"> … -
problems with the current date when modifying a record
I need help with my following form: enter image description here When I'm going to insert the year in the Año field (I'm currently working with the datetimepicker library which works perfectly) the idea is that the current year appears by default in the Año field. I managed to solve this with the following JavaScript code: $('#anno').datetimepicker({ format: 'YYYY', date: moment().format("YYYY"), locale: 'es', }); The real problem is when I try to modify a record it exists, because the date: moment().format("YYYY") property, being active when I am going to modify a record, will have the current year and not the year of the record. When this property is deactivated, then in the case of inserting, no value appears in the field (but the datetimepicker has the current year marked) and in the case of modifying the same thing happens (the datetimepicker has the year of the record marked). I attach the code of my form.py: class OcupacionForm(ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['tipoocupacion'].widget.attrs['autofocus'] = True class Meta: model = OcupacionPortador fields = '__all__' widgets = { 'anno': TextInput( attrs={ 'autocomplete': 'off', 'class': 'form-control datetimepicker-input', 'id': 'anno', 'data-target': '#anno', 'data-toggle': 'datetimepicker' } ), 'tipoocupacion': Select(attrs={'class': 'select2', 'style': 'width: 100%'}), 'mes': … -
How to use multiple forms in a single page in django
Hi i am pretty new to django. I am making a app for taking tiny notes. You can click on the texts (which is a django forms but it doesnt have the outlines) and edit them. I will make the submit form button appear when we change the content with javascript but for now lets leave it that way. With the "+" button you can add more Note instances. Now, the problem is when i want to edit the notes the only way i know is using forms, and when i do that i have to call another form for each Note instance...(i suppose). What i want on my website is, you can simply edit the content or title by clicking the text area, and submiting it(I can give https://trello.com as an example!). views.py def document_page(request, title): document = Document.objects.get(title=title) notes = document.notes.all() form = NoteForm(request.POST or None, request.FILES or None, instance=notes[0]) if form.is_valid(): form.save() return HttpResponseRedirect('/note/document/' + title) return render(request, 'note/document_page.html', {'document': document, 'notes': notes, 'form': form}) models.py class Note(models.Model): title = models.CharField(max_length=16, default='note-title') content = models.TextField(max_length=512, default='content') creation_date = models.DateTimeField(auto_now_add=True) document = models.ForeignKey(Document, on_delete=models.CASCADE, blank=True, null=True, related_name='notes') def __str__(self): return self.title forms.py class NoteForm(ModelForm): class Meta: model = … -
Frontend design tool espacially built for django
I want a frontend design tool built espacially for Django Tried webflow, but it is very inconvenient to download the designed template and then overwrite it so it works with your backend django apps. So I‘m searching for something which works well with Django -
What is the workflow for Stripe's Custom Payment?
I am currently developing a payment module for my django application and I am seeking assistance. Presently, my application uses Checkout Stripe for payment processing, but I find it limiting because it doesn't allow me to fully customize the checkout page according to my preferences. Additionally, I would like to keep the users on my website during the payment process. While exploring Stripe's documentation, I came across the "Custom Payment Flow" feature, which seems to be what I need. My desired flow is as follows: when a user clicks on the "Buy product" button, they should be redirected to a checkout page that I have customized using HTML. This checkout page will include product details, a form to collect personal information, and the Stripe payment form below. I understand that when the page loads, I need to update a variable called items using jQuery or JavaScript to populate it with the specific item or items the user intends to purchase. // The items the customer wants to buy const items = [{ id: "xl-tshirt" }]; However, I am unsure about how to handle the personal information that I will collect from the user. Could someone please provide guidance on how … -
How to handle multiple `GET` query parameters and their absence in Django ORM when filtering objects?
I'm currently building a blog, but this applies to a lot of projects. I have articles stored in Article model and have to retrieve them selectively as per the GET parameters. In this case, I want to return all the articles if the language GET query parameter is not supplied and only the specified language articles when the parameter is supplied. Currently I am doing the following: # articles/views.py @api_view(['GET', ]) def articles_view(request): """ Retrieves information about all published blog articles. """ language = request.GET.get('language') try: if language: articles = Article.objects.filter(published=True, language__iexact=language).order_by('-created_at') else: articles = Article.objects.filter(published=True).order_by('-created_at') # articles = Article.objects.first() except: return Response(status=status.HTTP_404_NOT_FOUND) serializer = ArticleSerializer(articles, many=True, exclude= ('content', 'author',)) data = serializer.data return Response(data) I feel this can be improved and condensed to a single Article.objects.filter(). The use of if for every query param seems inefficient. This is especially required since the articles will later also be retrieved via tags and categories along with language in the GET query parameters. With the expected condensed querying, there would be less if conditional checking and the freedom to include more query params. Can someone please help me with this? -
Django - multiple pages using one form
There's a number of questions regarding one page and handling multiple forms but I seem to have the reverse issue. I have two pages that contain datatables showing filtered data from my model, but both are the same source data and every object (in both tables, on both pages) has the same "edit" button bringing the user to the same form allowing them to edit the object details. My problem is redirecting from the form to the original page. I have tried using HttpResponseRedirect but that doesn't seem to be working, it goes to my homepage everytime. def edit_drawing(request, drawing_no): drawing = get_object_or_404(Drawings, pk=drawing_no) if request.method == "POST": form = DrawingForm(request.POST, instance=drawing) if form.is_valid(): form.save() messages.success(request, f'Drawing {drawing.drawing_no} was successfully updated.') return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/')) else: form = DrawingForm(instance=drawing) return render(request, 'edit_drawing.html', {'form': form, 'drawing': drawing}) I thought I could do something like this where my tag in the original html would tell the redirect where to go if I passed a variable: <a href="{% url 'schedule:edit_drawing' drawing_no=your_drawing_no %}?next={{ request.path }}">Edit Drawing</a> But when I try to use return redirect(next_url) in the view, next_url is undefined and doesn't work. Does anyone have a best practice to handle something like this? I … -
Django migration error: Applying migrations throws an error, and querying 'flight.objects.all()' results in an error as well
I'm facing an issue with my Django project where I encounter errors when trying to apply migrations using python manage.py migrate and when executing flight.objects.all(). Here's the code: from django.db import models # Create your models here. class Flight(models.Model): origin = models.ForeignKey('airport', on_delete=models.CASCADE, related_name="departure") destination = models.ForeignKey('airport', on_delete=models.CASCADE, related_name="arrival") duration = models.IntegerField() def __str__(self): return f"{self.origin} to {self.destination}" class Airport(models.Model): city = models.CharField(max_length=64) code = models.CharField(max_length=3) def __str__(self): return f"{self.city} ({self.code})" The Flight table previously had two Character fields instead of foreign keys and I had stored a row in it but later I decided use Airport table as a foreign key in Flight table. However after I exited the shell and tried to run "python manage.py migrate" I got an error: django.db.utils.IntegrityError: The row in table 'flights_flight' with primary key '1' has an invalid foreign key: flights_flight.origin_id contains a value 'Kathmandu' that does not have a corresponding value in flights_airport.id. I figured it might be because of the previously stored data in the Flight table so i tried to delete it, however i cant even view the contents of the Flight table. Whenever i try running "flight.object.all()" i get another error: django.db.utils.OperationalError: no such column: flights_flight.origin_id Can anyone help … -
Django user.set_password(password) is not hashing the password
I have wrote Custom user Model in Django everything is working fine except password is not being hashed when but when I had created the superuser password was hashed here are my models for custom user and custom user manager model.py() class CustomUser(AbstractUser): email = models.EmailField(_("email address"), null=False,blank=False,unique=True) USERNAME_FIELD='email' REQUIRED_FIELDS = ["username"] object=CustomUserManager() class CustomUserManager(UserManager): def _create_user(self, username, email, password, **extra_fields): """ Create and save a user with the given username, email, and password. """ if not email: raise ValueError("The given email must be set") email = self.normalize_email(email) user = self.model(username=username, email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self,username ,email, password, **extra_fields): extra_fields.setdefault("is_staff", False) extra_fields.setdefault("is_superuser", False) return self._create_user( username,email, password, **extra_fields) def create_superuser(self,username, email, password, **extra_fields): extra_fields.setdefault("is_staff", True) extra_fields.setdefault("is_superuser", True) if extra_fields.get("is_staff") is not True: raise ValueError("Superuser must have is_staff=True.") if extra_fields.get("is_superuser") is not True: raise ValueError("Superuser must have is_superuser=True.") return self._create_user(username, email, password, **extra_fields) should i use this from django.contrib.auth.hashers import make_password and how to use this -
How to handle ForeingKey fields in DRF serializer
I have 2 models with ForeignKey relation class Order(models.Model): ip = models.CharField(max_length=15) ref_code = models.CharField(max_length=15) is_ordered = models.BooleanField(default=False) class OrderItem(models.Model): product = models.ForeignKey(Products, on_delete=models.SET_NULL, null=True) is_ordered = models.BooleanField(default=False) quantity = models.IntegerField(default=1) size = models.ForeignKey(Size ,on_delete=models.CASCADE, related_name='sssize', default = None) order = models.ForeignKey(Order, related_name="item", on_delete=models.CASCADE) This is my serializer class CreateOrderItemSerializer(serializers.ModelSerializer): class Meta: model = OrderItem exclude = ('is_ordered',) def create(self, validated_data): order_item, created = OrderItem.objects.update_or_create( product = validated_data.get('product',None), quantity = validated_data.get('quantity', None), size = validated_data.get('size',None), ) return order_item I need to somehow get or create Order object base on ip (which i get from request) and is_ordered fields and pass it to serializer or do it in view I have tried to add order field in view.py after i get my serialized data but i get an error saying that order field is required View.py def post(self, request, pk): serializer = CreateOrderItemSerializer( data=request.data, ) print(serializer.initial_data) if serializer.is_valid(): product = serializer.save() ip = get_client_ip(request) order = Order.objects.get_or_create(ip = ip, is_ordered = False) product.order.add(order.id) Or need i get ip strait from POST method JSON? -
Unknown field(s) (client_value, client_name) specified for Client. Check fields/fieldsets/exclude attributes of class ClientDataAdmin
I have a model that I want to add to my admin pages. The model class is. class Client(models.Model): FBUSER = "FBU" GOOGLEUSER = "GU" FBACCESSCODE = "FBAC" GOOGLESECRET = "GS" MISC = "MISC" CLIENT_KEY_CHOICES = [ (FBUSER, "Facebook User ID"), (FBACCESSCODE, "Facebook Access Code"), (GOOGLEUSER, "Google User"), (GOOGLESECRET, "Google Secret"), (MISC, "Misc"), ] client_key = models.CharField( max_length=4, choices=CLIENT_KEY_CHOICES, default=FBUSER, ) id = models.BigAutoField(primary_key = True), client_name = models.CharField(max_length=100, blank=True, null = True), client_value = models.CharField(max_length=100, blank=True, null = True), and my admin.py is class ClientDataAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['client_key', 'client_name', 'client_value' ]}), ] list_display = ('client_name', 'client_key', 'client_value') search_fields = ['client_name'] I have looked at several similar error explanations and fixes but none fit, this case. I have other models and admin scripts that work fine, but I cannot find anything wrong here. The admin page shows the add link but I get the following error when I hit it... Unknown field(s) (client_value, client_name) specified for Client. Check fields/fieldsets/exclude attributes of class ClientDataAdmin. Request Method: GET Request URL: http://localhost:8000/admin/kdconnector/client/add/ Django Version: 4.1.7 Exception Type: FieldError Exception Value: Unknown field(s) (client_value, client_name) specified for Client. Check fields/fieldsets/exclude attributes of class ClientDataAdmin. I suspect it comes from the choices … -
Why is my breakpoint in Django not activated when I use a custom authentication backend
I have a custom user authentication back end in Django so I can make a user log in with email and or username. I placed a break point in the in the authenticate method but it is not firing so I can check why the authenticate method is returning None all the time. I changed the settings to include: AUTHENTICATION_BACKENDS = ["users.backends.EmailOrUsernameBackend"] Here is the view to handle the login: from django.contrib.auth import authenticate @api_view(["POST"]) def LoginUser(request): email = request.data.get("email") username = request.data.get("username") password = request.data.get("password") exists = User.objects.filter(email=email).exists() if exists: user = User.objects.get(email=email) if user.is_active and user.email_verified_at is None: authenticated = authenticate(email=email, username=username, password=password) if authenticated is not None: serializer = LoginSerializer(authenticated) token, created = Token.objects.get_or_create(user=user) return Response( {"id": serializer.data["id"], "Authorization": token.key, "role": user.role}, status=HTTP_200_OK, ) else: return Response("Wrong email and/or password", status=HTTP_401_UNAUTHORIZED) else: return Response("Account is not active! Did you change your email and haven't confirmed it?") else: return Response("Email is not registered, please register") Here is the custom backend to authenticate the username, or email and password: class EmailOrUsernameBackend(ModelBackend): def authenticate(self, **kwargs): breakpoint() email = kwargs.get('email') username = kwargs.get('username') password = kwargs.get('password') if email: try: user = User.objects.get(email=email) except User.DoesNotExist: return None elif username: try: user = … -
Best way to old "version" of specific parameters on django model
I want to do a "version control" kind of thing. I have a django model called "Person" I also have a method of updating all persons "gender" and "language" according to "detection" version. this method improves from version to version. I dont want to "detect" gender of person in latest version to not over use resources, each detection cost ... my method need to run over all persons with gender version 1 or language version 1 and update the person lang and gen to version 2 (run the method). so the simple is: class Person(models.Model): phone = models.CharField(max_length=50, blank=True, null=True) phone_version = int ... language = models.ManyToManyField( "instagram_data.Language", verbose_name=_("language_code_name"), blank=True) language_version = int ... but I have also 20 more filters (like gen and lang) so I prefer to have one attribute named version, so I could filter also in a simple way. if I do ManyToManyField to class Version it will be slow to do filters, right ? class Person(models.Model): phone = models.CharField(max_length=50, blank=True, null=True) language = models.ManyToManyField( "instagram_data.Language", verbose_name=_("language_code_name"), blank=True) version_control = models.ManyToManyField(DetectionVersion ...) class DetectionVersion(models.Model): phone_version = int ... language_version = int .. is the second fast and a good solution ? -
Wrong distance between two points in Geodjango
I have user class: class User(AbstractBaseUser): location = PointField(srid=4326) and I calculate distance between two points in serializer this way: obj.location.distance(request.user.location) * 100 For example I have two points: POINT(-95.3385 29.7245) POINT(-85.3385 29.7245) One point is for authorized user the other is for the other user. Serializer returns 1000 kilometers. I don't know what is latitude and longitude and it doesn't matter because in online calculators in one case it is a little bit more than 1000 km and in the other - a little bit less than 1000 km. And it is never 1000 km. Any ideas why this is happening? -
Calling javascript functions in static, Django
Im struggling to understand why I cant call a javascript function when my Bootstrap button is clicked in Django. I have created the static folder in my directory "main/static/main/js/script.js" I am able to load the static css file for boostrap without any issues, but for whatever reason the javascript function "testing()" cant be called. Web browser console logs as Uncaught ReferenceError: testing is not defined onclick. Am i suppose to use AJAX instead, or is there simply something wrong with my settings or url path. my settings.py file INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main.apps.MainConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.2/howto/static-files/ STATICFILES_DIRS = [BASE_DIR /'main/static'] STATIC_URL = '/static/' my scripts.js function testing() { alert("Button clicked!"); } my index.html, that is using bootstrap: {%load static%} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <meta name="description" content="" /> <meta name="author" content="" /> <title>MoviePicks</title> <!-- Core theme CSS (includes Bootstrap)--> <link rel="icon" type="image/x-icon" href="{%static 'main/assets/favicon.ico'%}" /> <link href="{%static 'main/css/styles.css'%}" rel="stylesheet" /> </head> <body id="page-top"> <!-- Header--> <header class="bg-dark bg-gradient text-white"> <div class="container px-4 d-flex flex-column align-items-center text-center"> <!--code to play … -
How to save multiple product ID from cart to Order table under one Order ID?
I tried to do this with my own coding based on the internet and chatgpt. However it only save one item from the cart. Can somebody help me?? (p/s : I used ManyToMany field for ProdID under Order table to save multiple products from Cart page) models.py (i put the null = True bcs i just want to focus on the orderID functionality) class Cart(models.Model): product = models.ForeignKey(Product, on_delete = models.CASCADE) item_qty = models.IntegerField(default=1) class Customer(models.Model): CustID = models.CharField(max_length=100, primary_key = True) CustName = models.TextField() CustAdd = models.TextField() CustPhone = models.TextField() class Order(models.Model): OrderID = models.CharField(max_length=100, primary_key = True) ProdID = models.ManyToManyField(Product) CustID = models.ForeignKey(Customer, on_delete = models.CASCADE, null=True) totalprice = models.FloatField(null=True) ordered_date = models.DateTimeField(auto_now_add=True) payment = models.TextField(null=True) paystatus = models.CharField(max_length=50,default='Pending') coding related to my problem in cartpage.html <form action="{% url 'placeorder' %}" method="get"> {% csrf_token %} <tbody> <tr> {% for cart in cart %} <td><button pid = "{{ cart.product.ProdID }}" class="remove-cart btn"><ion-icon name="close-outline"></ion-icon></button></td> <input type="hidden" name="prodid" value="{{cart.product.ProdID}}" id="prodid" class="prodid"> <td class="w-5"><image src="{{ cart.product.ProdPic.url }}" style="height:80px; width:65px;" class="rounded-circle"></td> <td>{{cart.product.ProdName}}</td> <td class="cart-product-quantity"> <input type="button" pid = "{{ cart.product.ProdID }}" class="minus-cart btn btn-light btn-circle btn-sm" value="-"></input> <span id="quantity" min="1">{{ cart.item_qty }}</span> <input type="button" pid = "{{ cart.product.ProdID }}" class="plus-cart btn btn-light btn-circle … -
How to make calorie goal dynamic in my django app that user can input according to them?
https://github.com/geetanshpardhi1/FitCalorie The above link redirects you to my repo where you can find code. In myapp/index.html (line no.127) I have added functionality for the calorie goal which is hardcoded for value 2000 and I want to make it dynamic for each user, how can I do it? My doubt is in which model do I have to add a goal field and how can I integrate HTML input with it? -
Budgeting feature for django ecommerce web app
Can anyone help me with login to build a budget feature within a ecommerce platform. i have this project I am designing for my final year project but i want to design a page where user can find multiple product within a specific price. Let say the user want to a shirt, bag and shoe but have 7000, I want the app to return all the three product that can be bought with 7000. -
Django - Display specific attribute of object in <Select> in template
I have the following Python models: class Usuario(models.Model): login = models.CharField(max_length=200) senha = models.CharField(max_length=200) meta = models.ManyToManyField('meta', through='Usuario_meta') def __str__(self): return f'id: {self.id} - login: {self.login} - senha: {self.senha}' class Meta(models.Model): tipo = models.CharField(max_length=200) def __str__(self): return f'id: {self.id} - senha: {self.tipo}' class Usuario_meta(models.Model): usuario = models.ForeignKey(Usuario,on_delete=models.CASCADE) meta = models.ForeignKey(Meta,on_delete=models.CASCADE) data = models.DateField() valor = models.IntegerField() def __str__(self): return f'Meta do usuário: {self.usuario} - meta:{self.meta} - data:{self.data} - valor: {self.valor}' The following view: class UsuarioMetaCreate(CreateView): model = Usuario_meta template_name = 'lancamento_meta_cadastro.html' fields = '__all__' The following html: <form action="" method="post"> {% csrf_token %} {{form}} <input type="submit" value="Submit" /> </form> Which displays the following: I would like to show, in the "usuario" select, only the attribute "login". Apparently, it calls the 'str()' and displays all the fields. Is there a way to show only a specific attribute while using CreateView and without modifying the 'str()' method? I have already tried using <form action="" method="post"> {% csrf_token %} {{form.usuario.login}} <input type="submit" value="Submit" /> </form> But it doesn't display anything