Django and Python "Questions and answers", page 3

09.02.2023
Single model instances on separate html

What is a best way to display single model instances on different html? I know how it is done on single page (forloop), but could not figure out how the same would be possible on different html. i.e. single question …

09.02.2023
Remote DRF Auth and handle payload with JWT

I have auth_service, tpm_api and frontend enviroments. All services use the same secret_key. My users and permissions are on the auth_service. I am using jwt_simple for Authentication on auth_service. On the frontend service, I get token from auth_service with username …

09.02.2023
Django FileSystemStorage does not save anything to media folder

I'm working on a Django backend deployed on a server, here's my settings: DEBUG = False STATIC_URL = "/staticfiles/" STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, "media") And I want to save the users' images outside …

09.02.2023
Adding image for blog posts

Coding some kind of blog with django, and I can't make homepage to contain images of the articles... It just doesn't upload a image... my Views.py : class AddPostView(CreateView): model = Post form_class = PostForm template_name = 'add_post.html' my …

09.02.2023
Rest api detail User Not Found code user not found Error postman

I am generating a token for each logged in user. But on Get request through postman i am getting this error. please guide me what's wrong ! postman error screenshot my models.py class allmodelfields(AbstractBaseUser): USERNAME_FIELD = …

09.02.2023
Django Rest api Update View form can't update single attribute

I have created an Employee CRUD in Django REST using generic views. when update view page is loaded I couldn't find the current values in the fields. so I can't update a single value. when i update a single value …

09.02.2023
Session expires while switching to another app.route in flask

Session expires when the '/mobile-confirmation' app.route runs and the user redirects to login page @app.route("/signup", methods=["GET", "POST"]) def signup(): if request.method == "POST": #SignUp form Insert codes ...... db.execute("SELECT tempcode FROM users WHERE id = %s", [userID]) tmpcode = db.fetchall() …

09.02.2023
Django - how to retrieve data from two models (at the same time) related with OneToOne relation?

In Django I have two models: class Car(models.Model): model_name = CharField(...) make_name = CharField(...) car_exterior_color= = CharField( CHOICES ) class CarWash(models.Model): car_washed = BooleanField(...) wash_date = DateTimeField(...) added_wax = BooleanField(...) car = models.OneToOneField(Car, on_delete=models.CASCADE, verbose_name="Car washed") I need to …

09.02.2023
Hi, i want add search bar to myproject but don't return anything

This view for search: class Search(generic.ListView): model = Blog template_name = 'pages/blog_list_view.html' context_object_name = 'blog' def get_queryset(self): search = self.request.GET.get("q") search_result = Blog.objects.filter( Q(title__icontains=search) | Q(description__icontains=search) | Q(active=True)) return search_result search form in _base.html <form action="{% url 'search' %}" …

09.02.2023
Writing a tuple search with Django ORM

I'm trying to write a search based on tuples with the Django ORM syntax. The final sql statement should look something like: SELECT * FROM mytable WHERE (field_a,field_b) IN ((1,2),(3,4)); I know I can achieve this in django using …

09.02.2023
Can i make an stackedInline connnection between two model without having any connection between them ? in Django

Class Item(models.Model): name=models.CharField(max_length=250) description = model.TextField() class Photo(models.Model): item = models.ChaField(max_length=250) title=models.ChaField(max_length=250) here is admin.py class PhotoInline(admin.StackedInline): model = Photo class ItemAdmin(admin.ModelAdmin): inlines = [PhotoInline] admin.site.register(Item,strong text ItemAdmin) admin.site.register(Photo) i want to have an inline connection between without …

09.02.2023
(Django model) How does this Message model works?

So I am following a Youtube video on how to create a chatting app. Then it build a model that I don't understand. Here's the Message model I came across and can't understand how it works. class Message(models.Model): user = …

09.02.2023
Getting ERROR "You must provide at least one recurring price in `subscription` mode when using prices."

Hello I am beginner in Django while trying to create Subscription with stripe i am getting error as InvalidRequestError at /stripe/create-checkout-session Request req_M2eko0H9LwXvDz: You must provide at least one recurring price in subscription mode when using prices. This is my …

09.02.2023
How to add reference Parameters in extend_schema decorator in drf-spectacular

I'm using drf-spectacular to generate the swagger/redoc API documentation. I am facing issue in customising the schemas generated. I am trying to generate reference parameter using @extend_schema decorators in drf_spectacular but did'nt get the expected schema. extend_schema …

09.02.2023
I am getting 405 error for get method in my django api, instead, i want a default message for get method

For django API, which we have written, post method is allowed but instead of get method, i am getting 405 error, but instead i want some default message like- "error". I am sharing my code. Please let me know if …

09.02.2023
How change database's port dynamically(django)

I have a django project that it should have ability to change the database's port dynamically for security reasons. for example there should be a template like ( port= ) and the administrator should enter a port and change the …

09.02.2023
500 error on django channels send message to group

I have the following Django channels consumer but when I try to send data to the stocks group، it returns a 500 error. Also, I don't get any error logs. Here is the consumer: class AuthRequiredConsumer(JsonWebsocketConsumer): def connect(self): user = …

09.02.2023
Does Django save model objects other than `save()` or `create()` methods?

I'm writing something like the following: class Foo(models.Model): a = models.CharField() def f(foo: Foo) -> Foo: y = Foo( **{field.name: getattr(foo, field.name) for field in foo._meta.get_fields()} ) # copy foo with pk y.a = "c" return y …

09.02.2023
In Django's auth contrib module, how do I correctly return an error when overriding the asswordResetConfirmView view?

I'm using Django 3 and the auth contrib module. I want to override the reset password procedure via an API and so I have a method that looks like this .... class CompleteResetPasswordView(PasswordResetConfirmView): @method_decorator(csrf_exempt) def dispatch(self, request): body = json.loads(request.body) …

09.02.2023
Django static url setting is not working in production

I have uploaded stsatic files to Cloudflare R2 with python manage.py collectstatic command, and checked files are there. Also, allowed public access for the R2 bucket. I have these in my settings.py file for static related: STATIC_HOST = …

09.02.2023
Filtering multicheckbox on datable

I have a problem with my code, i try to make a datable with multiple checkbox filter on Django environement. i have tried multiple code, but for now, i have this code, for each collumn there is a list and …

09.02.2023
Django's remove_stale_contenttypes command fails with DoesNotExist error

I recently tried to run remove_stale_contenttypes in a Django 3.1 app, after deleting some custom permissions. The first time it run it warned me that some entries would be deleted, and I went ahead and entered 'yes'. The command failed …

09.02.2023
Django MPTT, can't get parent_id for threaded comments reply

My Problems are as follows: Im relatively new to Django. so sorry for this mess. I've tried to implement threaded comments to my blog via MPTT. But when i pressing the 'Reply' Button django throws me a Type Error Normal …

09.02.2023
Django Filter using Q Objects on two Models

I am working a Django Application where I want to search two Models Profile (surname or othernames fields) and Account (account_number field) using Q objects. From what I did, it is searching only one Model (Account) and any attempt to …

09.02.2023
How to fix search function in Django?

I have a page with the list of objects. I need a search function, but there is an error. I am in process of studying and I used from . import views and the search function worked, but then I …

09.02.2023
CKEDITOR PillowBackend Django disable thumbnail creation

By default, when inserting an image from the clipboard into the CKEDITOR editor, the images are saved in PNG format and take up a lot of disk space. I have enabled PillowBackend to be able to save images in JPG …

09.02.2023
Creating a team of users with jobs

I want to make a model where users can create a team of users, and in these teams add the job that they did and choose recipient of the job(that is the member of this team) that they did it …

09.02.2023
Django - only call <a href="{% url 'view'%}"> when clicked

In my web page i have a for loop that displays multiple &lt;a&gt; tags. When one of the &lt;a&gt; tags is clicked the user will be redirected to another url. My problem is that all of the href=&quot;{% url 'search' …

08.02.2023
Django form request is always response with "GET" instead of "POST" even when I use <form action="" method="post">

Please help me m looking since hours for the solution but i didnt find something. Here is my HTML: &lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;title&gt;Title&lt;/title&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/css/bootstrap.min.css&quot; integrity=&quot;sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T&quot; crossorigin=&quot;anonymous&quot;&gt; &lt;style&gt; input { width: 10%; margin: 0 auto; …

08.02.2023
I am using Django to create and update an Text area I want to save my updated textarea after clicking Insert

I am using Django to create and update an Text area. After putting a text that have variables between {}, I want to change them using button variable. So when I click on variable it will show me all the …

08.02.2023
Docker nginx django gunicorn 502 bad gateway

I am a beginner in the docker I want deploy my django project on hostinger.com vps so I am using docker nginx and gunicorn for this I dockrized my django project a test it on the localhost every thing is …

08.02.2023
Django ORM: How to round down (truncate) a query number?

I'm working with sensitive currency values. In my case, i have to reproduce a sheet with it's formulas. The point is that i need to round down a currency value with 2 decimal places. A practical example is the number: …

08.02.2023
How to create a new csv from a csv that separated cell

I created a function for convert the csv. The main topic is: get a csv file like: ,features,corr_dropped,var_dropped,uv_dropped 0,AghEnt,False,False,False and I want to conver it to an another csv file: …

08.02.2023
How to prevent the page scrolling back to the top after clicking on a button?

I have a small form on django, when the button is clicked it display a django message bellow the form to tell the user that he successfully clicked on the button but it redirect the user in the top of …

08.02.2023
Django - special query or another field holding Boolean data to get view from multiple models

I have few models, but right now I want to focus on two: class Client(models.Model): first_name last_name car # Client's car to be serviced class Service(models.Model): service_name service_type service_date client = models.OneToOneField(Client, on_delete=models.CASCADE, verbose_name=&quot;Client served&quot;) def __str__(): return f&quot;Client {self.client} …

08.02.2023
The ability to like/vote posts from the post list

I have a problem. I made likes to the posts on the video from YouTube. It is possible to like a post only from post_detail view and it's works correctly! How to make it possible to like posts in the …

08.02.2023
Page not found (404) No Booking matches the given query - Django web application

I am having trouble figuring out where my issue is. I am parsing a slug to the url, via my view pulling from the SlugField in my model. For an object instance that exists in my database, the slug is …

08.02.2023
Mutation in django graphene for model with foreign key and many to many relationship

I have 2 models in my django app, the first is Tags model and the second is Post model, the problem is when i try to use mutation for the Post model to add a post from the graphql it …

08.02.2023
How to render update element (graph) with HTMX if two (2) elements (selector) have new value?

I have an element - dropdown list selector. Which works and there is a choice of value. Based on the value received, I send a request to execute the code and, at the end, to change / render another element …

08.02.2023
IntegrityError at /clinic_management/patients/1/medhistory/ NOT NULL constraint failed: clinic_management_medical_history.patient_id

I'm trying to create an app which stores medical records of patients. I'm trying to get information about the patient but I have encountered a problem. When it comes to posting the medical history I receive the following error: &quot;IntegrityError …