Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
colorpicker and field validation
I am using TabularInlines to gather some information, one of which is a colorfield: class UnitForm(forms.ModelForm): class Meta: model = Unit fields = ["date", "name", "label", "color"] widgets = {"color": TextInput(attrs={'type': 'color'}),} class UnitTabularInline(admin.TabularInline): form = UnitForm model = Unit extra = 0 ##workaround class StockAdmin(admin.ModelAdmin): list_display = [] inlines = [UnitTabularInline] My problem is, without the extra = 0 switch, I always see 3 "empty" fields (which I actually want to see). But I cannot save my form, if I do not fill out all the fields, because the colorpicker has a preselected value. It seems that when input has type="color" there is always a color defined, and there's no way to set that string to empty. Can I somehow skip form validation for fields, that only have color in self.chagned_data or something like this? I would like the other edits to be saved. The model: class Unit(models.Model): name = models.CharField("name", max_length=128, blank=True, null=True) date = models.DateField() stock = models.ForeignKey(Stock, on_delete=models.CASCADE) label = models.CharField("extra label", max_length=32, null=True, blank=True) color = models.CharField(max_length=7, null=True, blank=True) -
UnicodeEncodeError at api
enter image description here I cannot insert data into this api and because of this 'ascii' codec can't encode characters in position 231-232: ordinal not in range(128) enter image description here I want a solution to fix this issue. I'm using django framework. The same database is working on localhost of my local computer but at server I can't insert data. I've cloned the server database too but it work at local computer but send error at server database. -
What should I do if data is not saved in Django?
I'm new to Django. And I'm faced with the problem of saving data from the form to the database. I was writing code in PyCharm. The main problem is that the data is not saved in the database. There are no errors, no warnings, NOTHING. Everything works except saving. I will be very grateful for your help! Here is the code: views.py: `from django.shortcuts import render, redirect from .models import Articles from .forms import ArticlesForm def news_home(request): news = Articles.objects.order_by('title') return render(request, 'news/news_home.html', {'news': news}) def create(request): error = '' if request.method == 'POST': form = ArticlesForm(request.POST) if form.is_valid(): article = form.save() return redirect('news_home') else: error = 'Unfortunately, the form was not filled out correctly.' form = ArticlesForm() data = { 'form': form, 'error': error } return render(request, 'news/create.html', data)` models.py: `from django.db import models class Articles(models.Model): title = models.CharField('name', max_length=50) anons = models.CharField('anons', max_length=250) full_text = models.TextField('article') date = models.DateTimeField('Date of publication') def __str__(self): return self.title class Meta: verbose_name = 'news' verbose_name_plural = 'news'` forms.py: `from .models import Articles from django.forms import ModelForm, TextInput, DateTimeInput, Textarea class ArticlesForm(ModelForm): class Meta: model = Articles fields = ['title', 'anons', 'full_text', 'date'] widgets = { "title": TextInput(attrs={ 'class': 'form-control', 'placeholder': 'the name … -
How to save the child set instance in the parent object in Django's Many to One (Foreign Key) relationship?
I am working on a social media project where users can follow each other. Here are the models that are relevant to this problem django.contrib.auth.models.User class UsersProfiles(ddm.Model): user = ddm.OneToOneField( dcam.User, on_delete=ddm.CASCADE, related_name="profile", ) followers_count = ddm.IntegerField(default=0) followings_count = ddm.IntegerField(default=0) class UsersFollows(ddm.Model): follower = ddm.ForeignKey( dcam.User, on_delete=ddm.CASCADE, related_name="followers", ) following = ddm.ForeignKey( dcam.User, on_delete=ddm.CASCADE, related_name="followings", ) I am creating data redundancy for scalability by storing the followers and followings counts instead of calculating it by using UsersFollows model. So I am using Django's transaction to add a follower for atomicity. with ddt.atomic(): umuf.UsersFollows.objects.create( follower=user, following=followed_user, ) followed_user.profile.followers_count += 1 user.profile.followings_count += 1 followed_user.profile.save() user.profile.save() But during the testing, the user to its followers and followings set is appearing empty. def test_valid(self): response = self.client.post( c.urls.USERS_1_FOLLOWINGS, {"user": 2}, headers=h.generate_headers(self.login_response), ) h.assertEqualResponses(response, c.responses.SUCCESS) user1 = dcam.User.objects.get(pk=1) user2 = dcam.User.objects.get(pk=2) self.assertEqual(user1.profile.followings_count, 1) self.assertEqual(user2.profile.followers_count, 1) follow = umuf.UsersFollows.objects.filter( follower=user1, following=user2, ) self.assertEqual(len(follow), 1) # Below 2 assertions are failing self.assertIn(user1, user2.followers.all()) self.assertIn(user2, user1.followings.all()) I tried saving both the User instances. I also tried saving the UserFollow instance just in case the create function did not save it automatically. umuf.UsersFollows.objects.create( follower=user, following=followed_user, ).save() user.save() followed_user.save() I don't get what am I missing here. -
issue is sending data from backend to frontend in django cannels AsyncWebsocketConsumer
so, th eproblem is simple there is a mistake in receive method which i am unable to find , the problem is that i am successfully getting data from frontend but unable to send data back from server to frontend/client, i just want to send data from backend to frintend -
django model.py file remain unchanged
my django project tree image models.py source file sqlite3 db table image sorry about unskilled writing I want django migration to update sqlite3 db tables, so I make models.py with that codes (second image) but If I type python manage.py makemigrations, it prints "No change detected" and If I type python manage.py migrate, my models.py codes doesn't work like third image(tables doesn't change) p.s django installed in venv move models.py file to sub directory -> doesn't work either -
Manual Django form not saving no matter what I do to Postgres database
I have a problem with saving a form to the database. Everything I've tried doesn't work and I really don't know what else to do. I have a manual form created in Django, I get absolutely no errors on save, everything works fine without any errors, I even get redirected to the success page, and yet I have absolutely nothing in the database. # models.py class Lead(Model): lead_status = CharField(choices=STATUS, default='Activă', verbose_name='Status cerere') property_type = CharField(choices=TIP_PROPRIETATE, default='Apartament', verbose_name='Tip cerere') transaction_type = CharField(choices=TIP_TRANZACTIE, verbose_name='Tip tranzacție') contact = ForeignKey(Contact, on_delete=SET_NULL, null=True, verbose_name='Contact asociat') county = CharField(choices=JUDETE, verbose_name='Județ') city = CharField(max_length=30, verbose_name='Localitate') zone = CharField(max_length=30, null=True, blank=True, verbose_name='Zonă') street = CharField(max_length=40, null=True, blank=True, verbose_name='Stradă') budget = IntegerField(null=True, blank=True, verbose_name='Buget alocat') payment_method = CharField(choices=MODALITATE_PLATA, null=True, blank=True, verbose_name='Modalitate plată', ) urgency = CharField(choices=URGENTA, default='Normal', verbose_name='Urgență') other_details = TextField(max_length=2000, null=True, blank=True, verbose_name='Alte detalii') labels = CharField(choices=ETICHETA, null=True, blank=True, verbose_name='Etichete') notes = TextField(max_length=2000, null=True, blank=True, verbose_name='Notițe proprii') created_at = DateTimeField(auto_now_add=True, verbose_name='Data introducerii') updated_at = DateTimeField(auto_now=True, verbose_name='Data ultimei actualizări') deadline_date = DateField(null=True, blank=True, verbose_name='Data limită') deadline_time = TimeField(null=True, blank=True, verbose_name='Ora limită') class Meta: abstract = True def __str__(self): return f'{self.contact}' class ApartmentLead(Lead): apartment_type = CharField(choices=TIP_APARTAMENT, verbose_name='Tip apartament') destination = CharField(choices=DESTINATIE_AP, verbose_name='Destinație') rooms_number = IntegerField(null=True, blank=True, verbose_name='Număr camere') nr_bedrooms … -
How can I get my crispy form to work in Django in the login process?
I would like to customize my login page using crispy by using placeholders in the text fields instead of labels. I can't log in with the crispy form tag and the design is also different to what I want but with the crispy filter I can log in but I don't know how to design the template according to my wishes. That's my code so far: views.py: from django.http import HttpResponse from django.shortcuts import render, redirect from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from django.contrib import messages from .forms import UserRegisterForm, UserIndexForm #The webpage where you can login. def login(request): return render(request, 'loginprofile/login.html') forms.py: from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import AuthenticationForm from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Fieldset, Submit, HTML, Field # UserIndexForm class UserIndexForm(AuthenticationForm): def __init__(self, *args, **kwargs): super(UserIndexForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_show_labels = False self.helper.form_show_errors = True self.helper.error_text_inline = False self.helper.help_text_inline = True self.helper.form_tag = False self.helper.form_method = 'POST' self.helper.form_action = 'submit_survey' self.fields['username'].help_text = None self.fields['password'].help_text = None self.helper.layout = Layout( Field('username', placeholder='Username'), Field('password', placeholder='Password'), ) self.helper.add_input(Submit('submit', 'Sign In', css_class='container btn-success justify-content-center')) class Meta: model = User fields = ['username', 'password'] widgets = { 'username': forms.TextInput(attrs={'class': 'form-control mb-0', … -
how can i show the terminal output and matplotlib graphic on django web
I got no clue how to do it. this is my py code # Gerekli kütüphanelerin yüklenmesi import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier, AdaBoostClassifier from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score # Iris veri setini yükleme iris = load_iris() X = iris.data y = iris.target # Veri setini görselleştirme plt.figure(figsize=(10, 6)) plt.scatter(X[:, 0], X[:, 1], c=y, cmap='viridis') plt.xlabel('Sepal Length') plt.ylabel('Sepal Width') plt.title('Iris Veri Seti') plt.colorbar(label='Class') plt.show() # Veri setini eğitim ve test setlerine ayırma X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) this is the matplotlib output this is the output of the terminal -
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'tools.User' that has not been installed
I want to replace the original User of django with my own User, but the following error occurred there is my settings.py,I mainly addedAUTH_USER_MODEL = 'tools.User' from datetime import timedelta from pathlib import Path import django DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'channels', "daphne", 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework_simplejwt', 'corsheaders', 'campus_services', 'edu_admin', 'interaction', 'tools', ] AUTH_USER_MODEL = 'tools.User' # Application definition MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'backend.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'backend.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '', 'USER': '', 'PASSWORD': '', 'HOST': '', } } # Password validation # https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/4.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.2/howto/static-files/ STATIC_URL = 'static/' # Default primary key field type # https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } SIMPLE_JWT = { … -
Django DRF_Spectacular and dynamic serializer problem
i have a 2 serializers when i get the list of ItemCategory i want have all fields so ItemCategorySerializer is enough but when i call ItemCategorySerializer from ItemSerializer i want print only id and name but when i generate the swagger schema inside my schema list i find ItemCategory with only 'id', 'name' class ItemCategorySerializer(coreSerializers.DynamicModelSerializer): class Meta: model = ItemCategory fields = "__all__" class ItemSerializer(coreSerializers.DynamicModelSerializer,): class Meta: model = Item fields = "__all__" category_obj = ItemCategorySerializer(source='category', many=False, read_only=True, required=False, allow_null=True, partial=True, fields=['id', 'name', ]) so, i have this inside swagger this schema but i want that i think that happen because before it generate ItemCategory full then ItemSerializer call ItemCategorySerializer and replace ItemCategory full with minimized: how i can force to use in schema model ItemCategory full ? -
Model Message at migration in django
My Model is like below. from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ('O', 'Other'), ) USER_TYPE = ( ('S', 'Super Admin'), ('A', 'Admin'), ('P', 'Patient'), ('D', 'Doctor'), ('U', 'User'), ) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) date_of_birth = models.DateField() gender = models.CharField(max_length=1, choices=GENDER_CHOICES) user_type = models.CharField(max_length=1, choices=USER_TYPE) email = models.EmailField(unique=True) phone = models.CharField(max_length=15, blank=True, null=True) address = models.TextField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return f"{self.first_name} {self.last_name}" I am getting message like below. It is impossible to add a non-nullable field 'password' to user without specifying a default. This is because the database needs something to populate existing rows. Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit and manually define a default value in models.py. -
ViewSet method create never validates nested model
I'm learning WebSockets [django channels] to use along with DRF. I have created simple HTML form to create Comment. The form contains some User data so everyone can post a comment and the data entered is being used to create a new User (posting comment not requiring any authentication at all). Everything works fine when sending POST request from DRF Browsable API. However doesn't work when sending data from HTML form : returns error "user": ["This field is required."] Models: class Comment(MPTTModel): """ The base model represents comment object in db. """ user = models.ForeignKey(CustomUser, related_name="comments", on_delete=models.CASCADE) date_created = models.DateTimeField( verbose_name="Created at", auto_now_add=True, blank=True, null=True ) text = models.TextField(max_length=500) class CustomUser(AbstractBaseUser, PermissionsMixin): """Custom User model extends a pre-defined django AbstractUser model.""" uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField(verbose_name="email address", max_length=255, unique=True) username = models.CharField(max_length=64, unique=True) avatar = ResizedImageField( force_format="WEBP", crop=["middle", "center"], upload_to=profile_avatar_path, blank=True, null=True, max_length=500, storage=OverwriteStorage() ) homepage = models.URLField(max_length=255, null=True, blank=True) enter code here ViewSet: class CommentViewSet(ModelViewSet): """ Comment Viewset to handle base model operations. """ queryset = Comment.objects.filter(level=0) serializer_class = CommentSerializer def create(self, request, *args, **kwargs): user_data = {} for field, value in request.data.items(): if field.startswith("user"): user_data.update({field.split("-")[1]: value}) request.data._mutable = True request.data["user"] = user_data request.data._mutable = False … -
How to use variable to iterate in django template?
I'm using python and django and I would like to use a variable I entered in a previous input, to iterate over creating multiple other input fields. This is the part in the Django template where I ask the number I would like to use in the iteration: <form method="GET"> <label for="grondstoffen_count" style="font-family: Oswald, sans-serif;">Give how many products were delivered:</label> <input type="number" name="grondstoffen_count" id="grondstoffen_count" min="0" required> <button type="submit" name="submit_count">Bevestig</button> </form> This is the part my views.py where I generate a string of the sequence up to the input number. When I have the string I return it to the Django template: elif 'submit_count' in self.request.GET: grondstoffen_count = int(self.request.GET.get('grondstoffen_count', 0)) volgordelijst = "" for i in range(1, grondstoffen_count + 1): volgordelijst += str(i) print(type(volgordelijst)) # string print(volgordelijst) # when grondstoffen_count is 5 then this gives "12345" return render(self.request, 'Ano_app/BehandelNieuweVoorraad.html', {'volgordelijst': volgordelijst}) In the template I receive the 'volgordelijst' (so I don't think it's a problem with giving the variable from the view to the template because the name is automatically suggested) and I would like to use that variable for the loop. I would like to have as many input fields as the number in the original input but when I … -
add and view cart with django session
def add_cart(request, pk): produit = Produit.objects.get(id=pk) quantity = int(request.POST.get('quantity', 1)) # Get the quantity from the form cart = request.session.get('cart', []) if quantity > produit.quantitéP: messages.error(request, "La quantité dépasse le stock!!") return redirect(reverse('details-produit', args=[produit.id])) # Append the product and its quantity to the cart as a dictionary cart.append({'produit_id': produit.id, 'quantity': quantity}) request.session['cart'] = cart messages.success(request, "Produit ajouté au panier avec succès ") return redirect('cart') def view_cart(request): cart = request.session.get('cart', []) produits_in_cart = [] for item in cart: produit_id = item.get('produit_id') quantity = item.get('quantity') try: produit = Produit.objects.get(id=produit_id) produits_in_cart.append((produit, quantity)) except Produit.DoesNotExist: pass return render(request, 'app1/cart.html', {'produits_in_cart': produits_in_cart}) I'm trying to add a product and his quantity into a cart after that i wanted tho show all the products with their quantity in a cart template but i'm getting and (AttributeError at /cart 'int' object has no attribute 'get') Error here's my views : -
It does not change the data in database but it shows the new data in developer tools
It does not change the data in database but it shows the new data in developer tools It suppose to change it but it didn't can anybody whos using vue js help been stuck in this problem for quite some time now already tried this, this code shows the new inputted data but does not change the data in database asdasdasdasdasdasdasdasdasdsadasdasdasdasdasdasdasdasdasasdasasdasdasdasdasdasdasdasd <template> <div class="modal fade" id="editRolesModal" tabindex="-1" aria-labelledby="editRolesModalLabel" aria-modal="true"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="modal-header bg-soft-success" style="padding: 20px;"> <h5 class="modal-title">Edit Role</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <form @submit.prevent="updateRole"> <input type="hidden" v-model="roleId"> <div class="mb-3"> <label for="role-name-edit" class="form-label">Role Name</label> <input type="text" class="form-control" id="role-name-edit" v-model="roleName" required> </div> <div class="mb-3"> <label for="description-edit" class="form-label">Description</label> <input type="text" class="form-control" id="description-edit" v-model="description" required> </div> <button type="submit" class="btn btn-success btn-block">Update</button> </form> </div> </div> </div> </div> </template> <script> import axios from 'axios'; export default { props: ['selectedRoleId'], data() { return { roleId: '', roleName: '', description: '' }; }, watch: { selectedRoleId(newVal) { if (newVal) { this.fetchRole(newVal); } } }, methods: { fetchRole(selectedRoleId) { axios.get(`/api/roles/${selectedRoleId}`) .then(response => { const roleDetails = response.data; this.roleName = roleDetails.role_name; this.description = roleDetails.description; }) .catch(error => { console.error('Error fetching role:', error); }); }, updateRole() { axios.put(`/api/roles/${this.selectedRoleId}`, { role_name: this.roleName, description: this.description … -
DoesNotExist at /up_emp/31/
DoesNotExist at /up_emp/31/ Employee matching query does not exist. Request Method:POSTRequest URL:http://127.0.0.1:8000/up_emp/31/Django Version:5.0.6 Exception Type:DoesNotExistException Value:Employee matching query does not exist. While I was implementing CRUD operations in Django, I encountered some errors during the update process. Could you please analyze the code provided below and guide me on how to resolve these errors? update.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Add employee</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet"> <style> body { background-color: #222021; font-family: sans-serif; margin: 0; padding: 0; height: 100vh; display: flex; flex-direction: column; justify-content: center; align-items: center; } .card { border-radius: 10px; box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1); } .form-control { border-radius: 5px; box-shadow: none; border: 1px solid #ccc; } .btn-primary { background-color: #3498db; border-color: #3498db; } .btn-primary:hover { background-color: Blue; } .btn-back-home { color: red; background-color: yellow; border: none; border-radius: 5px; padding: 10px 20px; text-decoration: none; } .btn-back-home:hover { background-color: yellow; text-decoration: none; } #A,#B,#C,#D,#E,#F,#G,#H,#I { font-weight: bold; } </style> </head> <body> <div class="container"> <div class="row justify-content-center align-items-center"> <div class="col-sm-8 col-md-6 col-lg-5 card shadow-lg px-4 py-5"> <h2 class="text-center mb-4">Update Employee</h2> <form action="/up_emp/{{emp.id}}/" method="POST"> {% csrf_token %} <div class="form-group" id="A"> <label for="fname">Full name</label> <input type="text" class="form-control" id="fname" name="fname" placeholder="Enter first name" value="{{emp.name}}"> </div> … -
How to use Discord Oauth2 with Allauth?
I've been working on a social media clone of mine for a few days and I now think that having discord as a method to signup and login would be really cool. How can I integrate it using only Allauth? I tried reading their docs but there wasn't anything that could help me that much. I also tried setting up SOCIALACCOUNT_PROVIDERS and allauth.socialaccount.providers allauth.socialaccount.providers.discord but nothing worked. Thank you very much! -
how to importing python class in django case
why we import like this. from django.db.models import Model, Model class is inside base.py not models. expecting from django.db.models.base import Model, why base module ommitted. django/db/models/base.py is the structure -
How to deploy Django Webapp with subdomain
I have a domain as abc.com. I have created subdomain as xyz.abc.com. I have two Django Webapps both are not same. I want to deploy both Django Webapps with this domain and sub-domain on same VPS server. Webapp deployed on main domain works very well. But when I try to do same thing with wepapp and sub-domain it shows error as Not Found. I am using apache2 server to deploy webapp. Here is my apache configuration. <VirtualHost *:80> ServerAdmin webmaster@localhost ServerName xyz.abc.com ServerAlias www.xyz.abc.com DocumentRoot /home/altaf/LinkSuggestion/LinkSuggestion Alias /static /home/altaf/LinkSuggestion/LinkSuggestion/static <Directory /home/altaf/LinkSuggestion/LinkSuggestion/static> Require all granted </Directory> <Directory /home/altaf/LinkSuggestion/LinkSuggestion/LinkSuggestion> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess linksuggestion python-path=/home/altaf/LinkSuggestion/LinkSuggestion python-home=/home/altaf/LinkSuggestion/envlinksuggestion WSGIProcessGroup linksuggestion WSGIScriptAlias / /home/altaf/LinkSuggestion/LinkSuggestion/LinkSuggestion/wsgi.py ErrorLog ${APACHE_LOG_DIR}/linksuggestion_error.log CustomLog ${APACHE_LOG_DIR}/linksuggestion_access.log combined </VirtualHost> It shows error as : **Not Found** The requested resource was not found on this server. -
Why won't my home page redirect to a detail view (Django)
So the context is I'm following a tutorial on codemy.com. Somewhere before Django 5.0 I lost my "magic", the tutorial was written for 3.8 or 4.X maybe. I am showing a function based view although I have tried the class base view as suggested on the codemy youtube. The reason I chose function view is it was easier for me to debug. views.py from django.shortcuts import render from django.views.generic import ListView #DetailView from django.http import HttpResponse from .models import Post class Home(ListView): model = Post template_name = "home.html" def articleDetail(request, pk): try: obj = Post.objects.get(pk=pk) return render(request, "article_detail.html", {object, obj}) except Post.DoesNotExist: print("Object number: " + str(pk) + " not found") return HttpResponse("Object number: " + str(pk) + " not found") the model from django.db import models from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() def __str__(self): return str(self.title) + ' by: ' + str(self.author) the urls file from django.urls import path,include from .views import Home, articleDetail urlpatterns = [ path('', Home.as_view(), name="home"), path('article/<int:pk>', articleDetail,name="article-detail"), ] the template for home, works fine until redirect <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Landing!!!</title> <h1> Home Pageeeeee</h1> </head> <body> <ul> <h2>Articles</h2> {% for article … -
Djang rest frame-work error : django.core.exceptions.ImproperlyConfigured: Router with basename X is already registered , despite it is not
In my django app am using DRF and it gives me , and it gives me this strange error when i try to run the app : water_maps | router.register(r'breaches_edit_delete', api.BreacEditDeletehViewSet) water_maps | File "/usr/local/lib/python3.10/dist-packages/rest_framework/routers.py", line 59, in register water_maps | raise ImproperlyConfigured(msg) water_maps | django.core.exceptions.ImproperlyConfigured: Router with basename "breach" is already registered. Please provide a unique basename for viewset "<class 'water_maps_dashboard.api.BreacEditDeletehViewSet'>" despite there is no duplication and the routers ,, here is my URLS file : from django.urls import path, include from rest_framework import routers from . import api from . import views from .api import check_current_version, check_for_device_id, check_for_login, get_cords_ids router = routers.DefaultRouter() router.register("main_depart", api.MainDepartmentViewSet) router.register("job_description", api.JobDescriptionViewSet) # router.register("section", api.SectionViewSet) router.register("city", api.CityViewSet) router.register("AppUser", api.AppUserViewSet) router.register("Breach", api.BreachViewSet) router.register("Section", api.SectionViewSet) router.register("MapLayers", api.MapLayersViewSet) router.register("LayersCategory", api.LayersCategoryViewSet) router.register("UserMessage", api.UserMessageViewSet) router.register("about_us", api.AboutUsViewSet) # router.register(r'breaches_edit_delete', api.BreacEditDeletehViewSet) router.register(r'edit_delete_breach', api.BreacEditDeletehViewSet) urlpatterns = ( path("api/do_search/", api.do_search, name="do_search"), path("api/activate_account/", api.activate_account, name="activate_account"), path("api/user_login/", api.user_login, name="user_login"), path("api/create_app_user/", api.create_app_user, name="create_app_user"), path("api/save_breaches/", api.save_breaches, name="save_breaches"), path("api/add_cords_to_breach/", api.add_cords_to_breach, name="add_cords_to_breach"), path("api/do_forgot_password/", api.do_forgot_password, name="do_forgot_password"), path("api/reset_password/", api.reset_password, name="reset_password"), path("api/get_my_breaches/", api.get_my_breaches, name="get_my_breaches"), path("api/map_view/", api.map_view, name="map_view"), path("api/post_user_message/", api.post_user_message, name="post_user_message"), path("api/add_edit_request/", api.add_edit_request, name="add_edit_request"), path("api/request_delete_account/", api.request_delete_account, name="request_delete_account"), path("api/", include(router.urls)), path("api/check_for_login/", check_for_login, name="check_for_login"), path("api/check_for_device_id/", check_for_device_id, name="check_for_device_id"), path("api/check_current_version/", check_current_version, name="check_current_version"), path("api/get_cords_ids/", get_cords_ids, name="get_cords_ids"), path("upload_data/", views.upload_data, name="upload_data"), path("admin_logs/", views.admin_logs, name="admin_logs"), path("trigger_task/", views.admin_logs, name="trigger_task"), path("send_email/", views.send_email_to_users, name="send_email"), … -
composite primary key django and timescaledb (postgresql)
I am using django for my backend and postgresql for my database cause I have timeseries data i use timescaledb. i have hypertable called devices. there is a composite primary key on fields created_datetime(timestamp) and device_id(integer). I want to use django built in logging users activities ( LogEntry table), so i should have a model representing the hyper table . how can I do this? I have tried so many things like creating a model putting created_datetime as primarykey then in adminsite i had error ID “2024-05-06 11:55:21” doesn’t exist. Perhaps it was deleted? -
how to integrate QR code payment in django
I am facing the issue to integrate QR code in python django website but not getting proper solution Please help me that how can i integrate the QR code payment gateway in django. and what will be the payment method best for this? -
Django products not being added to cart immediately
So I am trying to build a Django e-commerce website, where there is a cart modal which pops up when I try to add any product by clicking the add to cart button. While the product is being added correctly in the backend (which I can verify by going to admin panel), the product just doesn't show up immediately on my cart modal, something which is essential for the website to look good. Only when I am refreshing the page, the product shows up on my modal. Been stuck on this for the last 3 days, no clue what to do. Can someone please help me out here? Thanks! My cart model: class Cart(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='cart') product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.user.username} - {self.product.name}" My views.py: class CartView(LoginRequiredMixin, View): def get(self, request): cart_items = Cart.objects.filter(user=request.user) total_price = sum(item.product.price * item.quantity for item in cart_items) return render(request, 'business/cart.html', {'cart_items': cart_items, 'total_price': total_price}) def post(self, request): try: data = json.loads(request.body) product_id = data.get('product_id') except json.JSONDecodeError: logger.error("Invalid JSON data in the request body") return JsonResponse({'error': 'Invalid JSON data'}, status=400) logger.debug(f'Received product_id: {product_id}') if not product_id: logger.error("No product_id provided in …