Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add SVG as background image in Django template
Pls how can I add SVG as background image in Django I have tried and it's not working I added the svg in this format url("image.svg") but nothing is showing. -
Django raise custom error if invalid API parameters
I am writing an API endpoint that queries for an Event in the time window given. The Event model has a start and end time, and the query accepts a search start time and an search end time. Any Event that overlaps between these two windows is returned. This works well. However, if the user asks to search using a search_time_start that is after the search_time_end, it returns no results (obviously), with no indication why. Instead I would like to return an Error message indicating what is wrong. I have a rough idea of how to do this, but not how to plug it into my existing code. Model class Event(models.Model): name = model.CharField(max_length=64) start_time = models.DateTimeField(null=False) end_time = models.DateTimeField(null=False) Serializer class EventSerializer(serializers.ModelSerializer): start_time = serializers.DateTimeField() end_time = serializers.DateTimeField() class Meta: model = Event fields = ("start_time", "end_time") Filter and View class EventFilterSet(GeoFilterSet): search_time_start = DateTimeFilter( field_name="end_time", lookup_expr="gte", help_text=( "The time for the start of the search. Limits events to those that end after the start time." ), ) search_time_end = DateTimeFilter( field_name="start_time", lookup_expr="lte", help_text=( "The time for the end of the search. Limits events to those that start before the end time." ), ) class Meta: model = Event … -
Saving a record along with the logged in users group in Django
I am new to Django. I want to save the logged in users Group in the groups field upon adding a new record. models.py from django.contrib.auth.models import User, Group, Permission class Infringement (models.Model): name = models.CharField(max_length=200) link = models.CharField(null=True, blank=True, max_length=200) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) infringer = models.ForeignKey(Infringer, on_delete=models.SET_NULL,null=True) player = models.ForeignKey(Player, on_delete=models.SET_NULL,null=True) status = models.ForeignKey(Status, on_delete=models.SET_NULL,null=True) groups = models.ForeignKey(Group, on_delete=models.CASCADE,default=1) views.py @login_required(login_url='login') def createInfringement(request): form = InfringementForm() if request.method == 'POST': form = InfringementForm(request.POST) if form.is_valid(): form.instance.groups = 'request.user.group' form.save() return redirect('home') context ={'form': form} return render (request, 'base/infringement_form.html', context) forms.py class InfringementForm(ModelForm): class Meta: model = Infringement fields = ['name', 'link', 'infringer', 'player'] Based on my research, I tried adding this in the view but it doesn't work. form.instance.groups = 'request.user.group' -
Updating environmental variables in Django while running
I have an app that makes some API calls, I store my API secret in an .env file which is loaded into the Django settings file which works fine. Once a month I have to update the API secret, I have the code to check for expiry and get the new key, my question is how to handle that within my running Django app. As it stands I can load the .env file in and do a find a replace on the key but that feels like a bad way to go about it in addition to not taking effect until the next time the app is restarted. When you have secrets that change over time whats best practice on updating and storing them? -
username and log out not appeared while logging in with google
I have made my models for customer, merchant. models.py class CustomUser(AbstractUser): is_customer = models.BooleanField(default=False) is_merchant = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) class Customer(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, related_name = 'customer', null=True, blank=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) username = models.CharField(max_length=255) email = models.EmailField(max_length=255) phone_number = models.CharField(max_length=12) address = models.CharField(max_length=255) profile_pic=models.FileField(default="") created_at=models.DateTimeField(auto_now_add=True) def __str__(self): return self.username When a customer log in to the app they see their username in navbar and the "log in" button turns out to "log out". Now I want to give customers the functionality to log in with google too. settings.py ALLOWED_HOSTS = ['localhost'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'projectapp.apps.ProjectappConfig', 'django_extensions', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'allauth.socialaccount.providers.facebook', ] SITE_ID=1 LOGIN_REDIRECT_URL = '/' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'reward_database', 'USER': 'postgres', 'PASSWORD': 'ReVerSe@05', 'HOST': 'localhost', 'PORT': '5432' } } AUTHENTICATION_BACKENDS = [ # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by e-mail 'allauth.account.auth_backends.AuthenticationBackend', ] SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': { 'access_type': 'online', } } } For that purposes I have a signal.py. @receiver(post_save, sender = CustomUser) … -
Django - display value of an @property field in a filter
Good evening guys, I have the following model structure in my project: ` class Foo(models.Model): foo_name = models.TextField() foo_city = models.TextField() foo_actions = models.ManyToManyField(Action, through="FooActions") @property def bar(self): response = True if FooAction.objects.filter( foo_id=self.pk, foo__action=Action.ACTION_NAME_PK).first() else False return response ` I need to bring the 'bar' field in a filter, but I'm not getting it. I tried as follows: Foo.objects.filter(nome="João").values("foo_city","bar") Is it possible to bring this information this way? PS.: Sorry for my bad english -
Run python script at the click of an html button (Flask/Django)
I have a very simple python code that retrieves the share price of some stocks. I have managed to include that in Django/Flask so I can see this in a html page. I would like to create an html button that when I click on it it runs the python script and the share prices refresh (and remain on the same html page e.g. index.html) however I can't make it work. Can you please help with the html code for the button and the piece of code that I need to add to the app to make it work? -
Django - How to add a comment limit of 1
I currently have a comment functionality and I want to add a limit of one comment for each user but don't know how to do that. I tought on making a 'posted' field in the user model which would be true when the user posted a comment but I don't know how to do that and most importantly if that is the better way of doing that... class Comment(models.Model): service = models.ForeignKey(Product, on_delete=models.CASCADE, blank=True, null=True, related_name='comments') author = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True,) content = models.CharField(max_length=200, null=False, blank=True) def get_absolute_url(self): return reverse('product-feedback', kwargs={'pk': self.pk}) class ProductFeedbackView(DetailView): model = Product template_name = 'services/product-feedback.html' def get_context_data(self , **kwargs): data = super().get_context_data(**kwargs) connected_comments = Comment.objects.filter(service=self.get_object()) number_of_comments = connected_comments.count() data['comments'] = connected_comments data['no_of_comments'] = number_of_comments data['comment_form'] = CommentForm() return data def post(self , request , *args , **kwargs): if self.request.method == 'POST': comment_form = CommentForm(self.request.POST) if comment_form.is_valid(): content = comment_form.cleaned_data['content'] new_comment = Comment(content=content, author=self.request.user , service=self.get_object()) new_comment.save() return redirect(self.request.path_info) <form action="" method="POST" id="main_form" class="comment_form"> <div> <label for="comment">Type Comment here</label> {{ comment_form.content }} {% csrf_token %} <input type="submit" value="Post"></div> </div> </form> -
How to deal with users when they are authenticated externally via openid recieving only an access or id token?
How do you for example create a model with a foreignkey to a user when the user is authenticated via openid connect externally recieving access token and id token after login or signup? How is authorization (roles, groups, permissions) done when we are not using standard Django authentication or user models but where these tokens (containing a sub or object id) exists in the session? Thanks for your time and help. -
Getting graphQl to work with django mongoengine and graphene
When trying to connect to graphQl, i am met with this error. AssertionError at /graphql/ You need to pass a valid Django Model in ProductType.Meta, received "<class 'inventory.models.Product'>". I am using Django, mongoengine and graphene. my models: from django.db import models from mongoengine import * # Create your models here. class Product(Document): name = StringField(required=True) pCode = StringField(required=True) sku = StringField() cost = StringField() price = StringField() category = StringField() meta = { "indexes":["name","pCode"] } my schema: import graphene from graphene_django import DjangoObjectType from .models import Store, Vendor, Product class ProductType(DjangoObjectType): class Meta: model = Product fields = ("name","pCode","price") class Query(graphene.ObjectType): all_products = graphene.List(ProductType) def resolve_all_products(root, info): return Product.objects.all() schema = graphene.Schema(query=Query) It is almost as if the document class doesnt pass something correctly...please help -
Django How to get sum of column after doing subtraction on each row?
For example, I have an item where the "soldprice" price was 10, the "paid" was 2 and the "shipcost" was 2. I am currently doing as follows: @property def profit(self): if self.soldprice is not None and self.paid is not None and self.shipcost is not None: return self.soldprice - self.paid - self.shipcost And the return should be 6, (10 - 2 - 2). I am then calling that profit property in a template. {% for inventory in inventory %} <tr> <td><a class='btn btn-success btn-sm' href=''>View Breakdown</a> <td>{{inventory.id}}</td> <td>{{inventory.product}}</td> <td>{{inventory.description}}</td> <td>{{ inventory.profit }}</td> </tr> {% endfor %} So I see things as below: ID Product Profit ---------------------------------------- 6 dessert 8.80 7 bowls 3.37 8 bowls 16.32 15 chip 6.19 What is the best way to add the "Profit" column up after calling the profit property? So for example, the total for the above would be 34.68 so I can display that in the template. Any and all help is greatly appreciated. -
How to use a javascript variable inside a Django {% url %} tag?
Im trying to dynamically change the link of a button based on which div a user has currently selected. I tried to run a quick test with a JS variable in the HTML script tag, but Django isn't reading the variable like a num. <script type="text/javascript"> const testing = 10 </script> <a href="{% url 'battlefield:onevsone_trainer_selection' num_trainers=testing %}" class='description__button btn btn__large'>Next ></a> URL looks like: path('one-vs-one/trainers/<int:num_trainers>', views.oneVsOne, name='onevsone_trainer_selection') Not sure exactly why it's not working. When I passed it a string of '10' it worked -
django-filter search filed not able to recognize and filter the None value
I'm using django-filter: filter.py: import django_filters TYPE_CHOICES = (('One', 'One'), ('Two', 'Two'),(None,None)) class MyFilterSet(django_filters.FilterSet): Type = django_filters.ChoiceFilter(choices=TYPE_CHOICES) class Meta: model = Mymodel fields = ['Type '] In the UI form select filed, when I choice the None ,and submit ,the system can't find the None value one. Nothing happen. I have tried convert the None to sting None ,but it still not work. Any friend can help ? -
How to perform additional functions from a class UpdateViews
to edit my table I use UpdateViews , and pass there the same template as in the creation function: class CampaignEditor(UpdateView): model = Campaigns template_name = 'mailsinfo/add_campaign.html' form_class = CampaignsForm def get_context_data(self, **kwards): context = super().get_context_data(**kwards) data = list(Emails.objects.values()) # you may want to further filter for update purposes data = MailsTableWithoutPass(data) userID = self.object.user_guid all_mails = CampaignEmail.objects.values_list ('id','campaigne_guid', 'email_guid') context['data'] = editCampaignDataWork(data, userID, all_mails) return context def add_campaign(request): if request.method == 'POST': addCampaignDataToDB(request.POST) data = list(Emails.objects.values()) data = MailsTableWithoutPass(data) form = CampaignsForm() data_ = { 'form': form, 'data': data } return render(request, 'mailsinfo/add_campaign.html', data_) Saving the main form is fine, but apart from that my create function has extra steps, for one more database, it's all done in a function - addCampaignDataToDB : def addCampaignDataToDB(req): formCampaigns = CampaignsForm(req) IDs = req['IDs'] if IDs != '': IDs_list = IDs.split(',') user_guid = req['user_guid'][0] for i in IDs_list: CampaignEmail.objects.create(email_guid=int(i), campaigne_guid=int(user_guid)) if formCampaigns.is_valid(): formCampaigns.save() I encountered a problem that when calling a class for edit from a function addCampaignDataToDB only a fragment is executed: if formCampaigns.is_valid(): formCampaigns.save() But I need this whole feature to work As a result, I get that part of the actions are not executed and it seriously breaks my … -
Non model field in Django ModelSerializer
class Form(models.Model): key = models.UUIDField(unique=True, default=uuid.uuid4, editable=False) class Answer(models.Model): form = models.ForeignKey(Form, on_delete=models.CASCADE, related_name='answers') answer = models.TextField() class AnswerSerializer(serializers.ModelSerializer): form_key = serializers.UUIDField(write_only=True) class Meta: model = imported_models.Answer fields = ['id', "answer"] I want to create Answer based access on form_key. So i need to validate form_key as valid UUID key. How can i do that? -
Django. Filtering both related and relating model based on a field in relating one
I have two models: class Genre(models.Model): name=models.CharField() class Book(models.Model): name=models.CharField() genre=models.ForeignKey(Genre, related_name='book', on_delete=models.CASCADE) published=models.BooleanField() I also have basic serializers for them: class BookSerializer(serializers.ModelSerializer): class Meta: model=Book fields='__all__' class GenreSerializer(serializers.ModelSerializer): books = BookSerializer(source='book', many=True) class Meta: model=Genre fields='__all__' I need to query and serialize Genre models and related Book models excluding the books, which aren't published. I also don't need to query genres, which don't have published books. Example: g1=Genre(name='g1') #Serialize b1=Book(genre=g1, name='b1', published=False) #Don't serialize b2=Book(genre=g1, name='b2', published=True) #Don't serialize g2=Genre(name='g2') #Don't serialize, because there's no published books for this genre b3=Book(genre=g2, name='b3', published=False) #Don't serialize Desired result: [ { 'id': 1, 'name': 'g1', 'books': [ { 'id': 2, 'name': 'b2', 'published': true } ] } ] None of the filtering and excluding I tried worked. They all seem to affect only outer model (genre in this case) and I can't figure out how to filter underlying books first and then filter genres based on the result of book filtering. I found a workaround, but it involves multiple queries, creating new temporary genre and deleting it later, so this approach isn't really an option. -
upload_to and storage not working in Django 4.1
i have just upgrade my Django from 2.x to 4.x. I had a function that not working correctly. I have been trying so many things but still not able to figure it out. So i need some help file = models.FileField( upload_to=get_file_path, storage=AbsolutePathStorage(), max_length=500, ) from django.core.files.storage import FileSystemStorage class AbsolutePathStorage(FileSystemStorage): """Storage that allows storing files given absolute paths.""" def path(self, name: str) -> str: """Override path validation to allow absolute paths.""" # Return name if it's a absolute path. if name.startswith("/"): return name # Return regular joined path if this is a relative path. return super().path(name) So before upgrading Django, the file is uploaded to the upload_to folder ( outside of MEDIA_ROOT). Everything is working fine. But after i upgraded Django to 4.1. Its not working anymore and complaining about: The joined path (upload_to) is located outside of the base path component (MEDIA_ROOT ). Any idea ? Thank you. -
Django - unable to add a field in postgres?
I am trying to add a field to existing model. example: from django.db import models # from django.contrib.auth.models import User from test.settings import AUTH_USER_MODEL as User import random class BrModel(models.Model): bro = models.CharField(max_length=20) cl_id = models.CharField(max_length=20) br_pwdd = models.CharField(max_length=255) api_key = models.CharField(max_length=255) # country = models.CharField(choices=COUNTRY_CHOICES["COUNTRY_CHOICES"], max_length=3, blank=True, default="IND") api_sec = models.CharField(max_length=255) t_sec = models.CharField(max_length=255, blank=True, null=True) # The new field I am trying to add, This is a test field because it keeps failing test_field = models.CharField(max_length=10, default="T") created_at = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey( User, related_name='bro', on_delete=models.CASCADE, null=True) I am constantly getting this error on elastic beanstalk postgres RDS: column bro_setting_brmodel.test_field does not exist LINE 1: ...ret", "bro_setting_brmodel"."t_sec", "bro_se... ^ at "t_sec" The field I want to add: def create_new_ref_number(): not_unique = True while not_unique: unique_ref = random.randint(1000, 65535) if not BrModel.objects.filter(test_field=unique_ref): not_unique = False return str(unique_ref) test_field = models.CharField(max_length=10, blank=True, editable=False, unique=True, default=create_new_ref_number) It works on local server which is using sqlite db. I am all out of ideas about why I the migration is not getting applied. -
Django Channels. How to "try-except" the error when the "Event loop is closed"?
I have a trigger that sends a message to the layer group. As it is a WebSocket, it works only on a webpage, but I have also an API point for that trigger because it also saves some object to DB. So I need to handle(pass) an error when the trigger act when Websocket is closed (i.e. web page is closed). So I think I need to "try except" that RuntimeError. But where to make it? What code include in try-except? I try to "try-except" the __init__ of Consumer Class, but to no avail. Pls, advise. -
django-filter AssertionError: Cannot filter a query once a slice has been taken
I'm using Django-filter ,I want to slice the rows ,just want the first 75 row: def hist_view_render(request): all_obj = RunStats.objects.all().order_by('-create_dttm')[:75] hist_filter = RunStatsFilter(request.GET, queryset=all_obj) paginator= Paginator(hist_filter.qs, 15) page = request.GET.get('page') try: response = paginator.page(page) except PageNotAnInteger: response = paginator.page(1) except EmptyPage: response = paginator.page(paginator.num_pages) context = {'response': response,'filter': hist_filter} return render(request, 'runstat_hist.html',context) I have tried put the [:75] in different places ,but I always receive the error: Cannot filter a query once a slice has been taken The only way that works is slice it in the template ,but I want to find a way to slice it in the views.py. Any friend can help ? -
How can I paginate the attributes from a model?
I have a single for each series, but I want to paginate inside this page. I want to paginate the episodes because some series have more than 100 episodes and it is too much for a single page. class SerieDetailedView(DetailView): template_name = "tailwind/series_detail.html" model = Serie slug_url_kwarg = "serie_name" slug_field = "name" context_object_name = "project" def get_object(self, queryset=None): return Serie.objects.get(name=self.kwargs["serie_name"]) In this case, I have this as my model: class Serie(models.Model): name = models.CharField(max_length=150, unique=True) finished = models.BooleanField(default=False) episodes = ArrayField(base_field=models.CharField(max_length=100), default=list) published_at = models.DateTimeField(auto_now_add=True) I’m just getting how to paginate all the series, but it’s different, I want to paginate a thing that is inside the series. I’ve tried to do it, but it has not worked because is a single page: class SerieDetailedView(DetailView): template_name = "tailwind/series_detail.html" model = Serie slug_url_kwarg = "serie_name" slug_field = "name" context_object_name = "project" paginate_by = 10 def get_object(self, queryset=None): return Serie.objects.get(name=self.kwargs["serie_name"]).episodes.order_by('-published_at') -
association user with forms
I'm making something like this: admin creates form manually, and user is automatically created with this form. But I need to add association that form to a new automatically created user, that's where I'm stuck. How can I make user auto registration to associate that form I need this because I want to then to show 'filtered, created' form by user. Views.py def create_driver_view(request): if request.method == "POST": add_driver = DriverForm(request.POST) add_driver_files = request.FILES.getlist("file") if add_driver.is_valid(): email = request.POST['email'] usern = 'test' passw = 'test' user = User.objects.create_user(email = email, username = usern, password = passw) user.save() f = add_driver.save(commit=False) f.user = request.user f.save() for i in add_driver_files: DriversFiles.objects.create(driver_files=f, file=i) return redirect('drivers:list_driver') else: print(add_driver.errors) else: add_driver = DriverForm() add_driver_files = DriverFormUpload() return render(request, "drivers/add.html", {"add_driver": add_driver, "add_driver_files": add_driver_files}) Forms.py class DriverForm(forms.ModelForm): class Meta: model = Drivers fields = [ 'full_name', 'phone_number', 'email', 'address', 'country', 'state', 'city', 'zip', 'birth_date', 'license_no', 'license_exp_date', 'last_medical', 'next_medical', 'last_drug_test', 'next_drug_test', 'status', ] class DriverFormUpload(forms.ModelForm): class Meta: model = DriversFiles fields = [ 'file', ] widget = { 'file': forms.ClearableFileInput(attrs={'multiple': True}), } Models.py STATUS = ((0, 'Inactive'), (1, 'Active')) class Drivers(models.Model): full_name = models.CharField(max_length=50, default=None) phone_number = models.CharField(max_length=50, default=None) email = models.EmailField(unique=True,max_length=255, default=None) address = models.CharField(max_length=70, default=None) … -
Сreate a folder for user files when creating a user FastAPI?
How can I create a directory for user files when creating a user? I want to store files from a client in that client's directory the code executes without errors, but the directory does not creating in the specified directory... i have this, but it doesn't work def create_user(db: Session, request: UserBase): new_user = DbUser( # id create automaticly first_name = request.first_name, last_name = request.last_name, email = request.email, password = Hash.bcrypt(request.password) ) db.add(new_user) db.commit() db.refresh(new_user) path = f"/users_files/user_id_{new_user.id}/orders" try: pathlib.Path(path).mkdir(parents=True, exist_ok=True) except OSError: print("Create folder %s error" % path) else: print ("Folder create %s " % path) return new_user when i specify the path = f"../users_files/user_id_{new_user.id}/orders" the dedirectory is created but one level higher. -
How to ensure that the timezone is entered in the ISO UTC format within the request body?
I am using pydantic within FastAPI and I need to ensure that the timestamp is always entered in the UTC ISO format such as 2015-09-01T16:09:00:000Z. from typing import Optional from fastapi import FastAPI from pydantic import BaseModel, Field from datetime import datetime app = FastAPI() measurements = [ { "timestamp": "2015-09-01T16:09:00:000Z", "temperature": 27.1, "dewPoint": 16.7, "percipitation": 0 }, { "timestamp": "2016-09-01T16:09:00:000Z", "temperature": 21.3, "dewPoint": 12.3, "percipitation": 1.5 } ] class MeasurementIn(BaseModel): timestamp: datetime temperature: Optional[float] dewPoint: Optional[float] percipitation: Optional[float] @app.post("/measurements") async def create_measurement(m: MeasurementIn, response: Response): measurements.append(m) The above code is working but it is also accepting datetime in other formats. I want to strictly restrict it to UTC ISO Format. I have tried to change the timestamp to timestamp: datetime.utcnow().isoformat() but it is not working. -
how can i connect my google sql postgres to my django application?
I have create my google postgres instance on cloud sql service, and i couldn't connect it with my django application, in the link below they give sqlalchemy configuration, but nothing about the database host [cloud.google](https://cloud.google.com/sql/docs/postgres/connect-admin-proxy#debianubuntu ) This is my database credentials # GCP DATABASE CREDENTIALS DB_NAME=db_name DB_HOST= *** DB_PORT=5432 DB_USER=db_user DB_PASSWORD=password Not sure about the DB_HOST, i tried the public ip address of my db and it not working i got this error This is my Django settings : DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": os.environ.get("DB_NAME"), "USER": os.environ.get("DB_USER"), "PASSWORD": os.environ.get("DB_PASSWORD"), "HOST": os.environ.get("DB_HOST"), "PORT": os.environ.get("DB_PORT") # default postgres port } }