Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why the Imgaes doesn't work in my Django Project
My logo doesn't work in Django project: Code bellow: index.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Главная</title> {% load static %} <img src="{% static 'media/logo.svg' %}" alt="My logo"> </head> <body> </body> <footer> </footer> </html> settings.py: STATIC_URL = 'static/' The structure of project: -
How to delete entry in django?
there is a small django project that has methods for creating a topic, creating and editing posts within it. I don't understand how to write a method to delete a post in a topic views.py from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from .models import Topic, Entry from .forms import TopicForm, EntryForm from django.http import Http404 @login_required() def new_entry(request, topic_id): topic = Topic.objects.get(id=topic_id) check_topic_owner(topic.owner, request) if request.method != "POST": form = EntryForm() else: form = EntryForm(data=request.POST) if form.is_valid(): new_entry = form.save(commit=False) new_entry.topic = topic new_entry.save() return redirect('composetopic:topic', topic_id=topic_id) context = {'topic': topic, 'form': form} return render(request, 'composetopic/new_entry.html', context) @login_required() def edit_entry(request, entry_id): entry = Entry.objects.get(id=entry_id) topic = entry.topic check_topic_owner(topic.owner, request) if request.method != "POST": form = EntryForm(instance=entry) else: form = EntryForm(instance=entry, data=request.POST) if form.is_valid(): form.save() return redirect('composetopic:topic', topic_id=topic.id) context = {'entry': entry, 'topic': topic, 'form': form} return render(request, 'composetopic/edit_entry.html', context) def check_topic_owner(owner, request): if owner != request.user: raise Http404 i was tried to add delete_entry() function, but its not working -
django still uses StatReloader even though watchman & pywatchman are installed
I wanted to slow down the auto-reload feature of django's runserver for 7 seconds. While searching for a solution, I read on the django documentation https://docs.djangoproject.com/en/4.1/ref/django-admin/#s-runserver that I should install Watchman as well as pywatchman and that django will use that instead for which I can add a timeout period for reload after file change. I also read on https://adamj.eu/tech/2021/01/20/efficient-reloading-in-djangos-runserver-with-watchman/ that after installation django's runserver will show Watching for file changes with WatchmanReloader instead of Watching for file changes with StatReloader. I also add a .watchmanconfig like this: {"ignore_dirs": [".git", ".vscode", "venv", "htmlcov", "media", ]} But on mine it still uses StatReloader even though watchman & pywatchman are installed in accordance with their doc. django version: 4.1.2 python version: 3.8.16 watchman version: 20221225.010033.0 pywatchman version: 1.4.1 Can anybody help? My gratitude before hand -
Django admin panel: How to show models with ManyToMany and OneToMany relationship within another model?
I tried so hard to write a question title that could somewhat point to the problem, but couldn't. So here is the question in details: I have a Product model, a Usage model and a SubUsage model. Usage model has a OneToMAny relationship with SubUsage model, where for every usage there may be various sub_usages, and the Product model has ManyToMany relationship with these two models, in which a product may have different usages and sub_usages. These models are as below: class Usage(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, ) usage_name = models.CharField( max_length=255, null=False, blank=False, unique=True, ) class SubUsage(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, ) sub_usage_name = models.CharField( max_length=255, null=False, blank=False, ) usage = models.ForeignKey( Usage, on_delete=models.CASCADE, ) class Product(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, ) product_name = models.CharField( max_length=255, null=False, blank=False, unique=True, ) usage = models.ManyToManyField(Usage) sub_usage = models.ManyToManyField(SubUsage) Now in the admin panel, I have product form, in which I can choose usages and sub_usages; as the image below: The problem is that, each usage has different sub_usages, which may has the same name as another sub_usage of another usage; I want to be able to know that each item in sub_usages list is related … -
Fetching a collection of documents and sub collections from firestore to django web app
I have a Flutter mobile app that is connected to a Firestore database, where I upload some data from the mobile app. The goal here is to use Django in a web app to display all collections from Firestore with all of their documents and sub-collection fields' values in the form of a table. I managed to fetch a single document with all its values, but when I tried to loop through the documents, I hit a dead end as every time I try something, it fails. And for some reason whenever I try to loop throgh the docs to display all the IDs for example, it only reads the documents which were created manualy from firestore side if that makes any sense. For example here is the output of the following code: all_users_ref_2 = db.collection('users').stream() for users in all_users_ref_2: abc= (u'{} => {}'.format(users.id, users.to_dict())) print(abc) [![enter image description here][1]][1] As you can see there are only 8 docs IDs printed while the reality is I have +80 docs which were created from the mobile app The structure of my database is a bit complex, so I will add some pictures for a clearer image. [![enter image description here][2]][2] as … -
Django UpdateView - how to return an HttpResponse instead of a URL from "get_success_url"
In the get_success_url you are supposed to provide a reverse url, however I want to pass a simple HTTPResponse (without a template), how can I accomplish that with an UpdateView like so? class SomeView(UpdateView): model = MyModel form_class = MyModelForm template_name = 'form.html' def get_success_url(self): response = HttpResponse('', status=204) return response -
Access .env or environment content inside of Django for a package that uses environment variables
So I have to utilize a package that requires an API_KEY set in the environment to function. It works normally when not in Django, so to make an REST API I utilize the package like such: class QAView(APIView): def post(self, request, format=None): try: answer = internet_ml.NLP.no_context.QA.answer(query) content = json.dumps( {"error": "", "response": answer[0], "resources": answer[1]} ) except: content = json.dumps( {"error": "Google API key not present in .env or environment"} ) return Response(content) And this always returns the except / error. The package itself works when not running in Django. How would I fix this? -
Save additional forms in Django
I have an original form (which is the result of three ModelForms) and I'm creating additional forms for two of those in the front-end. Everything is working fine except for when saving the data. The originally rendered form saves correctly all the instances in the database. However, all the 'additionally added forms' won't save. In the form I have this button that with HTMX adds a new form: <button type="button" class="btn btn-tertiary" hx-get="{% url 'buyandsell:create-product' %}" hx-target="#productforms" hx-swap="beforeend">Add new product</button> This 'create-product' partial form corresponds to this view: def create_product(request): producto_form = ProductoForm() imagen_form = ImagenForm() context = { 'producto_form' : producto_form, 'imagen_form' : imagen_form } return render(request, 'buyandsell/partials/producto-form.html', context) But I guess the view I need to change for saving the forms is the original main view. I tried iterating over 'producto_forms' but it doesn't let me (as I think that iteration refers to the fields of the form). This is the view function that is working well before adding additional products: def anunciocreateview(request): if request.method == "POST": anuncio_form = AnuncioForm(request.POST or None) producto_form = ProductoForm(request.POST or None) imagen_form = ImagenForm(request.POST, request.FILES) if all([anuncio_form.is_valid(), producto_form.is_valid(), imagen_form.is_valid()]): anuncio = anuncio_form.save(commit=False) anuncio.anunciante = request.user anuncio.save() producto = producto_form.save(commit=False) producto.anuncio = anuncio … -
How can I select only th row that has a specific sum total less than in Django?
I have this Model class statics(models.Model): user= models.ForeignKey(Users, on_delete=models.CASCADE) amount = models.DecimalField(max_digits = 100, decimal_places = 8, default=0) Let's say I have a table like this: id | amount 1 | 21 2 | 20 3 | 10 4 | 15 I want in results only to select the rows that the sum of thier amount is less then 55 In this case the result should be id | amount 1 | 21 2 | 20 3 | 10 because all these rows amount sum is less than 55 This is what I tried to do: data=statics.objects.annotate(total=Sum('amount')).filter(total__lte=55) But it didn't work as all rows had the total always equal to their amount not the sum -
Why do I get "'Image' object has no attribute 'name'" error when I visit Images database in admin panel, using Django?
I try to implement a ForeignKey in my models and I get an error when I save multiply images to the Image model. In two words the error started to appear when I wrote this line in Views.py: post = instance, I also tried to make it post = instance.id, but I got another error. The post fileld is models.ForeignKey('Post', on_delete=models.CASCADE). As I have understood, when you use ForeignKey you can't put an integer to an object in the field of it's id. This is why I have put a whole instance. What do I do wrong? Thank you in advance. This is my code: Views.py: def adminpanel(request): if request.method == "POST": form = PostForm(request.POST, request.FILES) instance = form.save(commit=False) if form.is_valid(): form.save() images = request.FILES.getlist('image') for image in images: picture = Image.objects.create( post = instance, image = image, ) Models.py: from django.db import models from imagekit.models import ImageSpecField #from PIL import Image import PIL.Image # Create your models here. class Post(models.Model): name = models.CharField(max_length = 100) thumbnail = models.ImageField(upload_to ='uploads/posts/') thumbnail_small = ImageSpecField(source='thumbnail', format='JPEG', options={'quality': 50}) category = models.CharField(max_length = 100, default = 'initial') slug = models.SlugField(default = 'initial',unique = True) body = models.TextField(default = 'initial') created_at = models.DateTimeField(auto_now_add=True) def … -
django admin - add multiple entries to db with single form submit
I have a model Point where i have a field called name charField. I trying to add multiple entries on Point with single Form submission. For example, the form has textarea field where i will entry 10 names line by line and then i try to split names one by one and save to point table. class Point(models.Model): name = models.CharField(blank=True) class PointForm(forms.ModelForm): pointlist = forms.CharField(widget=forms.Textarea, required=False) class Meta: model = Point fields = '__all__' def save(self, commit=True): return super(Point, self).save(commit=False) I tried to add multiple entries with single form submission in django admin page getting below error: super(type, obj): obj must be an instance or subtype of type -
How do I order related objects of ManyToMany field in Django?
So I have a ManyToMany field, and the related objects need to be ordered by id. But somehow I cannot order it as intended. This is how the models look like: class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='answer', null=True) body = models.TextField(blank=True, null=True) class AllAnswers(models.Model): answers = models.ManyToManyField(Answer, null=True) title = models.CharField(blank=True, null=True, max_length=30) created_at = models.DateField(auto_now_add=True) Now, let's say there are five Answer objects (ordered by id) : answer1, answer2, answer3, answer4, answer5. In my views.py, I'm creating an AllAnswers object but cannot give order to the Answer objects, like the code below. AllAnswers.objects.create( title = 'title #1', ) new_article = AllAnswers.objects.get(title='title #1') all_answers = Answer.objects.all().order_by('id') # This would get answer1 through answer5 new_article.answers.add(*all_answers) Now what I expect is the answers in new_article object to be displayed in the order I set. (by id) But in the template, the order is not the way I intended. (I can't figure out which order it is being displayed, but it definitely is NOT by id) # article.html ... {% for a in new_article.answers.all %} {{x.body}} {% endfor %} ... -
How to given reset password email name on django
How can I set custom django when email name when password reset email is sent. -
Suggestion of a framework for an amateur Python developer
I'm developing a Music database solution to help Dance teachers (Biodanza) share their music collections. The collections are stored in SQL database and I use Python to import new music collections. This is a semi-automated iterative process unlikely to ever be fully automated. So Python is really the way to go. I now need a front end to surface this database to users to allow them to select songs and build new playlists to share with other teachers. I spoke to an IT pro colleague who told me to learn ReactJS, but when I looked into it, I realized it's Javascript based, which I'm not very versed on, and I also will need to learn NodeJS. While meddling with Python, I came across Flask and Django as possible alternatives. The literature AFAIK tells me I would need to develop from base if I use Flask, while Django things are more out of the box. What I need is a pretty simple CRUD application, that let users select songs based on filters such as genre, dance types and few keywords in the field. My main issue is I have about 30 hrs available in total to learn a framework and develop … -
Django - How to get all related objects in ManyToMany relation
I have a Task model with self referencing. Every task can have multiple tasks as precondition tasks. class Task(models.Model): title = models.CharField(max_length=64) precondition_tasks = models.ManyToManyField(to='self', symmetrical=False) I need a query to get all related tasks. eg: a is pre_task of b and b is pre_task of c I want if I get a, I also receive b and c because a is pre_task of b, and also b is pre_task of c. I can do this by for loop and a recursive function. But i know this is terrible. I need to do this and get all related objects by query, not for loop or something like that in Python. -
primary key for users
primary key is created automatically for every row in table right, but for users isnt it better to use their username as primary key? or defaults better? or for posts like a music post or a picture shouldn't we use its name as primary key? if yes how should i change urls ? i mean this is my urlspath('genre_list/<int:pk>/',views.GenreDetailView.as_view(),name='genre_detail'),and path is int shoul i just remove int and let it be like <pk> or text primary key has another way? -
How to expire user token if particular field value is updated in User model in Django?
I'm trying to make a signal to expire the user token if a field value is updated in the User model. This is the signal I've written. But for some reason, instance.is_corporate_profile_admin is giving older data and not the data which is recently saved or sent from the request when the API was hit. apps.py class UserConfig(AppConfig): name = 'user' def ready(self): from . import signals request_finished.connect(signals.task_token_expire) signals.py def expire_user_knox_token(user_id : int, time : object) -> bool: from knox.models. import AuthToken try: _ = AuthToken.objects.filter(user_id=user_id).update(expiry=time) return True except: return False @receiver(post_save, sender=UserDetail) def task_token_expire(sender, instance, **kwargs): if instance and instance.id: from django.db import transaction with transaction.atomic(): from datetime import datetime logout_time = datetime.now() # If is_cp_admin value changed or if no user entry in UserDetailOlderValues then only token expire. try: older_is_cp_admin_value = UserDetailOlderValues.objects.filter(user=instance).order_by('-id').first().is_corporate_profile_admin print('older_is_cp_admin_value------------->', older_is_cp_admin_value) print('new value------------->', instance.is_corporate_profile_admin) # ! THIS VALUE IS NOT THE LATEST VALUE WHICH IS SENT IN THE REQUEST if instance.is_corporate_profile_admin != older_is_cp_admin_value: expire_user_knox_token(user_id=instance.id, time=logout_time) _obj, _created = UserDetailOlderValues.objects.filter(user=instance).update(is_corporate_profile_admin=instance.is_corporate_profile_admin, last_token_expired_at=logout_time) except: expire_user_knox_token(user_id=instance.id, time=logout_time) _obj, _created = UserDetailOlderValues.objects.update_or_create(user=instance, is_corporate_profile_admin=instance.is_corporate_profile_admin, last_token_expired_at=logout_time) I tried using pre_save before post_save, to hold previous data but both pre_save and post_save are fetching same older data. So, I created another model to save … -
Django Slugify with blank object field printing "none" in url
class Entry(models.Model): name = ... city = ... zip_code = ... def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(f"{self.name}-{self.city}-{self.zip_code}") return super().save(*args, **kwargs) Url is being returned as www.example.com/name-city-zip_code. If an object has is missing a city, then url is returning: www.example.com/name-none-zip_code How can I add an if statement in the F string in order to only display an object field if it is not None? I tried the following but did not work: self.slug = slugify(f"{self.name}-{self.city}-{self.zip_code}").replace("none",""). self.slug = slugify(f"{self.name}-{self.city}{% if self.zip_code %}-{self.zip_code}{% endif %}"). self.slug = slugify(f"{self.name}-{self.city}if self.zip_code:-{self.zip_code}"). self.slug = slugify(f"{self.name}-{self.city}if self.zip_code-{self.zip_code}"). -
Using cloudprnt with python with mc-print3
Does anyone know how to use cloudprnt with mc-print3? Unfortunately, StarTSP's support wasn't able to help or provide any tutorials. -
Is there a reason why this django form isn't valid?
my form is only valid when i just use {{ post_form }} without specifying the field, i know this because when i tried it i was able to save it to the data base, so i think i'm doing something wrong in my template. by the way none of these fields are required so i believe they should be able to go empty in the data base... right? this is the html form: <section id="newpost-form"> <form action="{% url 'newpost' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <label for="id_title">Title</label> {{ post_form.title }} <label for="id_image">Thumbnail</label> {{ post_form.image }} {{ post_form.content }} {{ post_form.media }} // this one is for a ckeditor rich text area called content <button type="submit" class="btn">Create</button> </form> </section> this is forms.py class NewPost(forms.ModelForm): class Meta: model = Post fields = ['image', 'title', 'content', 'status', 'author',] and my views.py in case it is relevant: if request.method == 'POST': post_form = NewPost(request.POST, request.FILES) if post_form.is_valid(): ... -
Getting 'role ___ does not exist' when running Django makemigrations
I am attempting to connect a Django app to a local database, per the instructions here. My settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'OPTIONS': { 'service': 'my_service', 'passfile': '.my_pgpass', }, } } My .pg_service.conf: [my_service] host=localhost user=firstlast dbname=my_db port=5432 My .my_pgpass: localhost:5432:my_db:firstlast:password I've defined a new Model, and when I run python manage.py makemigrations myapp I get the following error: /path/to/myproject/venv/lib/python3.9/site-packages/django/core/management/commands/makemigrations.py:143: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': connection to server at "localhost" (127.0.0.1), port 5432 failed: FATAL: role "first" does not exist warnings.warn( No changes detected in app 'myapp' Note that the role in the error is different than the user defined in .pg_service.conf and .my_pgpass. Why is the user wrong? Why am I unable to connect to the database? Thanks in advance for the help. Apologies if there is something obvious I am missing. -
How do I get a CSRF token for Django's auth contrib views if my frontend app is not served by Django?
I'm using Django 3.1.1 with Django's auth contrib module for managing users. I'm not using Django templates, but rather creating a Django API application to respond to requests from my React frontend. I have this in my settings.py file 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', 'directory.middleware.extend_token_response.ExtendTokenResponse' ] #CORS_ORIGIN_ALLOW_ALL = True ALLOWED_HOSTS = ['127.0.0.1', 'localhost', 'dev.mywebsite.com', 'prod.mywebsite.com', 'map.mywebsite.com'] CORS_ORIGIN_WHITELIST = [ 'http://localhost:3000', 'http://localhost:3001', 'http://127.0.0.1:3000', 'http://127.0.0.1:3001' ] CORS_EXPOSE_HEADERS = [ 'Refresh-Token', 'Content-Type', 'Authorization', 'X-CSRFToken' ] CORS_ALLOW_CREDENTIALS = True CSRF_TRUSTED_ORIGINS = ['localhost', '127.0.0.1'] I have this set up in my views.py file class ResetPasswordView(SuccessMessageMixin, PasswordResetView): email_template_name = 'users/password_reset_email.html' subject_template_name = 'users/password_reset_subject' success_message = "We've emailed you instructions for setting your password, " \ "if an account exists with the email you entered. You should receive them shortly." \ " If you don't receive an email, " \ "please make sure you've entered the address you registered with, and check your spam folder." success_url = reverse_lazy('users-home') def post(self, request, *args, **kwargs): print("request data %s" % request.data) email = request.data.get('email') try: if User.objects.get(email=email).active: print("email: %s " % email) return super(ResetPasswordView, self).post(request, *args, **kwargs) except: # this for if the email is not in the db of the system return super(ResetPasswordView, … -
streaming data/variables to templete using django
I have a method that returns float variables and I m streaming it to an HTML template using StreamingHttpResponse in Django, to catch the variable I found a way to use XMLHttpRequest in ajax as shown in the code below: #method to return speed as a list of three float values def gen_speed(video_feed): while True: speed, frame, gray, output = video_feed.get_frames() yield speed def speed_stream(request): try: pathVideo = r"static\app_resources\videos\rl4_pb8-7.mp4" cam = model.video_feed(pathVideo) stream = model.gen_speed(cam) response = StreamingHttpResponse(stream, status=200, content_type='text/event-stream') #response['Cache-Control'] = 'no-cache' return response except: pass this is code is in my HTML : <script> url = '{% url "test_stream" %}'; let xmlhttp = new XMLHttpRequest(); xmlhttp.open("get", url, true); xmlhttp.send(); function handleEvent(e) { console.log(e.target.responseText); } xmlhttp.addEventListener('progress',handleEvent); } <script> the results are like this : as you see the streaming is working but the problem is that I don't know how to handle the values in the template, the values that XMLHttpRequest catches are not separated. what I want is a way to catch this dictionary and access to it so that I can give each value to a streaming chart each time. -
TypeError: object of type 'NoneType' has no len()
I tried this code with the library django-zxcvbn-password when i do it without using this library everything work but when i use this library it seems like when i write a weak password the password field doesn't receive it and that lead to a NoneType Object because password is empty, and i don't know why but when i try it with a good password everything works perfectly. I use this library for security purpose. class SignUpForm(forms.Form) """password_regex = RegexValidator( regex=r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$', message="Password must be at least 8 characters in length and contain at least one uppercase letter, " "one lowercase letter, and one digit. " )""" name_regex = RegexValidator( regex=r'^[A-Z][a-z]{2,149}$', message="Names must begin with an uppercase letter followed by lowercase letters." ) username_regex = RegexValidator( regex=r'^[a-zA-Z][a-zA-Z0-9]{5,149}$', message="Username must begin with a letter followed by letters or digits and have a length of at least 6 " "characters and a maximum of 150 characters. " ) username = forms.CharField(validators=[username_regex], min_length=5, max_length=150) email = forms.EmailField(validators=[EmailValidator], error_messages={'invalid': 'Please enter a valid email address.'}) first_name = forms.CharField(validators=[name_regex], min_length=2, max_length=150) last_name = forms.CharField(validators=[name_regex], min_length=2, max_length=150) password = PasswordField() confirm_password = PasswordConfirmationField(confirm_with='password') #password = forms.CharField(widget=forms.PasswordInput, validators=[password_regex], min_length=8) #confirm_password = forms.CharField(widget=forms.PasswordInput) def clean(self): cleaned_data = super().clean() password = … -
MultipleObjectsReturned at /api/protein/A0A016S8J7
I'm trying to combine 2 columns from 2 csv files. The first file have multiple rows with the same entry. The second file has rows with entries that the first file did not have. col1 ---- a a b b c d col2 ---- a b d e f colCombined ---- a b c d e f This is the python script I wrote that suppose to merge together the 2 columns: proteinIds = set() with open(assignment_data_set) as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') for row in csv_reader: proteinIds.add(row[0]) with open(proteinSequence_data) as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') for row in csv_reader: proteinIds.add(row[0]) proteinIds_rows = {} for item in proteinIds: row = ProteinId.objects.create(protein_id=item) row.save() proteinIds_rows[item] = row I used a python set, so it's not supposed to have duplicates. This is my model for the proteinIds: class ProteinId(models.Model): protein_id = models.CharField(max_length=10, null=False, blank=False, primary_key=True) def __str__(self): return self.protein_id However, when i try to retrieve a proteinid, I still get an error: MultipleObjectsReturned at /api/protein/A0A016S8J7 get() returned more than one Protein -- it returned 2! What am I doing wrong?