Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Category and Subcategories OPT Group select in Django
I have two three models: Announce Category Subcategory This is my form.py # Formulaire de la depose d'une annonce class AnnonceForm(forms.ModelForm): title = forms.CharField(label="", help_text="", widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Titre de mon annonce'})) category = forms.ModelChoiceField(queryset=Souscat.objects.all(), empty_label='Selectionnez une categorie', label="", help_text="", widget=forms.Select(attrs={'class': 'form-control'})) class Meta: model = Annonce fields = ('title','category') And this is my models: # Catégories class Category(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(null=True, unique=True) created_date = models.DateTimeField(default=timezone.now) class Meta: verbose_name = "Catégorie" verbose_name_plural = "Catégories" def __str__(self): return self.title # Sous catégories class Souscat(models.Model): category = models.ForeignKey(Category, related_name="s_category", on_delete=models.CASCADE) title = models.CharField(max_length=255) slug = models.SlugField(null=True, unique=True) created_date = models.DateTimeField(default=timezone.now) class Meta: verbose_name = "Sous catégorie" verbose_name_plural = "Sous catégories" def __str__(self): return self.title On my annouce, i will get only subcategories, but on my select i want to show the categories and the subcategories can be selectable. I have see this is possible with "optgroup", but i have successfull get all the subcategories on my but, i want to show the categories (not selectable) in my select with the subcategories (selectable). For have the category i make simply {{ form.category }} How can i make this ? Thank you -
How to upload a file in Django and get other file in response
i have a task to do and task description is : The user uploads an excel file and then this file is sent via request and received in response an excel file and pdf file. i have problem to write views function what the best way to do this task? -
make a new django model that looks like a list
I want to add a model, but I don't get it working. my models.py class Information(models.Model): id = models.CharField(max_length=200, primary_key=True) title = models.CharField(max_length=500) link = models.CharField(max_length=100) summary = models.CharField(max_length=1000) published = models.CharField(max_length = 100) def __str__(self): return self.title class Search(models.Model): id = models.CharField(max_length=100, primary_key=True) searched_titles = models.CharField(max_length=100) searched_topics = models.CharField(max_length=100) number_found_articles = models.IntegerField() def __str__(self): return self.id now i would like to have a model that would be kind of a list. so in there i would like the article_id and search_id. so i can access all articles that were found with the search_id=''. Or i could find in which searches a particular article would appear. How should the model look like? -
Django form's not valid
This question might be asked alot in stackoverflow but i couldn't find the answer. Take a look at code: # models.py class Message(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) body = models.CharField(max_length=200, null=True, blank=True) room = models.ForeignKey(Room, on_delete=models.CASCADE, blank=True, null=True) posted = models.TimeField(auto_now_add=True) def __str__(self): return self.body views.py: class RoomInsideView(View): template_name = 'room/room_inside.html' form_class = SendMessageForm room = None def get(self, request, room_id, room_slug): self.room = Room.objects.get(id=room_id) if self.room.is_private: return redirect('room:private_room_auth', self.room.id) form = self.form_class() context = { 'room': self.room, 'form': form, } return render(request, self.template_name, context) def post(self, request, room_id, room_slug): form = self.form_class(request.POST) print(request.POST) if form.is_valid(): new_msg = Message(body=form.cleaned_data['body']) new_msg.user = request.user in all_messages = Message.objects.filter(room=self.room) messages.error(request, 'form not valid', 'warning') return render(request, self.template_name, {'form': form, 'message': all_messages}) forms.py: class SendMessageForm(forms.ModelForm): class Meta: model = Message fields = ('body',) widgets = { 'body': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Send'}), } template: <form method="post" action="" novalidate> {% csrf_token %} {{ form.non_field_errors }} {{ form.body.errors }} {{ form.body }} <input type="submit" value="Send" class="btn btn-primary"> </form> as I added a messages.error if form is not valid it's returning form not valid and I can't find where am I doing wrong -
i want to execute INSERT query in Django project without touching Models.py
i don't want to make table in my models.py as my database is very large and want to perform a INSERT query in it.it is possible to perform this without touching models.py. please help me if you have any idea. sorry for any mistakes, thanks in advance. -
django-storages dropbox - SuspiciousFileOperation
I try to upload a picture in Django-Admin, without success. I made a minimal app with basic informations, but it fails when I want to upload the ImageField to the server (storage on Dropbox). I installed django-storages, and here is my settings : DROPBOX_OAUTH2_TOKEN = "my_token_here" DROPBOX_ROOT_PATH = 'storage' My model : class Picture(BaseModel): title = models.CharField(max_length=80, default='', blank=True) description = models.TextField(default='', blank=True) image = models.ImageField(blank=True, null=True) I get the following error : SuspiciousFileOperation at / Detected path traversal attempt in '/home/me/Code/my-project/storage/my_image.JPG' Environment: Request Method: POST Request URL: http://127.0.0.1:8001/admin/gallery/picture/add/ Django Version: 4.0.2 Python Version: 3.8.10 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'gallery'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/home/gabmichelet/Code/nendaz-patrimoine/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/gabmichelet/Code/nendaz-patrimoine/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/gabmichelet/Code/nendaz-patrimoine/env/lib/python3.8/site-packages/django/contrib/admin/options.py", line 622, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/gabmichelet/Code/nendaz-patrimoine/env/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/gabmichelet/Code/nendaz-patrimoine/env/lib/python3.8/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/home/gabmichelet/Code/nendaz-patrimoine/env/lib/python3.8/site-packages/django/contrib/admin/sites.py", line 236, in inner return view(request, *args, **kwargs) File "/home/gabmichelet/Code/nendaz-patrimoine/env/lib/python3.8/site-packages/django/contrib/admin/options.py", line 1670, in add_view return self.changeform_view(request, None, form_url, extra_context) File "/home/gabmichelet/Code/nendaz-patrimoine/env/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File … -
How to prevent user login from multiple devices in Django?
I am facing issue in Django, I want to prevent multiple device login in Django, I am creating custom session and setting True & False when user is login or logout. When i am closing browser still it is in True state in back-end , I want to update it on browser close. Any ideas how to solve it in a best way. -
How to send partial status of request to frontend by django python?
Suppose, I have sent a post request from react to Django rest API and that request is time taking. I want to get how many percentages it has been processed and send to the frontend without sending the real response? -
Unable to filter products by category. Categories do not show when clicked Django
I am trying to filter listings/products by categories, clicking on the name of any category should take the user to a page that displays all of the listings in that category. When I click on the Category tab, it displays the names of the categories that have been listed but it does not show any listing/products attached to that category. I have implemented this so far and would like help knowing why I am having this error. URLS.PY path("category", views.all_category, name="all_category"), MODELS.PY class Category(models.Model): name = models.CharField(max_length=25) def __str__(self): return self.name class Auction(models.Model): title = models.CharField(max_length=25) description = models.TextField() current_bid = models.IntegerField(null=False, blank=False) image_url = models.URLField(verbose_name="URL", max_length=255, unique=True, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) category = models.ForeignKey(Category, max_length=12, null=True, blank=True, on_delete=models.CASCADE) LAYOUT.HTML <ul class="navbar-nav mr-auto"> <li class="nav-item"> <a class="nav-link" href="{% url 'index' %}">Active Listings</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'all_category' %}">Category</a> {% for category in categories %} <a class="nav-link" href="{% url 'all_category' %}?category={{ category.name}}">{{ category.name}}</a> {% endfor %} </li> VIEWS.PY def all_category(request): categories = Category.objects.all() category = request.GET.get('category') if category == None: products = Auction.objects.all().order_by('-created_at') else: products = Auction.objects.filter(category__name=category) context = {'categories':categories, 'products':products} return render(request, 'auctions/layout.html', context) I also tried implementing this but this seemed worse off as it … -
Registration or login as a user of project in django framework
I'm new to django framework.i've already familiar with php.In php if I need to register as admin or user.. I've just create a table for admin or user and register them via SQL queries but it's blind for me dive into django..Django has already have some tables like django.admin.log , django.user like that ,is there any table existing for admin or user? Can I use those tables for my project as a admin or register login? Please clarify about it, -
OIDC Redirect URI Error in Dockerized Django
I'm running two applications using docker-compose. Each application has a bunch of containers. The intention is for App A (django app) to host the OIDC provider, while App B (some other app) will authenticate users by calling the App A API. I'm using the django-oidc-provider library (https://django-oidc-provider.readthedocs.io/en/latest/index.html) I've already configured the OIDC integration on both sides. However, every time App B redirects to App A, I hit the following error: Redirect URI Error The request fails due to a missing, invalid, or mismatching redirection URI (redirect_uri). Even though the redirect_uri matches exactly on both sides. Here's my docker-compose.yml: version: '3' networks: default: external: name: datahub-gms_default services: django: build: context: . dockerfile: ./compose/local/django/Dockerfile image: dqt container_name: dqt hostname: dqt platform: linux/x86_64 depends_on: - postgres volumes: - .:/app:z environment: - DJANGO_READ_DOT_ENV_FILE=true env_file: - ./.envs/.local/.django - ./.envs/.local/.postgres ports: - "8000:8000" command: /start postgres: build: context: . dockerfile: ./compose/local/postgres/Dockerfile image: postgres container_name: postgres hostname: postgres volumes: - dqt_local_postgres_data:/var/lib/postgresql/data:Z - dqt_local_postgres_data_backups:/backups:z env_file: - ./.envs/.local/.postgres broker: container_name: broker depends_on: - zookeeper environment: - KAFKA_BROKER_ID=1 - KAFKA_ZOOKEEPER_CONNECT=zookeeper:2181 - KAFKA_LISTENER_SECURITY_PROTOCOL_MAP=PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT - KAFKA_ADVERTISED_LISTENERS=PLAINTEXT://broker:29092,PLAINTEXT_HOST://localhost:9092 - KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR=1 - KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS=0 - KAFKA_HEAP_OPTS=-Xms256m -Xmx256m hostname: broker image: confluentinc/cp-kafka:5.4.0 ports: - 29092:29092 - 9092:9092 datahub-actions: depends_on: - datahub-gms environment: - GMS_HOST=datahub-gms - GMS_PORT=8080 - … -
Django / Bootstrap forms - Input size - Python
I'm learning Django together with Bootstrap (5.1.3), and I'd like to keep my code as simple as possible for future updates. That's why I went for generic views in Django (Create/Detail/Edit...). That works great, all the features work seamlessly now. What I'm struggling with is the layout of my Edit / Create forms. I can't find a way to increase the size of the input boxes. I have the following code, for my Model: class customer(models.Model): created_date = models.DateTimeField(auto_now_add = True, editable = False, verbose_name = u"Créé le") modified_date = models.DateTimeField(auto_now = True, editable = False, verbose_name = u"Modifié le") fk_referrer = models.ForeignKey('customer', on_delete=models.CASCADE, verbose_name='Parrain', blank = True, null=True) surname = models.CharField('Prénom', max_length=200) lastname = models.CharField('Nom', max_length=200) phonenumber = PhoneNumberField('Téléphone', blank = True, null = True) email = models.EmailField('Email',max_length=100, blank = True, null = True) fk_interest = models.ManyToManyField(interests, verbose_name='Interêts', blank=True) comments = models.TextField('Commentaires', max_length=2000, blank=True, null = True) def __str__(self): return (self.surname + " " + self.lastname) I did create a generic view: class CustomerEditView(UpdateView): model = customer fields = "__all__" template_name = 'client/edition.html' success_url = '/client/' And have added the form in edition.html template: <form method="POST" enctype="multipart/form-data"> <!-- Security token --> {% csrf_token %} <!-- Using the formset --> … -
Count common ManyToMany members in queryset
Assuming I have such models: class Bar(models.Model): pass # some simple Model goes here class Foo(models.Model): bars = models.ManyToManyField(Bar) And some variable main_object = Foo() with bars filled, how can I make a Queryset so that it's annotated with the number of common bars elements betweeen each entity and main_object? Example: There are three Bar records, with primary keys 1, 2 and 3. main_object has pk=2 as member set in bars. Foo has two records: main_object and another with pk=1 set in bars. In this case, I want an annotation that has the value of 0, since said record has no common Bar foreign keys with main_object. I can imagine something similar to Foo.objects.filter(bars__in=<some_values_here>) but instead of simply checking presence, actually counting it like from django.db.models.Count. Is it even solvable via Querysets or I should resort to manual counting through loops? In practical use, such way of querying can be useful in similarity ranking, but it seems non-trivial for me. -
how to order Django query based on the sum of a specific field grouped by another field?
how to order Django query based on the sum of a specific field grouped by another field? The Model is simply recording goals that players score, every player has many inputs that each refers to a single goal. I'm trying to find out the top 3 scorers with the highest amount of goals scored. Here is my model : class Goal(models.Model): match = models.ForeignKey(Match,on_delete=models.CASCADE) date_time = models.DateTimeField() team = models.ForeignKey("teams.Team",on_delete=models.PROTECT,null=True,blank=True) player = models.ForeignKey('players.PlayerProfile',related_name="goal_maker",on_delete=models.PROTECT,null=True,blank=True) assistant = models.ForeignKey('players.PlayerProfile',related_name="goal_assist",on_delete=models.PROTECT,null=True,blank=True) Now what I want to do is to group it by player field ordering it from the highest player with goals to the lowest one What I have tried I have tried to loop trough all my database entries for this model Goal.objects.all() and check if it is the same player I do +=1 if not I create a new entry, and that is surly not the best way do achieve this. -
selenium.common.exceptions.WebDriverException: Message: Can not connect to the Service C:\Path\chromedriver.exe
All of a sudden I've started getting this error message, I've been using Selenium and Chromedriver for a while on this project with no issues and as far as I'm aware I've not changed anything to cause this error. I've read a few posts with this question but haven't been able to solve it. I've got two projects with the exact same Selenium code, one where I've just got the Selenium part and another that is a full Django project, using Celery to run the Selenium task. Chromedriver is working fine still in the selenium-only project (that has exactly the same code and setup as the Django project) Chromedriver has been working fine in my Django-Celery project for the past week (when I moved my selenium-only code over to run in celery tasks). I've not changed anything of note in my Django-Celery project to make it stop working I've checked and 127.0.0.1 is added to etc/hosts file (it was there already) I've got no idea what the problem is, this came up a few days ago but then only happened once and went away after I retried, now I can't start Selenium at all. -
Django - Form - ForeignKey - Hidden - Default value
I have a Hidden ForeignKey in an update form that I want to set to value of default value of 2 in my html form, but I can't get it to work. forms.py eval_sent_state = forms.ModelChoiceField(widget=forms.HiddenInput(), initial=2,queryset=models.EvalUrlSentState.objects.all()) Th Html output i get: <input type="hidden" name="eval_sent_state" value="1" id="id_eval_sent_state"> -
how to use django Serializer to update field in database
I create report Model that have a field report state i need a serializer that when user create report the state of report automatically change to pending or something else and when edit report body and save it then automatically set state to Edited or ... -
How to group a model data based on another model and paginate in django?
I have two models: Category - Zero or multiple books can be in one category Book - A book can have zero or one category if I do Book.objects.all() I'll get something like [book11, book10, book9, ...] normally but I don't want that. What I want is something like: [ [book11, book2, book1], [book10], [book8, book6], [book7], [book4, book3], ... ] Where Books are grouped according to their category. The books that don't have a category will also include in the list as a single element group Ordering would be according to book's creation in reverse For better understanding here is my model structure: class Category(models.Model): name = models.CharField(max_length=50) class Book(models.Model): name = models.CharField(max_length=128) category = models.ForeignKey(Category, on_delete=models.CASCADE,related_name='books', null=True, blank=True) -
Query Multiple Tables in Django and geta consolidated result
I am building a Blog application in Django and currently stuck at Querying the Data. I am creating a Post and then uploading multiple images to that post. This is my Blog Post Model. class Post(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT) title = models.CharField(max_length=255) description = models.CharField(max_length=1000,null=True) Tags = models.CharField(max_length = 255,null=True,blank=True) Created_date = models.DateTimeField(auto_now_add=True) Updated_date = models.DateTimeField(auto_now=True) category = models.ForeignKey(Category, on_delete=models.PROTECT) And this is my Images Model class Images(models.Model): Post = models.ForeignKey(Post,on_delete=models.CASCADE) image = models.ImageField(upload_to='media/') Now using this implementation I have 2 tables in DB in which data is stored as expected. In the first tables all the details related to Post are being stored and in the second Table ID, Post_Id, Image_URL is being stored. If I upload 3 images then three rows are being created. Now I want to Query the data that is -> I want all the posts and I want all the Images according to the Posts. I can get seprate queries for Post and Images but how can this be done in Django ORM? How can I query The data? -
Django dev server no longer reloads on save
I'm developing a simple Django app and things were going great until suddenly the dev server stopped reloading automatically on file change. Now I have to manually restart the server every time I change some Python file, which is pretty annoying. I've tried removing my virtual environment and reinstalling Django to no avail so I guess the problem is with the project itself. In settings.py I have DEBUG = True and also when I start the server it says Watching for file changes with StatReloader, which I assume means that it should reload. Can't think of what else it could be. I don't think I even touched any settings files, just views, urls and models. -
Django: continuing block after exception
How to continue the execution of a block after an exception. I have two vmware servers running I have created two functions, one that refreshes the information coming from the server and the other that populates the database. Except that when one of the servers does not respond an error occurs and the refresh is not done. def vm_refresh(request): vmware_list = Vmware.objects.all() for i in vmware_list: vmwarepopulatevm(i) i.save() # ... def vcsapopulatevm(vmware): # ... req1 = vmrequestsget() if 'value' in req1.json().keys(): for i in my req1.json()['value']: VirtualMachine.objects.update_or_create(vm=i['vm'] vmware=vmware, defaults=i ) # ... I tried somethink like this and it's works try: vmwarepopulatevm(i) i.save() except Exception: pass But I want to create a generic function because I will have to use it more often -
AJAX call to Django View returns None to data
I have been trying to get data that I send using AJAX with a Django view. I have this AJAX call $.ajax({ method: "POST", url: "{% url 'change_publish_status' %}", value: {"company_id": company_id, "published": published}, dataType: 'json', headers: {"X-CSRFToken": '{{ csrf_token }}'} }); and I'd like to access the company_id and the published variables from the django view. I have tried many things self.request.POST.get('company_id') --> returns None self.request.POST.get('company_id', None) --> returns None self.request.body --> returns b'' This is my view right now @method_decorator(login_required, name='dispatch') class ChangePublishStatus(TemplateView): def post(self, *args, **kwargs): company_id = self.request.POST.get('company_id', None) published_status = self.request.POST.get('published') == "true" print(company_id) return JsonResponse({"status": "ok"}) def get(self, *args, **kwargs): return redirect("list") -
How instances of Django's generic view classes created?
I am trying to understand how Django works and here is one question. Say we have this simple CreateView: class ListCreate(CreateView): model = ToDoList fields = ['title'] def get_context_data(self, **kwargs): context = super(ListCreate, self).get_context_data() context['title'] = 'Add a new list' return context Now, as far as I know, you create an instance of a class by my_instance = MyClass(). Untill then the code that describes the MyClass is just a code. So my question is, at what point in time the instance of ListCreate() is created and what is the name of that instance? -
populate a field with the result of subtracting two other fields
i have the following model class FeeModel(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE,null=True) total_fee=models.IntegerField(default=100000) paid_fee=models.IntegerField() remaining_fee=models.IntegerField(default=0) i need the remaining_fee to be filled by the result of (total_fee - paid_fee). How would i do that? -
How to know wich page redirected to the login url with the @login_required decorator in django?
I have two page that need to be logued to be accessed, both of them redirect to the login url with the @login_required decorator @login_required def ask_question(request) @login_required def answer_question(request) and i would like to display a message on the login page that will be specific depending from the page that redirect to the login. Like : You need to be loggued to ask question (if the user came from the ask question redirection) You need to be loggued to answer question (if the user came from the answer redirection) Regards