Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Admin Two screen are overlapping
enter image description hereplease help me out with such a problem what to do so that I get my normal admin interface? I had upgrade my Django version from 2.2 to 4.1.7 and now I am facing such an annoying issue at admin. please help me out. -
'home' is not a registered namespace Django
I want to create an a way that you can get the product information by licking on a product and then loading that information into 1 html file, I looked up a couple of tutorials up and they al says this code works, but for me it gives me an error named "'home' is not a registered namespace Django" does anyone know how to fix this? views.py (home app directory from django.shortcuts import render from django.http import HttpResponse from .models import albums from django.views.generic import ListView, DetailView def album(request): return render(request, 'home/album.html') def artists(request): return render(request, 'home/artists.html') class homeview(ListView): model = albums template_name = "home/home.html" class albuminfo(DetailView): model = albums template_name = "home/AlbumInfo.html" models.py class albums(models.Model): title = models.CharField(max_length=100) description = models.TextField() release_date = models.CharField(max_length=10) artist = models.CharField(max_length=100) genre = models.CharField(choices=GENRE_CHOICES, max_length=20) image = models.ImageField(default='default2.jpg', upload_to='album_pics') slug = models.SlugField() def __str__(self): return self.title def get_absolute_url(self): return reverse("home:AlbumInfo", kwargs={ 'slug': self.slug }) urls.py from . import views urlpatterns = [ path('', views.homeview.as_view(), name='home'), path('albums/', views.album, name='Nartonmusic-album'), path('artists/', views.artists, name='Nartonmusic-artists'), path('albuminfo/<slug>/', views.albuminfo.as_view(), name='AlbumInfo') ] home.html {% extends 'home/base.html' %} {%block content%} {% for album in object_list %} <li><a href="{{album.get_absolute_url}}">{{ album.title}} </a></li> {% endfor %} {%endblock%} can somebody help my out? -
I'm testing my 'UPDATE' on postman and ended getting runtime error - RuntimeError at /blog/2
I'm trying PUT (Update/Edit) on postman. i attached the view , url code file. The goal is to test the code in postman to see if the update is working. I am testing it using PUT request with localhost/id. The test should provide me update of the Id and get back with updated file. For example if i update the author name from Dr.xyz to Dr.abc i should get Dr.abc since it is the updated one. view.py file from django.shortcuts import render from django.http import HttpResponse from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from .models import Blog from .serializers import BlogSerializer from django.shortcuts import get_object_or_404 class BlogView(APIView): #Index-Get def get(self, request): print(request) Blog = Blog.objects.all() data = BlogSerializer(blogs, many=True).data return Response(data) #Post def post(self, request): print(request.data) blog = BlogSerializer(data=request.data) if blog.is_valid(): blog.save() return Response(blog.data, status=status.HTTP_201_CREATED) else: return Response(blog.errors, status=status.HTTP_400_BAD_REQUEST) class BlogDetail(APIView): #Show def get(self, request, pk): blog = get_object_or_404(Blog, pk=pk) data = BlogSerializer(blog).data return Response(data) #Update def put(self, request, pk): print(request) blog = get_object_or_404(Blog, pk=pk) updated_blog = BlogSerializer(blog, data=request.data) if updated_blog.is_valid(): updated_blog.save() return Response(updated_blog.data) else: return Response(updated_blog.errors, status=status.HTTP_400_BAD_REQUEST) #Delete def delete(self, request, pk): blog = get_object_or_404(Blog, pk=pk) blog.delete() return Response(status=status.HTTP_204_NO_CONTENT) def index(request): return HttpResponse('<h1> Welcome … -
Django - How to implement customer balance calculation using property
Sorry for the long post. This is my first time posting here. I am building a project to manage customer orders of a store. The code is working fine but I would like to know if it is possible to improve it using what I mentioned in the title. And if yes, how to do it? The store employee will login and do operations like: Create new customers Create new products Enter customers orders. The customer model has a decimal field called balance. Each time an order is placed for a customer, the order total cost is deducted from the customer balance. There is a Recharge functionality which increases the customer balance using signal. My question is how to implement customer balance calculation using property. Code: class Customer(models.Model): name = models.CharField(max_length=50, db_index=True) email = models.EmailField(max_length=50, unique=True) address = models.CharField(max_length=150, null=True, blank=True) balance = models.DecimalField(default=0, max_digits=5, decimal_places=2) starting_balance = models.DecimalField(default=0, max_digits=5, decimal_places=2) created_date = models.DateField(auto_now_add=True) updated_date = models.DateField(auto_now=True) class Meta: ordering = ('name',) def get_absolute_url(self): return reverse('customers:customer_detail', args=[self.id]) def __str__(self): return self.name class Recharge(models.Model): customer = models.ForeignKey(Customer, related_name='recharges', on_delete=models.CASCADE) amount = models.DecimalField(max_digits=5, decimal_places=2) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.customer.name} recharged for {self.amount}' class Order(models.Model): """ Order model. """ customer = … -
How to avoid duplicate image path in Django Create Method?
I'm currently making a loop that duplicates X times a post. The problem here is in the ImageField, all is working but the image path that is going to be set in the new duplicate post, has the same path. So if you delete the original post, the duplicates will lose their image too... this is the code that duplicates de post: while counter < recurrence_posting: event_loop = Post.objects.create(title=form.instance.title, thumb=form.instance.thumb) counter += 1 day_counter += 1 get_spot = get_object_or_404(Spot, id=event_loop.id) get_spot.save() How to avoid this? -
Django form POST request issue
I am trying to create an option menu input field which takes input from a POST request. My python code calls the database using a variable with the same value as the input field. Where the name is the value of the input field. I am having issues getting the data back to the Django application, I am also having trouble seeing the output in the VS code terminal and the browser console. views.py from django.shortcuts import render from django.shortcuts import get_object_or_404 from .models import Navbar, Hero from django.http import JsonResponse from core.forms import BuildForm def index(request): if request.method == 'POST': form = BuildForm(request.POST) if form.is_valid(): nav = form.cleaned_data['Nav'] hero = form.cleaned_data['Hero'] my_object = get_object_or_404(Navbar, id=nav) my_object2 = get_object_or_404(Hero, id=hero) return render(request, 'core/index.html', {'my_object': my_object}) else: form = BuildForm() return render(request, 'core/index.html', {'form': form}) forms.py from django import forms class BuildForm(forms.Form): Nav = forms.CharField(max_length=100) Hero = forms.CharField(max_length=100) index.html {% extends 'core/base.html' %} {% block title %}Welcome To Atom{% endblock %} {% block content %} <div class="choosepage"> <h1>Choose a page to view</h1> <form> {{ form.as_p }} <input type="submit" value="Submit"> </form> </div> {% endblock %} base.html <!DOCTYPE html> {% load static %} <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" … -
How to show fields from across different models in Django admin
I have a model that is coded so currently logged in Users who have registered can comment: class BlogComment(models.Model): post = models.ForeignKey(BlogPost, related_name="comments", on_delete=models.CASCADE) user = models.ForeignKey(User, editable=False, on_delete=models.CASCADE, default="") name = models.CharField('Name',max_length=100, default="") text = models.TextField('Comment',max_length=1000, default="") date = models.DateTimeField(auto_now_add=True) status = models.BooleanField(default=True) class Meta: ordering = ("date",) def __str__(self): return '%s -> %s'%(self.post.title, self.user) I want to be able to display their details for example, the user name here EDIT I would also like to know why their name isn't been automatically input: Likewise, I would also like to display the posts and comments in which the users have made, in the Users section inside Django Admin Here is my admin.py: @admin.register(BlogPost) class PostAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('title',)} list_display = ("title", "date", "published",) search_fields = ("title", "date", "published") list_filter = ("date", "published") @admin.register(BlogComment) class PostAdmin(admin.ModelAdmin): list_display = ("post", "name", "date", "status", "user") list_filter = ("date", "status") search_fields = ("name", "date", "status") -
How to map a django float form field that is not required to a django rest framework form serializer
In a Django 3.1.1 app that uses djangorestframework 3.11.1 and django-rest-framework-braces 0.3.4, I have the following form field in a Form class called SomeForm: value = FloatField( label='value of thing', required=False, ) I then set up a django rest framework form serializer using SomeForm with a mapping as follows: from django.forms import FloatField from rest_framework import fields from drf_braces.serializers.form_serializer import FormSerializer class BaseFormSerializer(FormSerializer): class Meta: form = SomeForm field_mapping = { FloatField: fields.FloatField, } However, when I submit a form using the restframework browseable API, I get a validation error: HTTP 400 Bad Request Allow: GET, POST Content-Type: application/json Vary: Accept { "value": [ "Enter a number." ] } This error does not occur in Django, however, and I get the value I'm expecting on blank (None - which should serialize to null) using the Django shell: In [4]: f.fields['value'].clean('') is None Out[4]: True Am I doing this correctly or is there a better way? -
Cannot login after a user activate account
Working on a django project, successfully done the registration, login, logout and activate views, the registration is working because a user get a link sent to their email after they signup but I'm having errors saying invalid credentials when I try to login with that created account, I could login with the admin account though. Here is the codes register view def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] phone_number = form.cleaned_data['phone_number'] email = form.cleaned_data['email'] password = form.cleaned_data['password'] username = email.split('@')[0] user = Account.objects.create_user(first_name=first_name, last_name=last_name, email=email, username=username, password=password) user.phone_number = phone_number user.save() # Create a user profile profile = UserProfile() profile.user_id = user.id profile.profile_picture = 'default/default.png' profile.save() #user activation current_site = get_current_site(request) mail_subject = "WElcome to ECO, Please activate your account" message = render_to_string('ecousers/account_verification_email.html', { 'user': user, 'domain':current_site, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': default_token_generator.make_token(user), }) to_email = email send_email = EmailMessage(mail_subject, message, to=[to_email]) send_email.send() # messages.success(request, "Account created successfully") return redirect('/accounts/login/?command=verification&email='+email) else: form = RegistrationForm() context = { 'form': form, } return render(request, 'ecousers/register.html', context) login and activate views def login(request): if request.method =="POST": email = request.POST['email'] password = request.POST['password'] user = auth.authenticate(email=email, password=password) if user is not None: auth.login(request, user) return redirect('/') … -
Why the images doesn't show on my website?
I dont know why django doesn't find my images When I go to my home page list images i want to see the images for user thumnbails and original But the html can't find this And maybe someone will know how can i show only fields what the user create not all users but the one user views.py def image_list(request): images = Image.objects.all() context = {'images': images} return render(request, 'imagelist.html', context) @login_required def add_image(request): if request.method == 'POST': form = ImageForm(request.POST, request.FILES) if form.is_valid(): profile = request.user.profile image = form.save(commit=False) image.user = profile image.save() return redirect('images') else: form = ImageForm() return render(request, 'add_image.html', {'form': form}) models.py class Profile(models.Model): TIERS = ( ('basic', 'Basic'), ('premium', 'Premium'), ('enterprise', 'Enterprise'), ) user = models.OneToOneField(User, on_delete=models.CASCADE) tier = models.CharField(max_length=10, choices=TIERS, default='basic', blank=True, null=True) class Image(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE) image = models.ImageField(upload_to='images/', null=True, blank=True) thumbnail_200 = models.ImageField(upload_to='images/thumbnails/200/', null=True, blank=True) thumbnail_400 = models.ImageField(upload_to='images/thumbnails/400/', null=True, blank=True) def save(self, *args, **kwargs): # Create appropriate thumbnails for the user's tier if self.image and not self.thumbnail_200: self.create_thumbnail_200() if self.image and not self.thumbnail_400 and self.user.tier in ['premium', 'enterprise']: self.create_thumbnail_400() super().save(*args, **kwargs) def create_thumbnail_200(self): im = PILImage.open(self.image) output_size = (200, 200) im.thumbnail(output_size) thumbnail_io = BytesIO() im.save(thumbnail_io, 'JPEG', quality=85) thumbnail_io.seek(0) self.thumbnail_200.save(self.image.name, ContentFile(thumbnail_io.read()), … -
How to parse _history_user_id from django-simple-history into an html table?
I'm currently using djanog-simple-history to track which user made the most recent change to a model. This is working as expected as it shows me on the UI who the most recent user is. I'm acheving this by using the middleware simple_history.middleware.HistoryRequestMiddleware. I have created a report (html table) that will grab certain datapoints from different models and be used as a hub to track all the changes made by certain users. Trying to track the history user is the last key to all of this. Model: class Degree(TimeStampedModel): user = ForeignKey(User, null=True, blank=True, related_name='degrees', on_delete=CASCADE) level = CharField(max_length=50, null=True, blank=True, choices=LEVELS) institution = CharField(max_length=255, null=True) major = CharField(max_length=255, null=True, blank=True) minor = CharField(max_length=255, null=True, blank=True) verified_date = DateField(null=True, blank=True) graduation_date = DateField(null=True, blank=True) reason_for_change = CharField(max_length=255, null=True) history = HistoricalRecords(User) Report: def Changelog_table(request): name = 'Changelog' desc = 'changelog' headers = [ ('', ''), ('user__last_name', 'Last name'), ('user__first_name', 'First name'), ('reason_for_change', 'Reason for change'), ('section', 'section'), ('modified', 'modified'), ('user', 'user') ] filters = { 'user__is_active': True, } values = [ 'user__username', 'user__last_name', 'user__first_name', 'reason_for_change', 'section', 'modified', 'user', ] qs_degree = ( Degree.objects.filter(**filters) \ .values_list(*values) ) return render(request, 'reports/report.html', { 'headers': headers, 'data': json.dumps(list(qs_degree)), cls=DjangoJSONEncoder), 'name': name, 'desc': desc, }) … -
Django Rest Framework - invalid credentials
I'm working on web app where you can register and login via Postman. Register is working fine. Here is serializer.py from rest_framework import serializers from django.contrib.auth.models import User from rest_framework_simplejwt.tokens import RefreshToken from django.contrib.auth import authenticate class RegisterSerializer(serializers.Serializer): first_name = serializers.CharField() last_name = serializers.CharField() username = serializers.CharField() password = serializers.CharField() def validate(self, data): if User.objects.filter(username=data["username"]).exists(): raise serializers.ValidationError("username is already taken") return data def create(self, validated_data): user = User.objects.create(first_name=validated_data["first_name"], last_name=validated_data["last_name"], username=validated_data["username"].lower() ) user.set_password(validated_data["password"]) return validated_data class LoginSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, data): if not User.objects.filter(username=data["username"]).exists(): raise serializers.ValidationError("account not found") return data def get_jwt_token(self, data): user = authenticate(username=data["username"], password=data["password"]) if not user: return {"message": "invalid credentials", "data": {}} refresh = RefreshToken.for_user(user) return { "message": "login success", "data": {"token": {"refresh": str(refresh), "access": str(refresh.access_token)}}} Here is views.py from rest_framework.views import APIView from rest_framework.response import Response from .serializer import RegisterSerializer, LoginSerializer from rest_framework import status class RegisterView(APIView): def post(self, request): try: data = request.data serializer = RegisterSerializer(data=data) if not serializer.is_valid(): return Response ({ "data" : serializer.errors, "message" : "something went wrong", }, status=status.HTTP_400_BAD_REQUEST) serializer.save() return Response({ "data" : {}, "message" : "user created successfully", }, status=status.HTTP_201_CREATED) except Exception as e: print(e) return Response({ "data" : {}, "message" : "something went wrong", … -
I want to store langitude and latitude of adress given by user i done all my configurations but did not understand why this error happen help me?
enter image description here windows I want to store langitude and latitude of adress given by user i done all my configurations but did not understand why this error happen help me? my settings.py file VIRTUAL_ENV_BASE = os.environ.get('VIRTUAL_ENV') print(VIRTUAL_ENV_BASE) GEOS_LIBRARY_PATH = VIRTUAL_ENV_BASE + '/Lib/site-packages/osgeo/geos_c.dll' GDAL_LIBRARY_PATH = VIRTUAL_ENV_BASE + '/Lib/site-packages/osgeo/gdal304.dll' My model.py file `from datetime import * import geocoder import os from django.db import models from django.core.validators import MaxValueValidator, MinValueValidator from django.contrib.gis.db import models as gismodels from django.contrib.gis.geos import Point from django.contrib.auth.models import User class Job(models.Model): title = models.CharField(max_length=200, null=True) description = models.TextField(null=True) email = models.EmailField(null=True) address = models.CharField(max_length=200, null=True) salary = models.IntegerField(default=1) positions = models.IntegerField(default=1) company = models.CharField(max_length=100, null=True) point = gismodels.PointField(default=Point(0.0,0.0)) last_date = models.DateTimeField(default=return_Date_time) created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) date_created = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) def save(self, *args, **kwargs): g = geocoder.mapquest(self.address, key=os.environ.get('GEOCODER_API')) print(g) lng = g.lng lat = g.lat self.point = Point(lng, lat) # Call the parent class's save method to actually save the object super(Job, self).save(*args, **kwargs)` [22/Feb/2023 22:51:32] "POST /admin/jobapp/jo`your text`b/add/ HTTP/1.1" 500 160565 GDAL_ERROR 1: b'PROJ: proj_create_from_database: Cannot find proj.db' GDAL_ERROR 1: b'PROJ: proj_create_from_database: Cannot find proj.db' Error transforming geometry from srid '4326' to srid '3857' (OGR failure.) GDAL_ERROR 1: b'PROJ: proj_create_from_database: Cannot find proj.db'`` -
value has an invalid date format. It must be in YYYY-MM-DD format
I am new to python and django. I was trying to make a todo app but i got error in my date field. I've tried searching in google for solutions but I couldn't get a solution for my problem. models: class Task(models.Model): name = models.CharField(max_length=250) priority = models.IntegerField() date = models.DateField(blank=True,null=True) def __str__(self): return self.name views. def demo(request): task1 = `Task.objects.all() if request.method == 'POST': name = request.POST.get('task', '') priority = request.POST.get('priori`ty', '') date = request.POST.get('date', '') task = Task(name=name, priority=priority, date=date) task.save() return render(request, 'index.html', {'task1': task1}) # def details(request): return render(request, 'detail.html', {'task': task}) -
relation "app_table" does not exist LINE 1: SELECT COUNT(*)
i'm running this django app with postgresql db on digital ocean droplet, i've added a django model (table), when running makemigrations and migrate everything seems good, but when i try to render the page related to that model i get this error : relation "app_table" does not exist LINE 1: SELECT COUNT(*) Well, i've tried many solutions except the one suggested to remove the entire database, i know it works, but i can't simply remove my entire data! do you guys have better solutions please ? much appreciated -
Database connection with Django
It won't let me do the migrations, I get this error `(env) C:\Users\Mercadotecnia\PycharmProjects\practica>python manage.py migrate System check identified some issues: WARNINGS: ?: (mysql.W002) MariaDB Strict Mode is not set for database connection 'default' HINT: MariaDB's Strict Mode fixes many data integrity problems in MariaDB, such as data truncation upon insertion, by escalating warnings into errors. It is strongly recommended you activate it. See: https://docs.djangoproject.com/en/4.1/ref/databases/#mysql-sql-mode Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: No migrations to apply.` this is my model from django.db import models # Create your models here. class Libro(models.Model): id = models.AutoField(primary_key=True) titulo = models.CharField(max_length=100, verbose_name="Titulo") imagen = models.ImageField(upload_to='imagenes/', verbose_name="Imagen", null=True), descripcion = models.TextField(verbose_name="Descripcion", null=True)class Meta: db_table = 'Libro' -
AttributeError: Can't get attribute 'EncoderCNN' on <module '__main__'
from django.db import models import django import torch.utils.data as data import cv2 import sys from os import listdir from os.path import join import numpy as np from keras.preprocessing.text import Tokenizer from tensorflow.keras.utils import to_categorical from nltk.translate.bleu_score import sentence_bleu, corpus_bleu from .Dataset import \* from .EncoderCNN import \* from .DecoderRNN import \* from .inference.Compiler import \* dir_name = 'api/training/' batch_size = 32 my_dateset = Dataset(dir_name) embed_size = 50 hidden_size = 256 num_layers = 3 num_epochs = 30 encoder = EncoderCNN(embed_size) decoder = DecoderRNN(embed_size, hidden_size, my_dateset.vocab_size, num_layers) criterion = nn.MSELoss() params = list(decoder.parameters()) + list(encoder.linear.parameters()) + list(encoder.bn.parameters()) optimizer = torch.optim.Adam(params,lr=0.001) encoder = torch.load('api/model_weights/encoder_resnet34_tensor(0.0643).pt') decoder = torch.load('api/model_weights/edecoder_resnet34_tensor(0.0643).pt') pred = Upload(upload_path, my_dataset, encoder, decoder) gen_html(pred, 'api/model_weights/temp') ` AttributeError: Can't get attribute 'EncoderCNN' on <module 'main'. We are trying to load our model but it gives an error at the first torch.load line that it can not find EncoderCNN. I tried everything but it doesn't work. There is a problem with pickle I guess. -
Auto add group to user
Can you tell me why this is happening? Django 4.1 I have created a signal, it works without problems updating model fields etc. But I want to add a group to the user when registering. I wrote the code, but the group is not saved for the user. The group is guaranteed to exist, and created in advance of the user. The user creation is done in Django admin. here is my code User = get_user_model() @receiver(post_save, sender=User) def add_user_to_user_group( sender: User, instance: User, created: bool = False, **kwargs ) -> None: If created: user_group = Group.objects.get(name="Operator") instance.groups.add(user_group) instance.sid = 3 instance.save() I've tried it: transactions through the decorator. use pre_save, m2m_changed. I don't want to override save method In the example I am adding a user to a group, I have tried the other way round -
Why am I getting a 301 and CORS response from Django Rest Framework while the request works well in Postman?
I am trying to make an API GET request from a React & Redux app to a Django app, but am getting an error about CORS with a 301 response. Below is the response Here is the React & Redux code: const fetchClasses = createAsyncThunk( GET_CLASSES, async (id) => { const CLASSES_API = `http://127.0.0.1:8000/learning/classes?schoolPk=${id}`; const response = await fetch(CLASSES_API); const data = await response.json(); return data; }, ); When I use the same code to fetch all schools, it works. But when I add the id params to get all classes in a certain school, thats when I get the error. Below is the views.py code in Django. # Create your views here. class SchoolViewSet(viewsets.ModelViewSet): queryset = School.objects.all() serializer_class = SchoolSerializer class ClassViewSet(viewsets.ModelViewSet): serializer_class = ClassSerializer def get_queryset(self): return Class.objects.filter(school=self.request.query_params['schoolPk']) I have tried setting CORS in Django settings.py file. ALLOWED_HOSTS = ['http://localhost:3000/', '127.0.0.1',] CORS_ALLOWED_ORIGINS = ['http://localhost:3000',] CORS_ORIGIN_WHITELIST = ( 'http://localhost:3000', ) CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_METHODS = [ "DELETE", "GET", "OPTIONS", "PATCH", "POST", "PUT", ] CORS_ALLOW_HEADERS = [ "accept", "accept-encoding", "authorization", "content-type", "dnt", "origin", "user-agent", "x-csrftoken", "x-requested-with", ] CORS_EXPOSE_HEADERS = [ "accept", "accept-encoding", "authorization", "content-type", ] CORS_ALLOW_CREDENTIALS = True I am thinking I could be missing something in … -
How to update Elasticsearch index on change in MySQL database?
I am working on django project. I am performing queries from my database and updating the elasticsearch index at regular intervals based on the timestamps in database. Like if the timestamp is within last hour then I query those objects and add it to the ES index. But I am facing few issues in this process. In django we perform .update() to update the existing object in database but this is not changing the timestamp and hence it is not coming in query and I cant update the ES index. Also if I delete an object in database using query I cant check the deleted objects and then I cannot update the index. Can anyone suggest me to solve these issues or any other way to update the index. -
How to write a Django model field that refers to another field in the same model?
I have a model called booking with two foreignkeys: artists and venues. Artist can request to book venues but venues can also request to book artists. I want to save in the model who tries to book who. How would I go about doing this? class Booking(models.Model): name = models.CharField(max_length=100) #relationships artist = models.ForeignKey(Artist, related_name="events", on_delete=models.CASCADE) venue = models.ForeignKey(Venue, related_name="events", on_delete=models.CASCADE) requester = # Either artist or venue (preferablly pointing to the object) How do I write this? I thought about creating another foreignkey, but that would have to be conditional as it could be either artist or venue. And that would lead to duplication in the database. I also thought about creating a simple boolean "booked_by_artist", but that would not point to which artist. Any help is appreciated! -
environment variables doen't work in django
I tried to connect to postgres in django. My env variables: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.getenv("NAME"), 'USER': os.getenv("USER"), 'PASSWORD': os.getenv("PASSWORD"), 'HOST': os.getenv("HOST"), 'PORT': os.getenv("PORT"), }, } But I got this error: File "/home/ghost/full_stack_projects/e-commerce/venv/lib/python3.10/site-packages/psycopg2/__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) " to address: Name or service not known not translate host name "localhost Here one of my env variables: export HOST="localhost" If i paste data directly, it works -
Is there any way to suggest to user's browser, where to start browsing for an upload ( FileField, <input type="file" ...> )
I have a Filefield, which is exposed to the user via a Modelform and which displays a Browse... (no file selected) button. I can click it, browse to a file and upload it. One anoyance is how browsers initialize the file selection window when one clicks "Browse". Firefox offers the folder from which the last file was uploaded. Chrome offers a list of recent uploads. Both are far from ideal. "Filesystem" or "Computer" would be better, but I can compute a better suggested path for typical workflow from inside Django. Is there anything I have missed whereby I can suggest to the browser what folder it should open in the first instance? JavaScript? Or is it simply not controllable from server-side? (It's an intranet application, so the app has a much better idea of a user's typical / expected filestore, than something exposed to anyone on the net). -
Form input calls file from database for manipulation in django
I am trying to to have a option menu or input field which takes input using a POST request then the python calls a database entry of the same name. I am having issues getting the data back to the Django application. The Output doesn't show in my VS code terminal or the browser console. in my views.py file from django.shortcuts import render from django.shortcuts import get_object_or_404 from .models import Navbar, Hero from django.http import JsonResponse from core.forms import BuildForm def index(request): if request.method == 'POST': form = BuildForm(request.POST) if form.is_valid(): nav = form.cleaned_data['Nav'] hero = form.cleaned_data['Hero'] my_object = get_object_or_404(Navbar, id=nav) my_object2 = get_object_or_404(Hero, id=hero) return render(request, 'core/index.html', {'my_object': my_object}) else: form = BuildForm() return render(request, 'core/index.html', {'form': form}) my forms.py file from django import forms class BuildForm(forms.Form): Nav = forms.CharField(max_length=100) Hero = forms.CharField(max_length=100) Index.html <!DOCTYPE html> {% load static %} <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{% static 'css/style.css' %}"></link> <title>Atom | {% block title %} {% endblock %} </title> </head> <body> {% block content %} {% endblock %} <script src="{% static 'js/form.js' %}"></script> </body> base.html <!DOCTYPE html> {% load static %} <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{% static 'css/style.css' … -
Is it possible to do arithmetic in a template conditional?
Basically I'd like to do this but the syntax is not valid. {% if index in widget.row_starts %} <div class="row"> {% elif index+1 in widget.row_starts %} </div> {% endif %} I tried using index|add:1 but I think that is actually incrementing the value permanently...