Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest API - Get & Verify User ID by token
How to obtain User ID from Django API having authentication token? Basically, I want to send an authentication token and get back the User id. Basically I want to verify the company id that must be call by Django rest API! -
Django Question. How to I change default django-filter "---------" option to custom string?
This is kind of insignificant, but does anyone know how to change the default choice in a django-filter FilterSet from "---------" to any given string? I'd like to change it to "All" because all the options are displayed if "---------" is selected. Do I override init maybe? Thanks in advance. -
Git bash color formats are not working. Instead it prints the color code in terminal
When I was using git bash for flask development, it worked fine. But now I am learning Django and when I use git bash instead of show status in color it shows the color code around the status. Someone help me with this. here is the image of my terminal -
Creating custom 404 page in django is causing problems loading javascript files
I am handling 404 error using a custom "not found page". But doing that is causing that from that moment the templates are nou loading all the javascripts files and plugins. This is my code in urls.py handler404 = 'riesgo.views.views.error_404' in views/views.py def error_404(request, exception): data = {} return render(request, '404.html', data) I check the log and loading all js files is causing a 404 error -
Django: Why is my view not displaying to HTML
I'm new to django and trying to get my machine learning model to display recommendations for a logged in user. The current view is this: def my_view(request): username = None if request.User.is_authenticated(): username = request.User.username result3 = get_recommendation(username, n=10) return render(request,'test.html', {'result3':result3}) else: pass It searches for the currently logged in user, and passes their user id (their username) into the function to get a recommendation for that user, and attempts to impute the result onto a html test page (the user is already logged in to be accessing this test page). The test page itself looks like this: {% if user.is_authenticated %} {{ result3 }} {% endif %} Does anyone know what I'm doing wrong? -
How To Add Multiple Forms In CreateView
I'm making a restaurant project where an order can be filled with order items. I want to create more than one order item at a time but I haven't done that before, so I have no idea how to do it.There are examples of Formsets and Inline Formsets but only for function based views.So any help would be appreciated. Here Is my Forms.py class AddOrderItemForm(forms.ModelForm): total_cost = forms.FloatField(widget = forms.HiddenInput(), required=False) class Meta: model = Order_Items fields = ['order', 'food', 'food_size', 'quantity', 'total_cost',] widgets = { 'order' : forms.Select(attrs={'class':'form-select select2-hidden-accessible'}), 'food' : forms.Select(attrs={'class':'form-select select2-hidden-accessible'}), 'food_size' : forms.Select(attrs={'class':'form-select select2-hidden-accessible'}), 'quantity': forms.NumberInput(attrs={'class': 'form-control form-control-lg'}), } def clean(self): food_t = self.cleaned_data.get('food') food_size_t = self.cleaned_data.get('food_size') quantity = self.cleaned_data.get('quantity') food = Food.objects.get(turkmen = food_t) food_size = Food_Size.objects.get(turkmen = food_size_t,food = food) self.cleaned_data['total_cost'] = calculations.order_item_add(food,food_size,quantity) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['food_size'].queryset = Food_Size.objects.none() if 'food' in self.data: try: food = int(self.data.get('food')) self.fields['food_size'].queryset = Food_Size.objects.filter(food=food).order_by('turkmen') except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty City queryset elif self.instance.pk: self.fields['food_size'].queryset = self.instance.food.food_size_set.order_by('turkmen') And my CreateView: class AddOrderItemView(CreateView): model = Order_Items form_class = AddOrderItemForm template_name = 'order/add-order_item.html' success_url = '/menu/orders' def form_valid(self, form): form.instance.order = Order.objects.get(pk=self.kwargs['pk']) return super(AddOrderItemView, self).form_valid(form) -
How do I determine what "key path" arguments to provide to `prefetch_related` in Django?
Note: below, I am going to refer to the arguments supplied to prefetch_related as "key paths". I don't know if that's the best/correct term - so let me know if there's a better term to use and I will update the question. I created an advanced search page in django that searches any of a number of fields from 6 different tables (not all of which are single a direct foreign key path) and displays selected fields from all those tables in a results table. The "key paths" included are: msrun__sample msrun__sample__tissue msrun__sample__animal msrun__sample__animal__tracer_compound msrun__sample__animal__studies (Note: no fields are included in the search or display from the msrun model. That specific model class in this particular view only serves as a connection between the model classes involved in the view.) It makes a huge difference in the run time when I include a prefetch like: .prefetch_related("msrun__sample__animal__studies"), but I see no discernible difference when I include any additional prefetch "key paths". So I have a couple questions: Are there any downsides to including all of the "key paths"? (I only ask so that I can construct more views programmatically without having to store a single "prefetch path" - because I already … -
How to upload multiple images using django rest framework
I am new to django and django rest framework. I want want users to be able to post something on my web, similar to twitter. See the below model: class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) content = models.CharField(max_length=255) upload_date = models.DateField(auto_now_add=True) def __str__(self): return self.content class PostImage(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="images") image = models.ImageField(upload_to="images/") Now, as you can see user should be able to upload either text content, or images (single or multiple) or both. What I want: I want to receive data from the client side in the following format: data = { content: "Some text goes here", media: [images] } I have created the following serializer: class PostSerializer(serializers.ModelSerializer): media = serializers.ImageField() class Meta: model = Post fields = ('content', 'media') Please help me, I am unsure how to save those imgaes into database and refer to the post id. I am getting images as "bytes". -
How to Track View As YouTube Does?
Hi Everyone I Am Coding in Python & Would Like To Find Out How Does Someone Track Views Of A Video In A Post, In Python. As Youtube And TikTok Does? Any Feedback With Code Examples Would Be Greatly Appreciated. Preferably Coding In Python To Use In My Django Project -
why whene I run makemessages the locale repertoir still empty
I have some problems using the command django-admin makemessages -l es I'm running it but the locale repertory still empty and and there is not .po files generated on my locale repertory . I add this following code on my setting.py file: LOCALE_PATHS = [ os.path.join(BASE_DIR, 'locale') ] And: MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] I have gettext installed and I have created a repertory named locale on root of the project, I don't realy get the problem -
One Django app in a separate python package
Django==3.2.5 Please, have a look at the picture: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'clients', 'general', 'images', 'themes', 'omnibus', 'staticassets', 'categories', 'tags', 'articles', ] When I run this, I get: ModuleNotFoundError: No module named 'articles' It is predictable as Django doesn't know where to find the app. Then I tried like this: INSTALLED_APPS = [ 'dependencies.articles', ] No success. Here 'articles' is just an ordinary Django app like categouries or clients. But I'd like to move it to 'depencencies' package. Why? I'd like to organize the code structure like this for as personal preferences. If it is technically possible, please, help me cope with this problem. -
Using One Model inside another model in Django
I am Developing a E-commerce Application with Django So what I was thinking is getting the category of the Product in a separate Model and list them down in another using choice field in CharField. So Here is the code for this This is the model for getting the Categories from the user class ProjektCat(models.Model): id = models.AutoField(primary_key=True) Option_Name = models.CharField(max_length=50) Option_Number = models.IntegerField() Number_Visits = models.IntegerField(default=0) def __str__(self): return f'{self.Option_Name}' and here is the code to list those categories as a dropdown in the CharField class Software_And_Service(models.Model): id = models.AutoField(primary_key=True) Product_Name = models.CharField(max_length=100, default='') projectKats = ProjektCat.objects.all() choice = [] for i in projectKats: option = (i.Option_Number, i.Option_Name) choice.append(option) Cateogary = models.CharField( max_length=256, choices=choice) Price = models.IntegerField(default=0) Description = models.TextField(default='', max_length=5000) pub_date = models.DateField(auto_now_add=True, blank=True, null=True) image = models.URLField(default='') linkToDownload = models.URLField(default='') def __str__(self): return f'Projekt : {self.Product_Name}' But it's Showing me an Error that there is no such table in app_name.projektcat Is there is any solution for this?? -
Django Rest Framework CSRF protection not working
I am developing an Angular application with Django Rest Framework and I want to configure CSRF protection. However, I can not seem to trigger CSRF violations when doing any POST request to the backend (for testing purposes). I currently do not use CSRF protection. My settings.py: MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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' ] I configured my CORS headers such that: CORS_ALLOW_ALL_ORIGINS = True I do not use CSRF_TRUSTED_ORIGINS anywhere. Why is the CSRF protection not invoked? -
NoReverseMatch at /vistaprevia/pedidos/4/edit Reverse for 'editr' not found. 'editr' is not a valid view function or pattern name
I have a problem with an edit view in django 3.2 and python 3.9.2, the problem is when a get into the link EDITAR in my view, it throws me the error "NoReverseMatch at /vistaprevia/pedidos/4/edit" and says to me that "Reverse for 'editr' not found. 'editr' is not a valid view function or pattern name.", I cant found what is going on with the code. Here is my code Views.py from django.shortcuts import render, redirect, get_object_or_404 from django.views import generic from django.views.generic.edit import UpdateView from vistaprevia.models import Op from vistaprevia.forms import CargarFormOp, EditarFormOp#, EditarFormRem # Create your views here. from django.shortcuts import render from django.http import HttpResponse from django.template import RequestContext, loader app_name = 'vistaprevia' #VISTA QUE MUESTRA LOS ULTIMOS 10 PEDIDOS def index(request): ultimasop = Op.objects.all().order_by('-fecha') return render(request, 'vistaprevia/index.html', context={'ultimasop':ultimasop}) #DETALLE PEDIDOS class PedidoDetailView(generic.DetailView): model = Op #CARGA DE PEDIDOS, EMPIEZ LA ACCION, WIIIIIIIIII def cargar_pedido(request): if request.method=='POST': form = CargarFormOp(request.POST) if form.is_valid(): fecha = form.cleaned_data['fecha'] cliente = form.cleaned_data['cliente'] tipoop = form.cleaned_data['tipoop'] fact = form.cleaned_data['fact'] condicion = form.cleaned_data['condicion'] despacho = form.cleaned_data['despacho'] vendedor = form.cleaned_data['vendedor'] newdoc = Op(fecha=fecha, cliente=cliente, tipoop=tipoop,fact=fact, condicion=condicion, despacho=despacho ,vendedor=vendedor) newdoc.save() return redirect("index") else: form = CargarFormOp() return render(request, 'vistaprevia/formulario.html', {'form': form}) #AGREGAMOS TODO LO REFERETE AL … -
How to fix Django admin page error related to `__str___`
Had a None type error on the admin page because of an empty field (null=True) in the db table. Followed of of the answers here with return self.author or '' + self.post_title[:40] and fixed the error. Now how do I get both the author and title of post appear in the admin page. The previous (broken) code: return self.author + ', ' + self.post_title[:40], but once I add or '', the part following + stops working. -
OneToMany relationship between abstract modules Django
So I have an app, i've created only one module which is the customer module, and there are three other tables on that app that are created by django itself. The names of the tables are auth_user, auth_user_group, auth_group. Now I need to establish a one-to-many relationship between the first two, the thing is I'm not quite sure how to do that because there are no modules. Any ideas? -
ProgrammingError: SELECT COUNT(*) AS "__count" FROM "product"
I am using multiple databases in Django and connected default SQLite and PostgreSQL db in the settings.py. setting.py : DATABASE_ROUTERS = ['routers.db_routers.AppRouter'] DATABASE_APPS_MAPPING = {'product': 'postgres',} DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'postgres': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'product', 'USER': 'postgres', 'PASSWORD':'password', 'HOST':'localhost' } } And also made the db_routers.py in the routers folder: class AppRouter: """ A router to control all database operations on models in the product application. """ def db_for_read(self, model, **hints): """ Attempts to read user models go to postgres. """ if model._meta.app_label == 'product': return 'postgres' return 'default' def db_for_write(self, model, **hints): """ Attempts to write user models go to postgres. """ if model._meta.app_label == 'product': return 'postgres' return 'default' def allow_relation(self, obj1, obj2, **hints): """ Allow relations if a model in the user app is involved. """ if obj1._meta.app_label == 'product' or \ obj2._meta.app_label == 'product': return True elif 'product' not in [obj1._meta.app_label, obj2._meta.app_label]: return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): """ Make sure the auth app only appears in the 'product_db' database. """ if app_label == 'product': return db == 'postgres' return None here, it's model.py: class Product(models.Model): name = models.CharField(max_length=100) price = models.DecimalField(max_digits=10, decimal_places=2) … -
how to reactjs axios send request to django database (case: the database has foreignKey)
I am learning reactjs and django by making a blog but I have a question: how to post a request to server when the database has ForeignKey field ? Example: I am making the comment section Can someone help me to solve this ? Thanks for helping ! this is my code ! models.py class Article(models.Model): title = models.CharField(max_length = 116) content = models.TextField() user_token = models.TextField(null = True) def __str__(self): return self.title class Comment(models.Model): article = models.ForeignKey(Article, on_delete = models.CASCADE) user = models.CharField(max_length = 116, null = True) comment = models.TextField() def __str__(self): return self.comment -
Unable to implement websocket with Nginix and Daphne
I am trying to setup websockets on my django application using Daphne and Ngnix. On my local setup everything works as expected but when I have uploaded to the server the websockets do not respond. This is Nginx.conf file: user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; ## # SSL Settings ## ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; # gzip_vary on; # gzip_proxied any; # gzip_comp_level 6; # gzip_buffers 16 8k; # gzip_http_version 1.1; # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; ## # Virtual Host Configs ## include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; client_max_body_size 10M; } and this is my sites-available file which is accessed by Nginx: server { server_name 139.59.9.118 newadmin.aysle.tech; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/django/AysleServer/src; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } location /wss/ { proxy_pass … -
Is there a way to change the blank attribute on Django form fields to False by clicking a button?
I am building a review form that will post to a single model in my database. This form will have multiple sections, each with its own set of questions. I want the user to be able to complete a section and hit a submit button that will save the progress and redirect them to the next section. In essence I want to create an in progress status for the review with the idea that as all sections are finished the user can hit a complete button that will run my validation on the entire form. However, I do not want to allow posting information to the database that has not been cleaned. I've been thinking through this trying to work out what I need to do and believe the best bet would be to have a complete button on the last page that changes blank to False for the fields of the form. I believe this would allow me to fill out each form and post it to the database as all fields would start as optional but then for that specific model instance the click of the button at the end would institute a change making all fields required, … -
Django heroku server error after deployment
I have deployed my django app to heroku. All seems to be working fine locally but not when deployed with heroku. I keep getting a Server error 500 anytime i visit the site. Here is my views.py file def home_view(request): email = send_mail("Account confirmation mail", f"Click on the link to activate your account", settings.EMAIL_HOST_USER, ["******@gmail.com"]) return render(request, "email.html", context={}) here is what comes up in my heroku logs 2021-07-16T04:32:23.908455+00:00 heroku[web.1]: State changed from starting to up 2021-07-16T04:32:28.000000+00:00 app[api]: Build succeeded 2021-07-16T04:33:04.554487+00:00 heroku[router]: at=info method=GET path="/" host=polar-temple-25791.herokuapp.com request_id=c958793a-15d9-46f7-8594-30b075db4413 fwd="102.89.1.147" dyno=web.1 connect=0ms service=794ms status=500 bytes=403 protocol=https 2021-07-16T04:33:04.554965+00:00 app[web.1]: 10.93.205.135 - - [16/Jul/2021:04:33:04 +0000] "GET / HTTP/1.1" 500 145 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" 2021-07-16T04:33:05.957497+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=polar-temple-25791.herokuapp.com request_id=c0ea8a4f-2e94-4e1d-92e1-99eaca82bd82 fwd="102.89.1.147" dyno=web.1 connect=1ms service=103ms status=404 bytes=411 protocol=https 2021-07-16T04:33:05.957866+00:00 app[web.1]: 10.93.205.135 - - [16/Jul/2021:04:33:05 +0000] "GET /favicon.ico HTTP/1.1" 404 179 "https://polar-temple-25791.herokuapp.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" 2021-07-16T04:34:55.263334+00:00 app[api]: Starting process with command `python manage.py migrate` by user somtochukwuuchegbu@gmail.com 2021-07-16T04:35:05.664576+00:00 heroku[run.9367]: State changed from starting to up 2021-07-16T04:35:05.984898+00:00 heroku[run.9367]: Awaiting client 2021-07-16T04:35:06.005500+00:00 heroku[run.9367]: Starting process with command `python manage.py migrate` 2021-07-16T04:35:12.861556+00:00 heroku[run.9367]: Process exited with status 0 2021-07-16T04:35:13.111213+00:00 heroku[run.9367]: … -
How to send a list of json object in PUT request for non-primary ID in Django?
I am getting a PUT request which is having array of json objects for same non-primary ID. Example: { "some_non_pk_id":101, "user_entries":[ { "name":"foo", "height":1.56 }, { "name":"bar", "height":1.76 }, . . . ] } I need to upsert the object in a table which looks something like this +----+----------------+------+--------+ | id | some_non_pk_id | name | height | +----+----------------+------+--------+ | 1 | 101 | foo | 1.56 | | 2 | 101 | bar | 1.76 | +----+----------------+------+--------+ The url of the PUT/PATCHrequest will be/api/details/?some_non_pk_id=101. I am not sure how to override the updateorpartial_updateofModelViewSet` to upsert this. I am ok if the request body can be changed to something like this. Changing the request bosy is in my control. [ { "some_non_pk_id":101, "name":"foo", "height":1.56 }, { "some_non_pk_id":101, "name":"bar", "height":1.76 } ] -
Django generate many pages with a single view
my project consists of making a library with different categories of books. for each category of book I made as many views. I would like to know if for all the existing categories I can make a single view. For example here instead of three views I want only one view to manage all categories views.py def mathematics(request): mathematics_books = Books.objects.filter(category_id=1) total_mathematics_books = mathematics_books.count() page = request.GET.get('page', 1) paginator = Paginator(mathematics_books, 5) try: page_obj = paginator.page(page) except PageNotAnInteger: page_obj = paginator.page(1) except EmptyPage: page_obj = paginator.page(paginator.num_pages) context = { 'total_mathematics_books': total_mathematics_books, 'page_obj': page_obj, } return render(request, 'mathematics.html',context) def biology(request): biology_books = Books.objects.filter(category_id=2) total_biology_books = biology_books.count() page = request.GET.get('page', 1) paginator = Paginator(biology_books, 5) try: page_obj = paginator.page(page) except PageNotAnInteger: page_obj = paginator.page(1) except EmptyPage: page_obj = paginator.page(paginator.num_pages) context = { 'total_biology_books': total_biology_books, 'page_obj': page_obj, } return render(request, 'biology.html',context) def chemistry(request): chemistry_books = Books.objects.filter(category_id=3) total_chemistry_books = chemistry_books.count() page = request.GET.get('page', 1) paginator = Paginator(chemistry_books, 5) try: page_obj = paginator.page(page) except PageNotAnInteger: page_obj = paginator.page(1) except EmptyPage: page_obj = paginator.page(paginator.num_pages) context = { 'total_chemistry_books': total_chemistry_books, 'page_obj': page_obj, } return render(request, 'chemistry.html',context) models.py class Categories(models.Model): name = models.CharField(max_length=250) description = models.TextField(blank=True) def __str__(self): return self.name class Authors(models.Model): name = models.CharField(max_length=250) biography = models.TextField(blank=True) … -
Creating HTML Modal for number of items in database
I am creating a donation application where users can view donations. If they want to learn more about a specific donation, they can click on the view button and an HTML overlay menu will come up. My problem is that I use a for loop to display every donation, and there is no specific number of donations, there can be infinite number of donations, and the view button only works for the first donation. How can I fix this so the view button can work for every donation? My code is down bellow {% extends 'suppliesbase.html' %} {% load static %} {% block content %} <div class="row"> {% for donation in donations %} <div class="col-lg-4"> <img class="thumbnail" src="{{donation.imageURL}}"> <div class="box-element product"> <h6><strong>{{donation.title}}</strong></h6> <hr> <button class="btn btn-outline-success" id="open-modal-button" href="#">View</button> <h4 style="display: inline-block; float: right"><strong>Free!</strong></h4> </div> </div> {% endfor %} </div> <!--Modal Overlay Content --> <div id="modal-overlay"> <div id="modal"> <div class="head"> <a id="close-modal-button" href="javascript:;"></a> </div> <div class="content">Modal content</div> </div> </div> <script> var openModalButton = document.getElementById("open-modal-button"); var closeModalButton = document.getElementById("close-modal-button"); var modalOverlay = document.getElementById("modal-overlay"); var modal = document.getElementById("modal"); // function that open modal and display the overlay openModalButton.addEventListener("click", event => { modalOverlay.classList.add("modal-overlay-visible"); modal.classList.add("modal-visible"); }); // function that closes the modal and remove the … -
adding multiple items to cart using a checkbox in the table
I want to include products from store page, to cart. On the shop page I have a table where there are checkboxes in the last column. when I select a checkbox in the header of the table, all checkboxes on that page are highlighted. At the end of the page there is a button that sends all selected products to the cart like this: enter image description here How can i do this?