Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to update web page after successfull ajax request without reload the page
I am sending the AJAX request to server and after success I would like to update the page without refreshing it fully. It is my snippet of code, but here I can just reloading the page and not sure how to do that without it, my line does not work either, could you help, please? PS. I am using Django for back-end function saveTags(slug, form, e) { e.preventDefault(); let tags = form.getElementsByClassName("new-tags")[0].value; if (tags != '') { var formData = { csrfmiddlewaretoken: '{{ csrf_token }}', slug: slug, tags: tags, }; var POST_URL = "{% url 'save_tags' %}"; $.ajax({ url: POST_URL, type: "POST", data: formData, success: function (data) { var x = document.getElementById("snackbar"); x.classList.add("show"); setTimeout(function(){ x.className = x.className.replace("show", ""); }, 3000); $("document").html(data); //window.location.reload(true); } }); // end ajax } return false; }; -
In Django, print a text in a textarea after clicking on a button
I would like to select an element of the combobox and print it in a textarea, after clicking on the button. I have no errors, but the problem that when I click the button nothing happens I have a combobox with this function: views.py def trips(request): country = request.GET.get('country') trips = Trip.objects.filter(country=country) return render(request, 'trips.html', {"trips": trips}) I would like to print trips in a textarea. So I created the textarea and the button (I DON'T want them in a form) home.html .... .... .... {% include "trips.html" %} <!-- Textarea--> {% include "result.html" %} <!-- NOTE: textarea name="result" id="id_result"></textarea>--> <!-- Button--> <button type="button" class="mybtn" href="{% url 'test'%}">Button 1</button> <button type="submit" name='mybtn' value={{test}}>Button 2</button> In views.py I also added the function to print in the textarea (but surely I must have done something wrong) def test(request, trips): new = ("my trips is ", trips) return render(request,"result.html", {"new": new}) In urls.py urlpatterns = [ path('trips', views.trips, name='trips'), path('mytest', views.test, name='test'), ] -
Django Python : This variable is defined, yet the shell says it is undefined not allowing me to process the page
Hi I'm relatively new to Django and am struggling to understand how models work with views. This is from a form used to create a flashcard. I'm trying to assign the characters inputted in the fields to the classes parameters. Then I would like to display the parameters in a card which I do in the template. Whilst I would like this issue fixed I would also be open to see if there are any better and more efficient ways to approach this issue. This is the section of my views.py that raise the issue: def flashcard(response): if response.method == "POST": form = Flashcard_verif(response.POST) if form.is_valid(): print("is workinggg boii") head = form.cleaned_data["header"] ques = form.cleaned_data["question"] ans = form.cleaned_data["answer"] flashcard_data = Flashcard(header=head, question=ques, answer=ans) global rawHeader, rawQuestion, rawAnswer rawHeader, rawQuestion, rawAnswer = Flashcard(header=head, question=ques, answer=ans).flash_format() print(rawHeader, rawQuestion, rawAnswer) flashcard_data.save() else: form = Flashcard_verif() return render(response, "main/Flashcard.html", { "form":form, "header":rawHeader, "question":rawQuestion, "ans":rawAnswer, }) This is the flashcard model: class Flashcard(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="flashcard", null=True) header = models.CharField(max_length=40) question = models.CharField(max_length=200) answer = models.CharField(max_length=200) def __str__(self): return self.header def flash_format(self): print(self.header, self.question, self.answer) return self.header, self.question, self.answer This is the template: {% extends 'main/base.html' %} {% load static %} {% block … -
Watchlist matching query does not exist
Iam trying to find out if a movie exists on the watchlist on my movie project and this error occured while i goes to detail page of a movie that doesn't exists in watchlist, how can i solve this? this is the code. this is my Watchlist model class Watchlist(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) movie=models.ForeignKey(Movie,on_delete=models.CASCADE) quantity=models.IntegerField(default=1) date=models.DateField(auto_now_add=True) def __str__(self): return self.movie.name this is my movie detail request function on views.py def view_movie(request,mslug): user=request.usermovie=Movie.objects.get(slug=mslug) watchlist=Watchlist.objects.get(user=user,movie__slug=mslug) return render(request,'moviesingle.html',{'mov':movie,'watchlist':watchlist}) this is the movie detail template <div class="social-btn"> {% if watchlist.is_none %} <a href="{% url 'Watchlist:add_watchlist' mov.id %}" class="parent-btn"> <i class="ion-plus"></i> Add to Watchlist</a> {% else %} <a href="" class="parent-btn"> <i class="ion-heart"></i> Already in Watchlist</a> {% endif %} </div> while going to a movie that exists on the watchlsit, its showing 'Already on watchlist', the problem is with the movies not in watchlist.. -
Django: Hide required field in form and generate value from other fields
Having a class like this: class MyClass(): foo = CharField('Foo', max_length=42) bar = CharField('Bar', max_length=42) baz = CharField('Baz', max_length=42) Fields "foo" and "bar" should be show in the form, field "baz" should NOT be shown. When POST'ing, the field "baz" should be generated from "foo" and "bar", e.g.: baz = foo + bar The "baz" field can be prevented from shown in the form by using the "HiddenInput" widget. Ok. But using the CBV: Where to generate the "baz" content from "foo" and "bar"? In the "def post()", in the "def is_valid()", in the "def clean()"? Or somewhere else? -
an error is displayed The view images.views.image_create didn't return an HttpResponse object. It returned None instead
' from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.contrib import messages from .forms import ImageCreateForm @login_required def image_create(request): if request.method == 'POST': # форма отправлена form = ImageCreateForm(data=request.POST) if form.is_valid(): # данные в форме валидны cd = form.cleaned_data new_image = form.save(commit=False) # назначить текущего пользователя элементу new_image.user = request.user new_image.save() messages.success(request,'Image added successfully') # перенаправить к представлению детальной # информации о только что созданном элементе return redirect(new_image.get_absolute_url()) else: # скомпоновать форму с данными, # предоставленными букмарклетом методом GET form = ImageCreateForm(data=request.GET) return render(request,'images/image/create.html',{'section': 'images','form': form}) ' if I write code from the phone and run it on Termux I tried to check the code but didn't find anything -
Implementing WooCommerce attributes into Django
I want to create a model where I can dynamically add the three attributes color, size and type like the images below taken from WooCommerce. Sometimes each feature comes in a single form and sometimes it comes in a double form -
python3.8 cannot import ed448 from cryptography.hazmat.primitives.asymmetric
I am using python3.8 to run a Django project, I tried to import Pisa from xhtml2pdf, got a error message listed below: File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/xhtml2pdf/pisa.py", line 26, in <module> from xhtml2pdf.document import pisaDocument File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/xhtml2pdf/document.py", line 24, in <module> from xhtml2pdf.builders.signs import PDFSignature File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/xhtml2pdf/builders/signs.py", line 5, in <module> from pyhanko.pdf_utils.incremental_writer import IncrementalPdfFileWriter File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyhanko/pdf_utils/incremental_writer.py", line 8, in <module> from . import generic, misc File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyhanko/pdf_utils/generic.py", line 21, in <module> from .misc import ( File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyhanko/pdf_utils/misc.py", line 18, in <module> from pyhanko_certvalidator.util import CancelableAsyncIterator, ConsList File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyhanko_certvalidator/__init__.py", line 8, in <module> from .context import ValidationContext File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyhanko_certvalidator/context.py", line 13, in <module> from .fetchers.requests_fetchers import RequestsFetcherBackend File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyhanko_certvalidator/fetchers/requests_fetchers/__init__.py", line 8, in <module> from .cert_fetch_client import RequestsCertificateFetcher File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyhanko_certvalidator/fetchers/requests_fetchers/cert_fetch_client.py", line 7, in <module> from ...errors import CertificateFetchError File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyhanko_certvalidator/errors.py", line 8, in <module> from pyhanko_certvalidator._state import ValProcState File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyhanko_certvalidator/_state.py", line 5, in <module> from pyhanko_certvalidator.path import ValidationPath File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyhanko_certvalidator/path.py", line 15, in <module> from .util import get_ac_extension_value, get_issuer_dn File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyhanko_certvalidator/util.py", line 10, in <module> from cryptography.hazmat.primitives.asymmetric import ( ImportError: cannot import name 'ed448' from 'cryptography.hazmat.primitives.asymmetric' (/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/cryptography/hazmat/primitives/asymmetric/__init__.py) P.S. my python version is 3.8.9, Django version is 2.0.7, cryptography version is 2.2.2. Can you please help me to figure it out? THX! -
Sending json and file(binary) together by requests() of python
I have this curl command which send file and data to my api. It works correctly. curl --location 'localhost:8088/api/' \ --header 'Content-Type: multipart/form-data' \ --header 'Accept: application/json' \ --form 'file=@"image.png"' \ --form 'metadata="{ \"meta\": { \"number\": 400 }}"' Now I want to do the equivalent thing to inside of the python. So I use requests however it says TypeError: request() got an unexpected keyword argument 'file' How can I do when sending the json and image data together? headers = { 'Content-Type': 'multipart/form-data', 'Accept': 'application/json' } metadata = {"number":400} response = requests.post('https://localhost:8088/api/', headers=headers, data={ metadata:metadata}, file = { open("image.png",'rb') } ) -
django show field from related model in form
I just don't get it. I have been reading but I am not even close to find the answer. It is most likely extremely easy. I have two models Person (Name and zipcode) and Zip (Zipcode and city). When registering a new person the field name and zipcode should be entered. When zipcode is entered the related correct city from the Zipmodel should be shown models.py class Zip(models.Model): zipcode = models.IntegerField() city = models.CharField(max_length=200) def __str__(self): return str(self.zipcode) class Person(models.Model): name = models.CharField(max_length=200) zipcode = models.ForeignKey('Zip',on_delete=models.CASCADE,) def __str__(self): return self.name forms.py from django import forms from .models import Zip, Person class PersonForm(forms.ModelForm): class Meta: model = Person fields = ('name', 'zipcode',) class ZipForm(forms.ModelForm): class Meta: model = Zip fields = ('zipcode', 'city',) views.py from django.shortcuts import render, redirect, get_object_or_404 from .forms import PersonForm, ZipForm from .models import Zip, Person def index(request): return render(request, 'theapp/index.html' ) def person_new(request): if request.method == "POST": form = PersonForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.save() return redirect('person_detail', pk=post.pk) else: form = PersonForm() return render(request, 'theapp/person.html', {'form': form}) def zip_new(request): if request.method == "POST": form = ZipForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.save() return redirect('zip_detail', pk=post.pk) else: form = ZipForm() return render(request, 'theapp/zip.html', {'form': form}) def … -
How to get the file object from request
I send file with javascript like this, fetch png from server and send to the python fetch(fileUrl,{headers: headers}) .then(response => response.blob()) .then(blob => new File([blob], "image.png")) .then(file => { var formData = new FormData(); formData.append("metadata",JSON.stringify(metadata)); formData.append("file",file); axios.post( ai_api,formData,{} ).then(function (response) { console.log("sent success"); } then in django @api_view(["POST"]) def jobs(request): metadata = request.POST.get("metadata") file = request.POST.get("file") print(metadata) # I can get the metadata here!! print(file) # None why this file is None? How can I get the file itself? -
i cannot create a column aws rds database using django
when i add code at models.py file to make a new column like below, partnerId = models.IntegerField(null=True, blank=True, default=None) # added and do "python manage.py makemigrations" and "python manage.py migrate", and migration is done successfully, but the 'partnerId' column' is created only in local mysql database, not in aws rds mysql database. how can i deal with this problem? -
ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported
I am working on a django project, it was working fine untill I added "namespace="polls" in the code below(urls.py) and connected it to "index.html" in 2nd code. 1st- urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('polls/', include('polls.urls', namespace="polls")), ] 2nd: index.html: {% extends 'polls/base.html' %} {% block main_content %} {% if latest_questions %} <ul> {% for question in latest_questions %} <li><a href={% url "polls:detail" question.id %}><b>{{question.question_text}}</b</a></li> {% endfor %} </ul> {% else %} <p> You don't have any questions. Please add some.</p> {% endif %} {% endblock %} Now when I renserver it shows following error: ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. Please help, where I am wrong, it could be some missing package/s too as it is recently installed pycharm. Thank you. -
django and stripe subscription payments issues
I'm trying to create a subscription based saas in django. There are three subscription tiers with both monthly and annual payment options. I have setup the stripe customer id to be created when a new user signs up. I have somehow managed to put together the forms so that they redirect to Stripe's checkout, but I can't save the subscription id and the subscription end date in the database. I get an error as well "An error occurred while creating the new subscription: Request req_8TXfavfNXo1P0A: This customer has no attached payment source or default payment method. Please consider adding a default payment method. For more information, visit https://stripe.com/docs/billing/subscriptions/payment-methods-setting#payment-method-priority." I want to be able to save the subscription id and subscription end date after a successful payment. My models.py from django.conf import settings from django.contrib.auth import get_user_model from django.db import models from django.db.models.signals import post_save import stripe stripe.api_key = settings.STRIPE_SECRET_KEY User = get_user_model() MEMBERSHIP_CHOICES = ( ('Free', 'free'), ('Basic', 'basic'), ('Premium', 'premium') ) class Membership(models.Model): membership_type = models.CharField( choices=MEMBERSHIP_CHOICES, default='Free', max_length=30) stripe_monthly_plan_id = models.CharField(max_length=40, blank=True, null=True) stripe_yearly_plan_id = models.CharField(max_length=40, blank=True, null=True) price_monthly = models.IntegerField(default=0) price_yearly = models.IntegerField(default=0) ordering = models.PositiveIntegerField(default=0) def __str__(self): return self.membership_type class UserMembership(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) stripe_customer_id … -
Nginx container don't see static from Django container
I launch containers through docker-compose, and when I go to url I see site without static. Where is the problem? git link to project - https://github.com/NNKapustin/docker-compose result I have tried different settings for Nginx and docker-compose.yml, but steel have same problem -
Docker-compose up starts Django server, but after changing index.html in templates folder, server doesn't reflect changes
My Dockerfile FROM python:3.6-slim ENV PYTHONUNBUFFERED 1 RUN mkdir /demo WORKDIR /demo ADD . /demo COPY requirements.txt . RUN pip3 install -r requirements.txt EXPOSE 8000 CMD python manage.py runserver 0:8000 my docker-compose file version: "3" services: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/app ports: - "8000:8000" i tried all solution which provided by chatgpt but none of them is working for me -
Django html dependencies
I'm new to Django, I'm trying to load bootstrap5 and js to my project. To achieve this, I created a 'base.html' under templates and extend it in my other html file. For example: {% extends 'base.html' %} {% block content %} <div class="mt-4"> <h2>Log In</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Log In</button> </form> </div> {% endblock %} This method works but I think it might make the maintenance harder if I include those tags in all of my html files, so is it possible to remove those tags and the dependencies still works? {% extends 'base.html' %} {% block content %} ... {% endblock %} I've tried to use a document_processors to load the CDN, I can confirm that this method is executed but the style is still not loaded if I remove the tags. # document.processor.py def base_template_variables(request): return { 'title': 'Default Title', 'bootstrap_css_cdn': 'https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/css/bootstrap.min.css', 'bootstrap_js_cdn': 'https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/js/bootstrap.bundle.min.js', } -
How to use the free domain given by ngrok?
In their release of ngrok https://ngrok.com/blog-post/new-ngrok-domains, they now provide free domains to free users as of April 2023. I can see my one free domain at https://dashboard.ngrok.com/cloud-edge/domains. However, I don't know how to use it. I have tried ngrok http -subdomain=xxx.ngrok-free.app 80 and ngrok http -subdomain=xxx 80 But it will give me an error Custom subdomains are a feature on ngrok's paid plans. Failed to bind the custom subdomain 'xxx.ngrok-free.app' for the account 'James Arnold'. This account is on the 'Free' plan. Is there a documentation on how to use this free domain by ngrok? -
How to Create different user/Member types in Python Django?
I need to create a paid memebership website with django.There are three types of members to be registered. these registration form/model will have different form fields appart from common authentication fields. In the admin panel these member/users should be listed separately from the super user/ admin/staff users. how can I achive this? models.py from datetime import timedelta, date, datetime from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.db import models from django.conf import settings from .constants import GENDER_CHOICES, RADIO_CHOICES, INDIAN_STATES,COUNTRIES, DISTRICTS_IN_KERALA class MemberType(models.Model): title = models.CharField(max_length=100, blank=True,null=True) slug = models.SlugField(blank=True, null=True) description = models.CharField(max_length=250, blank=True,null=True) price = models.FloatField() def __str__(self): return self.title class NurseMemberManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): if not email: raise ValueError('The Email field must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) return self.create_user(email, password, **extra_fields) class NurseMember(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) # Add other fields as needed is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) gender = models.CharField(max_length=1, choices=GENDER_CHOICES) date_of_birth = models.DateField(null=True) mobile_no = models.CharField(max_length=15) whatsapp_no = models.CharField(max_length=15) address_lene_1 = models.CharField(max_length=150) address_lene_2 = models.CharField(max_length=150) pin_code = models.CharField(max_length=10) nursing_reg_no = models.CharField(max_length=50) employed = models.BooleanField(choices=RADIO_CHOICES,default=True,) country = models.CharField(max_length=100, choices=COUNTRIES, blank=True, null=True) … -
How can I query my API in React in a way that has dynamically defined queries?
I'm using Django Rest Framework and React, but this is more of a conceptual question. I've noticed that when querying data from an API, especially on a React-esque frontend, I always run into the same issues. API responses are not intrinsically typed I cannot specific exactly what fields I'd like to get back from the API I can't specify dynamic type-safe filtering and sorting. In an ideal world, I'd like to be able to do something like this: // Using a user model as an example. export function UserComponent(props: ...){ // `data` is inferred to be of type Pick<User, "email", "lastActive"> const data = myCustomAPIFetch<User>({ model: User fields: [User.email, User.lastActive], filters: { [User.firstName]: "Linus" } // Similar syntax for sorting }) return (...) } This solves all three issues - it returns the proper type object, filtering/sorting is type-safe, and the exact fields that I want back can be specified. The solutions that I've researched here solve some of the problems, but not all. Graphql - solves #2 and can solve #1, but from what I understand I have to make a new query/resolver for each filter or sort I want to do. Not ideal. Protobuf - types are cross-language … -
Django App fails to upload file to quickbooks
Hello all I am encountering a problem while trying to upload a file to quickbooks using the api. Below is the code, I get a success but the file is not sent or cannot be found in the bill itself. Any help would be appreciated. Inside my app views.py def handle_file_uploads(request): auth_client = AuthClient( settings.CLIENT_ID, settings.CLIENT_SECRET, settings.REDIRECT_URI, settings.ENVIRONMENT, access_token=request.session.get('access_token', None), refresh_token=request.session.get('refresh_token', None), realm_id=request.session.get('realm_id', None), ) if auth_client.access_token is None: return JsonResponse({'status': 'failure', 'message': 'Access token not available.'}) if auth_client.realm_id is None: raise ValueError('Realm id not specified.') if request.method == 'POST': # Get the file input names for each bill ID bill_ids = [key.replace('bill_', '') for key in request.FILES.keys()] for bill_id in bill_ids: uploaded_file = request.FILES.get(f'bill_{bill_id}') if uploaded_file: # Prepare the API endpoint URL to upload the attachment url = f"https://sandbox-quickbooks.api.intuit.com/v3/company/{auth_client.realm_id}/upload" # Prepare the request headers headers = { 'Authorization': f'Bearer {auth_client.access_token}', } # Prepare the file data to be sent as multipart form data files = { 'file_content': (uploaded_file.name, uploaded_file.read(), uploaded_file.content_type), } # Make the API call to upload the attachment response = requests.post(url, files=files, headers=headers) print(response.json) # Check the response status and handle the error case if necessary if response.status_code != 200: error_message = 'API call failed with status … -
ValueError at /store/place_order/ Cannot assign "<SimpleLazyObject: <User: user>>": "Order.user" must be a "User" instance
I am very new with django, i am trying to build a e-commerce store in django in my django project i have two applications accounts and store i my accounts application my form.py looks like this:- from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm from django import forms class UserCreateForm(UserCreationForm): mobile_number = forms.CharField(max_length=15, required=True) date_of_birth = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'})) gender = forms.ChoiceField(choices=[('M', 'Male'), ('F', 'Female'), ('O', 'Other')], required=True) class Meta(): fields = ('username', 'email', 'date_of_birth', 'gender', 'mobile_number', 'password1', 'password2',) model = get_user_model() def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) self.fields['username'].label = 'Display Name' self.fields['email'].label = 'Email Address' self.fields['mobile_number'].label = 'Mobile Number' self.fields['date_of_birth'].label = 'Date of Birth' self.fields['gender'].label = 'Gender' in accounts/views.py:- from django.shortcuts import render, get_object_or_404 from django.urls import reverse_lazy from . import forms from django.views.generic import CreateView from .forms import UserCreateForm from django.contrib.auth import get_user_model from django.contrib.auth.models import User from django.views.generic import TemplateView class SignUp(CreateView): form_class = forms.UserCreateForm success_url = reverse_lazy('index') template_name = 'accounts/signup.html' def profile(request): return render(request,'accounts/profile.html',{'username':request.user, 'email':request.user.email, 'first_name':request.user.first_name, 'last_name':request.user.last_name}) class UserCreateView(CreateView): form_class = UserCreateForm success_url = reverse_lazy('index') template_name = 'accounts/signup.html' def form_valid(self, form): response = super().form_valid(form) self.success_url = reverse_lazy('profile', args=[self.object.pk]) return response in my store application models.py looks like this: - from django.db import models import datetime from accounts.models import User import … -
How to implement reuse of a discount code used for a canceled order?
I have a Django project to implement discount codes. The models are as follows: class CouponCode(models.Model): max_usage = models.PositiveSmallIntegerField() max_usage_per_user = models.PositiveSmallIntegerField(default=1) code = CharField(max_length=10, unique=True) discount_percent = models.PositiveSmallIntegerField(default=0, validators=MaxValueValidator(100)]) max_discount_amount = models.PositiveIntegerField(default=0) is_active = models.BooleanField(default=True) start_date = models.DateTimeField(null=True, blank=True) end_date = models.DateTimeField(null=True, blank=True) minimum_price = models.PositiveBigIntegerField(default=0) class UsedCode(models.Model): customer = models.PositiveBigIntegerField(verbose_name='customer id') coupon = models.ForeignKey(CouponCode, on_delete=models.PROTECT) order_id = models.PositiveIntegerField() @classmethod def has_reached_max_usage_for_user(cls, coupon, user): usages = cls.objects.filter(coupon=coupon, customer=user).count() if usages < coupon.max_usage_per_user: return False return True @classmethod def has_reached_max_usage(cls, coupon): usages = cls.objects.filter(coupon=coupon).count() if usages < coupon.max_usage: return False return True Every time an order is created with a coupon code, a UsedCode object is created. I want to implement a feature where the coupon code can be reused if the order is cancelled. I prefer not to delete the objects so I can track the data. -
Save file (not in MEDIA_ROOT) to Django FileField from fastapi UploadFile
I need to save a fastapi UploadFile object directly to a Django model defined below: class MyFile(models): file = models.FileField(upload_to="files/") In the API, I managed to obtain file object from the SpooledTemporaryFile using the read and write methods like in the block below: async def file_upload(file: UploadFile = File(...)): async with aiofiles.open(f"path/{file.filename}", "wb") as media: cont = await file.read() await media.write(cont) Then I try to convert the new file to FieldFile type in Django to be able to save it in the MyFile.file field but it kept returning a TypeError with the description: write() argument must be str, not generator from django.core.files import File as DjangoFile async def file_upload(file: UploadFile = File(...)): ... async with aiofiles.open(f"path/{file.filename}") as media: d_file = DjangoFile(media) file_model = MyFile() file_model.file.save(file.filename, d_file) file_model.save() return {"ok": True} The stack trace revealed file_model.file.save(file.filename, d_file) as the offending line. >>> type(file.filename) str >>> type(d_file) <class 'django.core.files.base.File'> Could you point me in the right direction? Thanks. -
Running django test, migrations with django.conf import settings are not using DJANGO_SETTINGS_MODULE or --settings override settings
I have a migration which does a check on settings.DEBUG, I've imported settings using from django.conf import settings and if it's False I'm expecting that this is a production(or production-ish) environment so I'm importing a secrets manager secret to use in a createsuperuser migration function, otherwise it's local hosting or local dev and I'm just using a hard coded string. My problem is that in my settings.py I've set DEBUG to false as a safe default, similar to how I set my SECRET_KEY to None so that if for some reason the settings override fails I get an error not the generated SECRET_KEY. Anyway, back from that aside, I'm trying to run ./manage.py test --settings=myproject.test (I have also tried using an export of DJANGO_SETTINGS_MODULE='myproject.test') to load my test.py settings file, at the top of which it does a from .settings import * import and then further down the page I overwrite the setting with DEBUG = True. So in my migration I from django.conf import settings and I'm expecting that to load my DJANGO_SETTINGS_MODULE settings, when I run my tests and it runs my migrations, I'm expecting that from django.conf import settings is going to use my DJANGO_SETTINGS_MODULE settings I …