Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploy multiple sites from a single repository
I have a repository which has three projects, a django rest api, a react dashboard, and a react frontend, this is a store website, that should be used by multiple users, where I want to update all websites (stores) once I make any changes to the repo, I use dockerfile for each project in this repo, and docker-compose file to deploy the project in the server. using environment variables to distinguish between sites, like styles colors, name, etc... my problem now is that the frontend in the built stage is not accessing the environment variables, and this is the problem exactly, that the frontend should be built with the variables, I want to use the container in multiple places. how to handle this I need just an overview solution to this. the must important thing is to make sure that updates goes to all stores websites, I just need to use this command: dokcer compose up --force-recreate -d is that possible ? -
Django Private or Public posts
For my django app I want to enable the user to select whether a post is public or private. This is my best attempt so far: views.py def home(request): recipes = models.Recipe.objects.filter(recipe_private, recipes) context = { 'recipes': recipes } def recipe_private(): for recipe in recipes: if recipe(is_private=True) and recipe.author == self.request.user: True else: False return render(request, "recipes/home.html", context) And here is my models.py: class Recipe(models.Model): title = models.CharField(max_length=100) description = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) serving = models.PositiveIntegerField(default=1) temperature = models.PositiveIntegerField(default=1) prep_time = models.PositiveIntegerField(default=1) cook_time = models.PositiveIntegerField(default=1) ##tags = models.ManyToManyField('Tag') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) id = models.CharField(max_length=100, default=uuid.uuid4, unique=True, primary_key=True, editable=False) def get_absolute_url(self): return reverse('recipes-detail', kwargs={"pk": self.pk}) def __str__(self): return str(self.title) The logic works in my head but not in practice, how would I improve this? I want it so only the author can see their own private posts, anyone who isnt the author shouldnt be able to see a post marked as private. -
Custom User admin issue
I am creating a custom User model and I cant get Users table in my admin models.py: class EmailUserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): if not email: raise ValueError('Email required') 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 EmailUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = EmailUserManager() USERNAME_FIELD = 'email' groups = models.ManyToManyField(Group, related_name="customuser_set") user_permissions = models.ManyToManyField(Permission, related_name="customuser_set") settings.py: AUTH_USER_MODEL = 'jwt_auth.EmailUser' admin.py: from django.contrib import admin from django.contrib.auth import get_user_model User = get_user_model() admin.register(User) I already run migrations and I actually can create superuser and log in to my admin. I didnot find any solution on the internet. If anybody knows how to fix admin please help. -
Retrieve data from CKEditor using ajax to not cause the page to reload*
Here is my code first: forms code from product.html: ... {% comment %} Review Form Start`` {% endcomment %} <div class="container"> <section class="review-section col-12 mt-4"> {% comment %} Display All Reviews {% endcomment %} <h3 class="hide-review-heading">Reviews</h3> {% for review in reviews %} <div class="review"> <p><strong>{{ review.user.username }}</strong> - {{ review.rating }} stars</p> <p>{{ review.review | safe }}</p> </div> <hr> {% empty %} <p>No reviews yet. Be the first to write a review!</p> {% endfor %} <h3 class="hide-review-heading">Write a Review</h3> <strong class="" id="review-response"></strong> <form action="{% url 'home:ajax_add_review' p.pid %}" method="POST" class="hide-review-form" id="commentForm"> {% csrf_token %} <div class="form-group mt-3"> {{ review_form.review }} </div> <div class="form-group mt-3"> {{ review_form.rating.label_tag }}<br> {{ review_form.rating }} </div> <br> <button type="submit" class="btn btn-primary">Submit</button> </form> </section> </div> {% comment %} Review Form End {% endcomment %} {% endblock body %} review.js: console.log("review.js loaded"); $("#commentForm").submit(function(e) { e.preventDefault(); $.ajax({ data: $(this).serialize(), method: $(this).attr("method"), url: $(this).attr("action"), dataType: "json", success: function(response) { console.log("Comment saved to DB") if (response.bool) { $("#review-response").html("Review saved successfully"); // Assign a class and remove text-danger class if there $("#review-response").addClass("text-success"); $("#review-response").removeClass("text-danger"); $(".hide-review-form").hide(); $(".hide-review-heading").hide(); } else { $("#review-response").html("Error saving review"); $("#review-response").addClass("text-danger"); $("#review-response").removeClass("text-success"); } } }); }); urls.py: from django.urls import path from . import views app_name = "home" urlpatterns = … -
Static files not served in Django production [duplicate]
My Django application working perfectly on my local machine but when I successfully deployed it to AWS EC2, I don't get any styling. I tried search for solution as many others faced this issue but non of the answers fixed my case. I tried a lot of stuff for two days but nothing seem to work with me. What am I missing or doing wrong? Appreciate your help! These are my folders: enter image description here This is my settings.py file: import dj_database_url import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Application definition INSTALLED_APPS = [ # Django Apps 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # My Apps 'main_app.apps.MainAppConfig' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', # My Middleware 'main_app.middleware.LoginCheckMiddleWare', ] ROOT_URLCONF = 'student_management_system.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['main_app/templates'], #My App Templates 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] # WSGI_APPLICATION = 'student_management_system.wsgi.application' ASGI_APPLICATION = 'student_management_system.asgi.application' # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = '/static/' MEDIA_URL = '/media/' # STATIC_ROOT = os.path.join(BASE_DIR, 'static') # MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_ROOT = … -
Unknown field(s) (post) specified for CategoryModel. Check fields/fieldsets/exclude attributes of class CategoryAdmin
I give this error and I don't have any idea about it. `@admin.register(models.CategoryModel) class CategoryAdmin(admin.ModelAdmin): fieldsets = [ ( 'Main', { 'classes' : ('wide',), 'fields' : ['title', 'slug', 'post', 'image', 'description', 'sub_category', 'is_sub_category', 'created_at', 'updated_at'] }, ), ] list_display = ['title', 'is_sub_category', 'sub_category', 'created_at',] list_filter = ['created_at', 'updated_at', 'sub_category',] readonly_fields = ['created_at', 'updated_at',] search_fields = ['title', 'created_at',] prepopulated_fields = { 'slug' : ('title',) } raw_id_fields = ['sub_category',] def get_form(self, request: Any, obj: Any | None = ..., change: bool = ..., **kwargs: Any) -> Any: help_text_fields = 'It initializes automatically' help_texts = { 'created_at' : help_text_fields, 'updated_at' : help_text_fields, } kwargs.update({ 'help_texts':help_texts }) return super().get_form(self, obj=obj, change=change, **kwargs)` -
Integrating Holoviz Panel and Django to build Dashboard Webapps
I am looking for any working example of a Django project that is integrated with Panel Apps. There is a section in the user guide that gives tips on how to integrate. But I am unable to get it to work. Could you please share any available resources online that demonstrates the integration. The code I tried is this (and its variants) The actual business logic is not important here. I want to integrate the Panel Dashboards and Django successfully. # project structure: # myproject/ # manage.py # myproject/ # __init__.py # settings.py # urls.py # wsgi.py # app1/ # __init__.py # apps.py # views.py # app2/ # __init__.py # apps.py # views.py # myproject/settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app1', 'app2', 'panel', ] # myproject/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('app1/', include('app1.urls')), path('app2/', include('app2.urls')), ] # app1/apps.py from django.apps import AppConfig class App1Config(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'app1' # app1/views.py import panel as pn from django.http import HttpResponse def app1_panel(request): # Create a simple Panel app slider = pn.widgets.FloatSlider(start=0, end=10, name='Slider') text = pn.widgets.StaticText(name='Slider Value') @pn.depends(slider.param.value) def update_text(value): text.value = f"Slider value: {value:.2f}" app = … -
My Django website is unable to know if visitor is logged in or not
I am trying to deploy a website which does something depending on if the user is login or not. I tested it on local host and it worked but now that I try to deploy on pythonanywhere it seems to to recognize user though I logged in again. I used the "user.is_authenticated method" in my html template -
Downloading Images from S3 bucket in Django
Trying to download images with a download button but when i click it goes to the s3bucket link instead of downloading the image. The link it redirects to is https://bucketname.s3.amazonaws.com/images/filename.jpeg. I want the download button to download the image to the users device when this is clicked instead of redirecting. Heres my main gallery view which uses the search prompt to find the filenames + keywords in my db and then retrieves the matching images from the bucket. def gallery(request): query = request.GET.get('q', 'free wallpapers') s3_image_urls = [] top_search_terms = [] keywords = query.split() conditions = [] query_params = [] for keyword in keywords: conditions.append("description LIKE %s") query_params.append('%' + keyword + '%') sql_query = "SELECT image_key FROM images_table WHERE " + " AND ".join(conditions) with connection.cursor() as cursor: cursor.execute(sql_query, query_params) results = cursor.fetchall() s3_bucket_url = 'https://{}.s3.amazonaws.com/images/'.format(settings.AWS_STORAGE_BUCKET_NAME) # Generate image URLs for result in results: for image_key in result: image_url = s3_bucket_url + image_key s3_image_urls.append(image_url) # Log the search term into the search_logs table with connection.cursor() as cursor: cursor.execute("SELECT search_count FROM search_logs WHERE search_term = %s", [query]) row = cursor.fetchone() if row: new_count = row[0] + 1 cursor.execute("UPDATE search_logs SET search_count = %s WHERE search_term = %s", [new_count, query]) else: # … -
Import 'django.urls' could not be resolved from source Pylance(Report Missing Module Source)
For configuring the global URLconfig on a project name, the codes "from django.urls import include, path" was required. When implemented on VScode, the warning is shown: 'django.urls could not be resolved from source--Pylance'. I followed exactly as per the tutorial in W3 school. I am new to this area. I am unable to detect the mistake on my part despite several checking on the step by step procedure detailed in the tutorial -
Authorize.Net throws "User authentication failed due to invalid authentication values" but works in sandbox. All credentials are verified as correct
I've test it for valid card and also few times I recreate transaction keys but it helpless. I checked all forums about this. Ive got 007 code error which says Posting a live account's API Login ID and Transaction Key to the test environment at https://apitest.authorize.net/xml/v1/request.api. For live accounts, please post to https://api.authorize.net/xml/v1/request.api instead. Posting a test account's API Login ID and Transaction Key to the live environment at https://api.authorize.net/xml/v1/request.api. For test accounts, please post to https://apitest.authorize.net/xml/v1/request.api instead. The API Login ID or Transaction Key have errors. Im sure all my creds are correct, I cheched it 100 times. first of all I create customer payment profile if it does not exists already def create_customer_profile(cls, user: User, merchant_auth): if not user.customer_profile_id: customer_data = { "merchantCustomerId": str(user.id), "email": user.email, } create_customer_profile = apicontractsv1.createCustomerProfileRequest() create_customer_profile.merchantAuthentication = merchant_auth create_customer_profile.profile = apicontractsv1.customerProfileType( **customer_data ) controller = createCustomerProfileController(create_customer_profile) controller.execute() response = controller.getresponse() if response.messages.resultCode == "Ok": user.customer_profile_id = response.customerProfileId user.save() return response.customerProfileId else: raise TransactionCanceled( message=str(response.messages.message[0]["text"].text) ) return user.customer_profile_id after that I try to create customer payment profile with all credit card and billing data @classmethod def create_customer_payment_profile( cls, card_details, billing_address, user: User, default: bool ): merchant_auth = cls.merchant_auth() payment = apicontractsv1.paymentType() credit_card = apicontractsv1.creditCardType() … -
connecting the backend directly to a distant postgresql database is slow (10 insertions/sec )
i tried to host the postgres 16 db in a windows 19 server that is in the same region of the backend server that is also a windows server , it only saves 10 rows per second even when having pool of open sessions with db , but on localhost it saves 100k in less than a sec , I don't believe that two servers in same region will have this slow connection , because when sending via HTTP , I can receive them requests , but connecting backend to db directly is not able to surpass 10 insertions/sec . note that I'm only trying to insert new rows , I'm not trying to execute complex queries . if someone have a solution please help. -
How to execute a Python script which uses a library which produces a visualization in a Angular JS dashboard?
I'm trying to figure out the best way to integrate Python code and render the output onto an Angular dashboard. Here is the library I'd like to execute in Python and then take the rendered output and place it into a Angular JS dashboard: https://robert-haas.github.io/gravis-docs/index.html The library is called Gravis and this rendering can be outputted in several ways such as using gv.vis(), gv.d3(), fig.display(), fig.export_html(), as well as export to svg and others. I'm trying to figure out what is the most optimal way to do this with Angular Javascript or just JS in general. Here is an example Python code that outputs a Gravis visualization: import gravis as gv graph1 = { 'graph':{ 'directed': True, 'metadata': { 'arrow_size': 5, 'background_color': 'black', 'edge_size': 3, 'edge_label_size': 14, 'edge_label_color': 'white', 'node_size': 15, 'node_color': 'white', }, 'nodes': { 1: {'metadata': {'shape': 'rectangle', 'y': 200}}, 2: {}, 3: {}, 4: {'metadata': {'shape': 'rectangle', 'y': 200}}, 5: {'metadata': {'shape': 'hexagon', 'y': 0}}, }, 'edges': [ {'source': 1, 'target': 2, 'metadata': {'color': '#d73027', 'de': 'Das', 'en': 'This'}}, {'source': 2, 'target': 3, 'metadata': {'color': '#f46d43', 'de': 'ist', 'en': 'is'}}, {'source': 3, 'target': 1, 'metadata': {'color': '#fdae61', 'de': 'das', 'en': 'the'}}, {'source': 1, 'target': 4, 'metadata': {'color': … -
Django NoReverseMatch Error: How do I generate urls for each Model
I'm facing a NoReverseMatch error in my Django application when trying to generate URLs for product detail pages. The error message indicates that the URL pattern for 'product-detail' with the provided pk and slug is not found. Here are the details of my setup: NoReverseMatch at /earrings Reverse for 'product-detail' with arguments '('', '')' not found. 1 pattern(s) tried: ['product/(?P[0-9]+)/(?P[-a-zA-Z0-9_]+)/\Z'] Model: class Product(models.Model): name = models.CharField(max_length=400) price = models.IntegerField(default=0) description = RichTextField(null=True, blank=True) slug = models.SlugField(unique=True, null=True, blank=True, max_length=400) create_at = models.DateTimeField(null=True, blank=True) id = models.AutoField(primary_key=True) def get_absolute_url(self): return reverse('product-detail', kwargs={'pk': self.pk, 'slug': self.slug}) def __str__(self): return f'{self.name}' View: class ProductDetailView(DetailView): model = Product template_name = 'tehApp/product_detail.html' context_object_name = 'product' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['Products'] = Product.objects.all() return context def get_object(self): return get_object_or_404(Product, pk=self.kwargs['pk'], slug=self.kwargs['slug']) URL: urlpatterns = [ path('product/<int:pk>/<slug:slug>/', ProductDetailView.as_view(), name='product-detail'), ] Template: {% for product in products %} <div class="item" data-name="{{ product.name }}" data-price="{{ product.price }}" data-date="{{ product.create_at|date:"Y-m-d\TH:i:s" }}"> <div class="relative"> <div class="relative thumbnail"> {% with images=product.images.all %} {% if images|length > 0 %} <a href="{% url 'product-detail' product.pk product.slug %}"> <img width="250px" height="250px" class="" src="{{ images.0.image.url }}" alt=""> </a> {% endif %} {% if images|length > 1 %} <img width="100%" height="100%" class="hidden" src="{{ images.1.image.url }}" … -
Problem sending Persian emails with django's EmailMessage
I'm fairly new to django and was trying to send an email containing Persian letters using django.core.mail.EmailMessage . here is my code: from django.core.mail import EmailMessage from django.conf import settings def custom_sender(subject: str, body: str, recipient_list: list[str], attachments: list[str] = (), content_type_html: bool = False): try: email = EmailMessage( subject, body, settings.DEFAULT_FROM_EMAIL, recipient_list, ) if content_type_html: email.content_subtype = "html" for attachment in attachments: email.attach_file(attachment) email.send() except Exception as e: print(f'\n\nFailed to send email: {e}\n\n') and this is how I tried to use it in my view : custom_sender(subject='ایمیل تستی', body='این یک ایمیل تستی است.', recipient_list=[user.email]) but I encounter this error : 'charmap' codec can't encode character '\u06cc' in position 1: character maps to <undefined> I have noticed that I can't even print Persian stuff out in the console in my django project and I keep encountering this same error (this doesn't happen outside of my django project, and I CAN print Persian letters out in the console). can someone please tell me what this error is about and how I can fix it? I asked some AIs and tried a bunch of solutions like encoding the subject and body using .encode('utf-8') and using django's smart_str , or using python's unicode … -
Issue with Extracting Text from Images Using Django and Tesseract OCR
I am working on a Django project where I need to extract text from images using Tesseract OCR. The images are often blurred and low in contrast, and contain various text blocks such as headings, dates, small letters, bold letters, and sometimes even blurred letters. The image dimensions are approximately 256 x 350 pixels with a resolution of 96 DPI. import os from django.shortcuts import render from django.core.files.storage import FileSystemStorage import pytesseract import cv2 from PIL import Image import numpy as np import re # Set Tesseract command pytesseract.pytesseract.tesseract_cmd = '/usr/bin/tesseract' def clean_text(text): # Example of cleaning common OCR errors text = re.sub(r'\s+', ' ', text) # Remove extra whitespace text = re.sub(r'[^\w\s,.!?;:()"\']', '', text) # Keep common punctuation return text.strip() def home(request): return render(request, 'layout/index.html') def preprocess_image(image_path): # Read the image image = cv2.imread(image_path, cv2.IMREAD_COLOR) if image is None: raise ValueError(f"Error loading image: {image_path}") # Use the red channel to improve contrast red_channel = image[:, :, 2] # Convert to grayscale (using red channel) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Manually stretch the histogram to improve contrast # Histogram stretching min_val = np.min(gray) max_val = np.max(gray) stretched_gray = ((gray - min_val) / (max_val - min_val) * 255).astype(np.uint8) # If text … -
OK issue #4,54645,546546546, either have your form data submitted to your CRM system, or don' have your form redirected to a success page
You're going to love this one. This one is hilarious.... Have you ever developed a website whereby you can either have your form data submitted to your CRM system, OR you have your website not redirect to a confirmation page upon successful submission of said form. I have. This could only happen to me, couldn't it ? I mean, why would this make my life easy, eh? I mean, that would just way waaaay too much to ask for, wouldn't it? For something just work, just to have your form submit your data with no issues AND redirect to a success page? Oh no because that would just be waaaaay too simple. Why not have it completed in circa 10 minutes when you can waste 6 hours of your life ripping your hair out Here it is! My views.py def raise_support_ticket(request): '''Function to create the ticket. Once created, this will be passed to the "handle_ticket_creation() function" Vendor: freshdesk.com ''' from legal.forms import LegalDocumentsFeedback if request.method == 'POST': form = LegalDocumentsFeedback(request.POST) if form.is_valid(): # Extract data from the form name = form.cleaned_data['name'] subject = form.cleaned_data['subject'] description = form.cleaned_data['description'] email = form.cleaned_data['email'] #Pass this data to the ticket creation handler result = … -
How to set up logging for just my code in Django
I'm having trouble figuring out how to set up a logger for just my app. My app is named calibration. This is what I have in settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'root': { 'handlers': ['console'], 'level': 'INFO' }, 'formatters': { 'verbose': { 'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}', 'style': '{', }, 'simple': { 'format': '{levelname} {asctime} {module} {message}', 'style': '{', }, }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'simple' }, 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR, 'cerfServer.log'), 'formatter': 'verbose' } }, 'loggers': { 'django.db.backends': { 'handlers': ['console'], 'level': 'INFO', }, 'django': { 'handlers': ['console', 'file'], 'level': 'INFO', 'propagate': True, }, 'django.request': { 'handlers': ['console', 'file'], 'level': 'DEBUG', 'propagate': True, }, 'calibration': { 'handlers': ['console', 'file'], 'level': 'DEBUG', 'propagate': False } } } I assume that I create a logger with the same name as my app. But this is not working. I am not seeing my Debug messages. If I set the root logger to DEBUG, then I do see the Debug messages, as we as for everything else such as Boto. I want to leave Root set to Info and only see my Debug messages -
"IntegrityError at /payment_getway/ FOREIGN KEY constraint failed in Django"
I'm working on a Django project where users can place orders and I’m encountering an IntegrityError related to a foreign key constraint. Error: IntegrityError at /payment_getway/ FOREIGN KEY constraint failed View code: def payment_getway(request): if request.method == "POST": user = request.user # Retrieve address data from the form # address_id = request.POST.get('address_id') # Make sure you pass this ID in your form # Retrieve the address instance address_instance = get_object_or_404(Address, user=user) # Create a new CartOrder instance order = CartOrder( user=user, full_name=address_instance.name, email=address_instance.email, mobile=address_instance.mobile, address=address_instance, # Assign the Address instance here landmark=address_instance.landmark, city=address_instance.region, state=address_instance.region, # Update as per your address model postalCode=address_instance.pin, ) order.save() cart_total_ammount=0 if 'cart_data_obj' in request.session: for p_id, item in request.session['cart_data_obj'].items(): cart_total_ammount += int(item['qty']) * float(item['price']) #getting total ammount for the cart # for p_id, item in request.session['cart_data_obj'].items(): # cart_total_ammount += int(item['qty']) * float(item['price']) cart_order_products = CartOrderItems.objects.create( user=request.user, order=order, invoice_num= str(order.id), # INVOICE_NO-3 item=item['title'], image=item['image'], qty=item['qty'], price=item['price'], total=float(item['qty']) * float(item['price']), # product = Product.objects.get(pid=item['pid']) ) # Redirect or render a success page return redirect('core:order_confirmation') # Update with your success URL # Render payment page with context user = request.user addresses = Address.objects.filter(user=user) return render(request, "core/payment-getway.html", {"addresses": addresses}) Models: class CartOrder(models.Model): user=models.ForeignKey(CustomUser,on_delete=models.CASCADE) sku=ShortUUIDField(length=10,max_length=100,prefix="sku",alphabet="1234567890") oid=ShortUUIDField(length=10,max_length=100,prefix="oid",alphabet="1234567890") full_name=models.CharField(max_length=100,null=True,blank=True) email=models.CharField(max_length=100,null=True,blank=True) mobile=models.CharField(max_length=100,null=True,blank=True) address=models.CharField(max_length=100,null=True,blank=True) … -
Django failes to understand what the term "redirect" is
I could literally scream right now. If its not one issues, it's another. What is so difficult for Python to work out what the function redirect is? Why is it not redirector despite the ace that I have told it to redirect? What part of redirect does Python not understand? Why does it just refresh the page with the form no longer present? If I wanted it to refresh the page on form submission, I would have told it to refresh the page on form submission. However, I have told it to redirect to a success page n form submission, so why is it not redirecting to a success page n form submission. I mean, come on. this is simple basic stuff that a human can understand, why can't Python understand this? MRE #support.views def raise_support_ticket(request): '''**DEMO** This is a demo function, in development. ''' from legal.forms import LegalDocumentsFeedback if request.method == 'POST': form = LegalDocumentsFeedback(request.POST) if form.is_valid(): # Extract data from the form name = form.cleaned_data['name'] subject = form.cleaned_data['subject'] description = form.cleaned_data['description'] email = form.cleaned_data['email'] try: # Call a function to handle form data result = handle_ticket_creation(name, subject, description, email) if result: print("Your ticket has been successfully created and … -
Django jwt cannot customize authentication return message
enter image description here[[enter image description here](https://i.sstatic.net/oTr8Qx1A.png)](https://i.sstatic.net/yrSsiK30.png) Django jwt cannot customize authentication return message `{ "refresh": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTcyMjY3NzE5NCwiaWF0IjoxNzIyNTkwNzk0LCJqdGkiOiI2ZDJmMGMzYzg2MTc0MDhkODExMGZmZmMxZDUxYjIxOCIsInVzZXJfaWQiOjF9.lomSSwRHBLwzdfJgQUy4o-qxn9bb4_bF0ScNsRIDMWw", "access": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNzIyNTkxMDk0LCJpYXQiOjE3MjI1OTA3OTQsImp0aSI6ImYwZmI2MjI5ZGQ1YjRlZDhhMWNmZGY5MGE5ZDRkZWViIiwidXNlcl9pZCI6MX0.Va9l4cPqomfSeI3emtqjlczlho2fzkVvSerQ-_jWR0w" } ` 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema' -
Django form returning Validation errors for fields that have never existed
What is the valid reason behind why it's: failing to redirect to the appropriate error page if result if false telling me that the description field is apparently invalid when it isn't (upon testing the field with string content, telling me that there is a missing field named message and a missing field names subject despite the fact that I have never specified a field named message or subject in the first place This is my MRE #support.views def raise_support_ticket(request): '''**DEMO** This is a demo function, in development. ''' from legal.forms import LegalDocumentsFeedback if request.method == 'POST': form = LegalDocumentsFeedback(request.POST) if form.is_valid(): # Extract data from the form name = form.cleaned_data['name'] description = form.cleaned_data['description'] email = form.cleaned_data['email'] try: # Call a function to handle form data result = handle_ticket_creation(name, description, email) if result: return redirect('success') else: print("Invalid form submission") #Verification that its; thinking its an invalid firm submission print(form.errors) form.add_error(None, 'Failed to create ticket. Please try again.') return redirect('error.html') #Failing to redirect except Exception as ex: messages.error(f"Error in form validation. Error: {ex}") print(f"Exception Error: {ex}") return render(request, 'error.html') else: form = LegalDocumentsFeedback() return form def handle_ticket_creation(name, description, email): """ Function to handle ticket creation. This function could send data to … -
How to make a API in django which will take user as input and return longitude and latitude of the user?
I need to develop an API endpoint that, given a user model, returns the current longitude and latitude of the user. This API is intended for use in a project where you want to display the user's location on a map. The endpoint should take a user ID or similar identifier as input and respond with the geographical coordinates of the user. The location data should be fetched from a backend system where it is regularly updated. The API should be designed with proper security measures to ensure only authorized access to user location data. -
Django URL reset after authentication fail
if user is not None: login(request, user) return redirect('home') else: error_message = "Invalid username or password." return render(request, 'login.html', {'error_message': error_message}) Using the above code, if user enters wrong credentials, login.html shows up successfully with error message. But now the URL is http://localhost:8000/authentication_view/. Now if the user re-enters credentials, the URL will be http://localhost:8000/authentication_view/authentication_view/, and it creates Page Not Found error. If I use return redirect('login_view'), then the error message will not show. Could someone help me how to show login page with error message without adding Authentication View to the URL? I was expecting: if user provides wrong credentials, he gets error message and goes back to login page. Now he can re-enter credentials. But now login page is not usable because authentication view name is already added to the URL. New login attempt will add authentication view name twice the URL. -
Pytest doesn't found my settings directory
I tried to start pytest but the settings file cannot be found by pytest I'm in virtualenv with Python 3.11.9 and pytest 8.3.2 ImportError: No module named 'drf.settings' pytest-django could not find a Django project (no manage.py file could be found). You must explicitly add your Django project to the Python path to have it picked up. here the structure of my project ├── README.md ├── drf │ ├── drf │ │ ├── __init__.py │ │ ├── production_settings.py │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── manage.py │ └── tests │ ├── __pycache__ │ │ └── test_auth.cpython-311-pytest-8.3.2.pyc │ ├── factory_boy │ │ ├── __pycache__ │ │ │ └── factory_models.cpython-311.pyc │ │ └── factory_models.py │ └── test_auth.py ├── drf-uwsgi.ini ├── pytest.ini ├── requirements.in ├── requirements.txt and here the content of pytest.ini [pytest] DJANGO_SETTINGS_MODULE = drf.settings.py python_files = test_*.py What I have tried so far: I tried to add init.py to tests directory (seems not be recommended and didn't worked) deactivate and reactivate the virtualenv change drf.settings.py for drf.drf.settings but nothing run pytest as module with python -m pytest tests edit: if I cd drf and tried I get a little different error ImportError: No module …