Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Objects looping in JavaScript
i want to loop over a object and manipulate it in JavaScript file but i am not able to get these object in JavaScript file although i can loop them if they are in html . But cannot do that in separate JavaScript file -
Django queryset NameError
Just started learning python and using sublime text. trying to run a queryset but getting a NameError. from the error, it seems the table which is in the models.py is not being picked up. the code in models.py shown in screenshot the error im getting is - name 'Stock' is not defined im trying to get the queryset to run such that i can get a list of items from the Stock table models code class Stock(models.Model): category = models.CharField(max_length=50, blank=True, null=True) item_name = models.CharField(max_length=50, blank=True, null=True) view code def list_item(request): title = 'List of list_item' queryset = Stock.objects.all() the error im getting is from the line with queryset -
ForeignKey Field replaced with text input, but not validating in form
I am working on a project that involves some foreign key fields but i converted them to text inputs in a form. I plan to use datalist to display some choices from the foreign keys but users can still input new data in the input field. The problem now is that the form is being submitted but the data isn't validating Here's the code models.py class Todo(models.Model): title = models.CharField(max_length=250) completed = models.BooleanField(default=False) due_date = models.DateTimeField(blank=True) created = models.DateTimeField(auto_now_add=True) tags = models.ManyToManyField(Tag, blank=True) goal = models.ForeignKey( Goal, on_delete=models.SET_DEFAULT, default='', blank=True) context = models.ForeignKey( Context, on_delete=models.SET_DEFAULT, default='', blank=True) project = models.ForeignKey( 'Project', blank=True, on_delete=models.CASCADE,default='') status = models.CharField(choices=status_types, max_length=250, blank=True) priority = models.CharField( choices=priority_types, max_length=250, blank=True, default='none') place = models.CharField(max_length=250, blank=True) def __str__(self): return self.title add_task.html <h5>Add Task</h5> <br><br> <form action="{% url 'todos:add_task' %}" method="POST" id="add-task-form"> {% csrf_token %} {% if form.error %} <p class="alert">{{form.error}}</p> {% endif %} {% for field in form %} {% if field == form.tags %} <div class="form-group row"> <div class="col"> {{field.label_tag}} </div> <div class="col"> {{field}} <datalist id="taglist"> {% for tag in tags %} <option value="{{tag}}"></option> {% endfor %} </datalist> </div> </div> {% elif field == form.context %} <div class="form-group row"> <div class="col"> {{field.label_tag}} </div> <div class="col"> {{field}} … -
DRF list endoint returns 404 while there are objects present in db
There's some problem when I'm trying to retrieve a list of objects. Here is my code (I've reduced it for simplicity) # Models.py class TournamentType(models.Model): name = models.CharField(max_length=255) # Serializers.py class TournamentTypeSerializer(serializers.ModelSerializer): class Meta: model = models.TournamentType fields = ('id', 'name') # Views.py class TournamentTypeViewSet(ReadOnlyModelViewSet): queryset = TournamentType.objects.all() serializer_class = serializers.TournamentTypeSerializer In Swagger I end up seeing 2 request types: http://localhost:8000/api/tournaments/time_control/{id} http://localhost:8000/api/tournaments/time_control/ First one (with ID) returns object as expected. But the second one, which is supposed to return a list, returns a 404 response. I've tried specifying a request type by adding this to the view: def list(self, request): queryset = TournamentType.objects.all() serializer = serializers.TournamentTypeSerializer(queryset, many=True) return Response(serializer.data) But result is still the same. What am I missing? I've checked all the docs, and everything seems to be in place. -
what __str__ is doing in the below code????The two code listed are different
We are creating a python django model.What is the use of __str__below? What str is actually returning and where? Sample code 1 from django.db import models from django.contrib.auth.models import User # Create your models here. class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) image = models.FileField(upload_to='profile_pics', blank=True,default='default.jpg') def __str__(self): return self.user.username+ " Profile" Sample code 2 from django.db import models from django.contrib.auth.models import User # Create your models here. class Article(models.Model): title = models.CharField(max_length=100) body = models.TextField() date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title -
ValueError at /newspaperapp/category/sports/ : Field 'id' expected a number but got 'sports'
I am creating categories for news. I am trying to filter the news category wise but getting a value error models.py class category(models.Model): title=models.CharField(max_length = 200) category_image = models.ImageField(upload_to="imgs") def __str__(self): return self.title class newsmodel_1(models.Model): category = models.ForeignKey(category,on_delete=models.CASCADE) title = models.CharField(max_length = 50 , null=False,blank=False) date_published = models.DateTimeField(auto_now_add=True) #details = models.TextField() details = RichTextUploadingField(blank=True,null= True) slug = models.SlugField(blank=True,unique=True) def slug(self): return slugify(self.date_published) this is views.py def index(request): cats=category.objects.all() return render(request,'newspaperapp/index.html',{'cats':cats}) class nowlist(ListView): model = newsmodel_1 template_name = 'newspaperapp/index.html' class newslist(DetailView): model = newsmodel_1 template_name = 'newspaperapp/home.html' context_object_name = 'newspaperapp' class SearchView(ListView): model = newsmodel_1 template_name = 'newspaperapp/search.html' context_object_name = 'all_search_results' def get_queryset(self): result = super(SearchView, self).get_queryset() query = self.request.GET.get('search') # query is of type 'str', convert to datetime start_day = datetime.fromisoformat(query) end_day = start_day + timedelta(days=1) if query: postresult = newsmodel_1.objects.filter( date_published__gte=start_day, date_published__lt=end_day ) result = postresult else: result = None return result def full_news(request): return render(request,'newspaperapp/full-news.html') def CategoryView(request,cats): category_posts = newsmodel_1.objects.filter(category = cats) return render(request,"newspaperapp/categories.html",{'cats':cats,'category_posts':category_posts}) this is urls.py urlpatterns = [ path('',views.index,name='index'), path('date/',nowlist.as_view(),name = "date"), path('<int:pk>',newslist.as_view(),name = "home"), path('results/', SearchView.as_view(), name='search'), path('full_news/',views.full_news,name = "full_news"), path('category/<str:cats>/',views.CategoryView,name='category'), ] categories.html <h1>{{cats}} category</h1> <ul> {%for post in category_posts%} <h3><a href="{%url 'newspaperapp:home' newspaperapp.pk %}">{{ newspaperapp.title}} {{newspaperapp.category}}</a></h3> {% endfor %} index.html {% for cat in … -
Change auto increment id to last without django ORM
i want refresh auto increment order_id from between rows to next of last row in database layer without Django ORM. my order_id field is integer and it's auto increment in MySQL for example i have 1, 2, 3, 4, 5 and i want update order_id from 3 to 6 id without get last order_id with Django ORM. is it possible? my model is like this: class Order(models.Model): order_id = models.BigIntegerField(unique=True) -
when I change urlconfig,images does not load in django
when I change urlconf my images are not load in the page. this code is when the images are loaded in the page,"urls.py" urlpatterns = [ path('admin/', admin.site.urls), path('<lang>/', home_page), path('', home_redirect), path('products/', include('products.urls')), path('', include('agents.urls')), path('', include('information.urls')), path('', include('media_app.urls')), ] in this code when the images are not loaded urlpatterns = [ path('admin/', admin.site.urls), path('<lang>/', home_page), path('', home_redirect), path('<lang>/products/', include('products.urls')), path('<lang>/', include('agents.urls')), path('<lang>/', include('information.urls')), path('<lang>/', include('media_app.urls')), ] I have no idea for solve it... -
Django:MEDIA_ROOT error : _getfullpathname: path should be string, bytes or os.PathLike, not tuple
I am new to Django Framework.I am trying to upload image to the customer table and this error occurs _getfullpathname: path should be string, bytes or os.PathLike,. I am using this code to upload MEDIA_ROOT = [BASE_DIR, 'static/images'].I change the code to MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images'), but,it says NameError: name 'os' not defined..what's the reason for the errors and how solve it? settings.py STATIC_URL = '/static/' MEDIA = '/images/' STATICFILES_DIRS = [BASE_DIR, 'static'] MEDIA_ROOT = [BASE_DIR, 'static/images'] models.py class Customer(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=11, null=True) email = models.EmailField(max_length=200, null=True) profile_pic = models.ImageField(null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) -
WSGI apache Unsupported Media Type error in custom http request
I am using Django to receive request from an AVR. I uses an custom http POST request containing some byte. I receive data and store successfully to my database when I use manage.py runserver. But when I WSGI in apache (WSGIDaemonProcess) I get this error: [wsgi:error] [pid 5080] [remote 222.157.163.133:4773] Unsupported Media Type: /api/micro/data How can I fix it? -
Django: app displays 400 error when deployed on server
Actually I have two problem here.I have one vps(bare minimum for testing) on which I have 2-3 apps.I have just deployed another app on it & got a free domain name from freenom.com.I use supervisor+nginx for hosting the app.For no reason I am getting this Bad Request (400) when I visit the domain.Generally this occurs when you don't put the the domain name in the ALLOWED_HOSTS list but I have set this up. The second problem is that I have DEBUG = True still it's just displaying the bare minimum error response instead of full stack trace hence I am not sure what errors I am actually getting & unable to debug it. No error logs in the gunicorn-error.log file. No error logs in the nginx-error.log file. No error logs in the nginx-access.log file. My gunicorn_start config #!/bin/bash NAME="hrms_app" DIR=/home/kunsab/projects/hrms_venv/hrms USER=kunsab GROUP=kunsab WORKERS=3 BIND=127.0.0.1:8081 DJANGO_SETTINGS_MODULE=hrms.settings DJANGO_WSGI_MODULE=hrms.wsgi LOG_LEVEL=error cd $DIR source ../bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DIR:$PYTHONPATH exec ../bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $WORKERS \ --user=$USER \ --group=$GROUP \ --bind=$BIND \ --log-level=$LOG_LEVEL \ --log-file=- supervisor config: [program:hrms_app] command=/home/kunsab/projects/hrms_venv/bin/gunicorn_start user=kunsab autostart=true autorestart=true redirect_stderr=true stdout_logfile=/home/kunsab/projects/hrms_venv/logs/gunicorn-error.log settings.py """ Django settings for hrms project. Generated by 'django-admin startproject' using Django 3.1.3. For more information … -
How to load only active data in Django Forms
I have a model that is referenced to my Profile by ForeignKey. During registration, I want to load this model that is active only. My Profile model: residence_status = models.ForeignKey("residencestatus.ResidenceStatus", verbose_name="ResidenceStatus", related_name="Profile", on_delete=models.CASCADE) My Residence Status Model: is_active = models.BooleanField(default=False, null=False) Created a separate py file to get the residence status and return as an object(Since there are a lot of models like this) def get_residence_status(): resObjs = ResidenceStatus.objects.all().filter(is_active=True) return resObjs Then on my forms, load it all on choices: class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = "__all__" def __init__(self, *args, **kwargs): RESIDENCE_STATUS_CHOICE = {} resObj = get_residence_status() for x in resObj: print(x) RESIDENCE_STATUS_CHOICE['id'] = x super().__init__(*args, **kwargs) self.fields['residence_status'] = forms.ChoiceField(choices=RESIDENCE_STATUS_CHOICE) On my terminal, the result if print(x) and print(RESIDENCE_STATUS_CHOICES) are as follows: 特になし {'id': <ResidenceStatus: 特になし>} 特定技能外国人 {'id': <ResidenceStatus: 特定技能外国人>} '高度人材 {'id': <ResidenceStatus: '高度人材>} その他 {'id': <ResidenceStatus: その他>} However, the return on my template(select) is only "d" -
How to write a condition use django queryset
I write a if else statement to user but it not working. I get data form database use Post.objects.get(sno = delpk). Then i writer a condition request.user.username == Post.author def postdelapi(request): if request.method == 'POST': delpk = request.POST['delpk'] deletepost = Post.objects.get(sno = delpk) print(Post.author) if request.user.username == Post.author : deletepost.delete() else: HttpResponse('eroor') else: pass return redirect('home') -
Wishlist functionality in Django
I am trying to implement wish list functionality My requirement is In my website I have deals page, coupons page, promotions page. For deals page I have some list of products for each product it has on fav icon. If user clicks on fav icon it has drop down list by default deals and then create new list two columns and if user choose deals that product added to deals list. or else if user clicks on create new list user will create some list then that product added that new list. By list wise we have to shown in wish list template page. How can i achieve this please any one can help to achieve this thank you. -
Django How to user FormSet with ListView
I'm trying to use modelformset_factory with ListView to Update multiple rows in the model. It works fine just subclassing the FormView, but I would like to pagenate it. -
How to access a txt file in django via url for verification purposes
I have purchased an SSL certificate and I used an HTTP validation method where I need to store a text file under my server. I am supposed to store is as http://eblossom.lk/.well-known/pki-validation/ECB7.txt. I am hosting through Linode(Ubuntu) using apache2. However, for some reason, my website cannot access the folder and gives me an error saying that the URL is invalid. I know for a fact that if I type something like http://eblossom.lk/static/style.css, my static file appears, similarly, I need to allow my SSL certificate provider to get access to my .txt file the same way by. Note: FOLDER NAME CANNOT BE CHANGED I am sure something should be done with the settings.py file to allow access to open that folder, but I am not sure how. Any ideas? Thanks! -
Multiply input values into other input
I want to multiply numbers and the result shows in another input. I managed to obtain the value of each input with the following code, but from here I do not know how to advance and make it multiply and that the result is shown in the input of the "total". This is part of the code: $(` [name='unidadTrabajosFactura'], [name='precioUniTrabajoFactura'], [name='totalTrabajoFactura'] `).each( function(index, item){ var valores = $(item).val(); console.log(valores) }); in the console I get the following results: What I want to achieve is that the quantity value is multiplied by the unit price and show the result in in input of total An this is my form code <div class="job-form row mb-3"> <div class="col-md-1"> <label for="unidadTrabajosFactura" class="">Unidad</label> <input type="text" name="unidadTrabajosFactura" class="form-control" value="{{trabajo.unidad}}"> </div> <div class="col-md-5"> <label for="descTrabajosFactura" class="">Descripción</label> <input type="text" name="descTrabajosFactura" maxlength="200" class="form-control" value="{{trabajo.trabajo}}"> </div> <div class="col-md-2"> <label for="precioUniTrabajoFactura" class="">Precio Unitario</label> <input type="text" name="precioUniTrabajoFactura" class="form-control" value="{{trabajo.precio_unitario}}"> </div> <div class="col-md-2"> <label for="totalTrabajoFactura" class="">Total</label> <input type="text" name="totalTrabajoFactura" class="form-control" value="{{trabajo.total}}"> </div> These fields can be multiple as well as one Regards -
Filter the data generated from DB - Django
How to limit the generated list from database? I have a model that references to other models via ForeignKey. class ApplicantAccount: sns_name = models.ForeignKey("sns_names.SnsNames", verbose_name="SnsNames", related_name="ApplicantAccount", on_delete=models.CASCADE) With this line, all of the list inside SNS would be displayed in template. However, in my SNS model, I have added a boolean field is_active. I just want to render only the active SNS. How to do this? At first, I created a py file that would handle all the generated list like this: models: def get_sns(): # Get all active SNS Names snsObjs = SnsNames.objects.all().filter(is_active=True) return snsObjs Then on view, pass it to context then render it to template view.py: snsObjs = get_sns() context['snsObjs'] = snsObjs return render(request, 'forms/reg_form.html', context) But on my template, it displays everything. I just found out that even if I remove the code from views.py, snsObjs = get_sns() context['snsObjs'] = snsObjs it still generates all the list. -
Updating template with a form through context or fetch
I'm on a project and i need a way to get a django form as a response to a fetch request or maybe to re-render my template with the context dictionary updated with the form in it. I want to add the form to a modal box when the button is clicked. Thanks guys -
Trouble loading static files in Nginx + Digital Ocean Deployment
Django Beginner here.. Having some trouble loading my static files during final deployment on a Digital Ocean Droplet I'm using Nginx and Gunicorn. I've followed a tutorial from Traversy Media, but I can not get my static files to show up in the browser via my Digital Ocean ipv4. Upon inspecting it is throwing these multiple errors. Refused to apply style from 'http://162.243.162.127/btre/static/css/all.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. GET 162.243.162.127/:510 GET http://162.243.162.127/btre/static/js/bootstrap.bundle.min.js net::ERR_ABORTED 404 (Not Found) Here are my nginx settings server { listen 80; server_name 162.243.162.127; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/djangoadmin/pyapps/realestate_project; } location /media/ { root /home/djangoadmin/pyapps/realestate_project; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } Here are my gunicorn settings [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=djangoadmin Group=www-data WorkingDirectory=/home/djangoadmin/pyapps/realestate_project ExecStart=/home/djangoadmin/pyapps/venv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ btre.wsgi:application [Install] WantedBy=multi-user.target I've tried running collectstatic in the terminal multiple times but it does not do anything.. Says it has '0 to collect'. -
Python re-write jupyter notebook to python script problem
I have a very simple RNN model which I can execute on Jupyter notebook without any problem, now I want to embed this model in my Django project, so I downloaded the .ipynb file then saved it as .py file, then I just put it in my Django project. However, the first problem is VSCode says I have unresolved import 'MLutils, the MLutils is my utility file in the same folder. The second problem is if I just run this file, I'll get this error RuntimeError: cannot perform reduction function argmax on a tensor with no elements because the operation does not have an identity but if I use the Run Cell Above button of the VSCode, I'll get the correct result. The code I want to run is this, called MLTrain.py import torch import torch.nn as nn import matplotlib.pyplot as plt from MLutils import ALL_LETTERS, N_LETTERS from MLutils import load_data, letter_to_tensor, line_to_tensor, random_training_example class RNN(nn.Module): # implement RNN from scratch rather than using nn.RNN # # number of possible letters, hidden size, categories number def __init__(self, input_size, hidden_size, output_size): super(RNN, self).__init__() self.hidden_size = hidden_size #Define 2 different liner layers self.i2h = nn.Linear(input_size + hidden_size, hidden_size) self.i2o = nn.Linear(input_size + … -
Get first instance for each group in a model
So I love django but I keep bumping my head into the same or similar problem. That is, I have a model A with a FK to another model B, and I want the first model A instance for each model B. For example, I have the following models: class Room(models.Model): name = models.CharField(primary_key=True, max_length=16, blank=False) class Event(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE, blank=False) start = models.DateTimeField(blank=False) end = models.DateTimeField(blank=False) (...) It's basically, each Room has Events which have a start and end time. I want to get the next Event for each Room considering now - Q(start__gt=datetime.now()) I've tried a lot of things, I don't say everything because I have little experience with django.db.models.functions and I don't if that's way For reference, what I want to do in SQL is: SELECT * FROM api_event WHERE start > VAR_NOW GROUP BY room_id; Which returns this: +----+----------------------------+----------------------------+---------+-------------+ | id | start | end | room_id | course_id | +----+----------------------------+----------------------------+---------+-------------+ | 1 | 2020-10-15 15:30:00.000000 | 2020-10-15 17:00:00.000000 | 0-14 | DDRS14 | | 17 | 2020-10-13 15:30:00.000000 | 2020-10-13 17:00:00.000000 | 0-21 | DDRS14 | | 26 | 2020-10-16 12:30:00.000000 | 2020-10-16 14:00:00.000000 | 0-27 | CGJ7 | | 39 | 2020-10-14 … -
How to join tables from models that are not directly related
The title is kinda weird (sorry, I did not have any other idea on how to ask my question clearly) but let me explain it better here with an example, it will be more understandable. Lets start with the models: class A(): # Abstract class field_a = models.IntegerField(default=0) class B(A): # Inherit fields from A field_b = models.TextField(blank=False, null=False) class C(A): # Inherit fields from A + foreign key on B field_c = models.TextField(blank=False, null=False) foreign_key_to_b = models.ForeignKey("B", blank=False, null=False) class D(): # model with foreign key on A and B but not inheriting from A field_d = models.TextField(blank=False, null=False) foreign_key_to_a = models.ForeignKey("A", blank=False, null=False) foreign_key_to_b = models.ForeignKey("B", blank=False, null=False) And this is, in SQL, what I am trying to achieve: SELECT c.* FROM C c INNER JOIN B b ON b.id = c.foreign_key_to_b INNER JOIN D d part ON d.foreign_key_to_b = b.id WHERE d.foreign_key_to_a = 10 I am trying to get all C, depending on a condition on a field of D. To do so, I join D to B then B to C and get the fields I need. Since D has a foreign key to A, the object this foreign key is pointing to, can be one … -
Django. Non-ascii field doesn't create slug. I expect to get transliteration, but getting an empty field and error
I have simple Model with title and slug fields. I want to accept non-Latin characters as a title and transliterate them into Latin slug. Specifically, I want to transliterate Cyrillic characters, say 'Привет, мир!' into Latin 'privet-mir'. Instead of slug I'm getting following error: Reverse for 'blog_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['blog/(?P[-a-zA-Z0-9_]+)/$'] Django Version: 3.1.5 Python Version: 3.9.1 Exception Type: NoReverseMatch Exception Value: Reverse for 'blog_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['blog/(?P<slug>[-a-zA-Z0-9_]+)/$'] Model from django.db import models from django.template.defaultfilters import slugify class Post(models.Model): title = models.CharField(max_length=70) slug = models.SlugField(null=False, unique=True, allow_unicode=True) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) return super().save(*args, **kwargs) def __str__(self): return self.title admin.py from django.contrib import admin from .models import Post class PostAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('title',)} admin.site.register(Post, PostAdmin) urls.py from django.urls import path from . import views app_name = 'blog' urlpatterns = [ path('', views.BlogList.as_view( template_name=app_name + "/blog_list.html"), name='blog_list'), path('<slug:slug>/', views.BlogDetail.as_view( template_name=app_name + "/blog_detail.html"), name='blog_detail'), ] views.py from .models import Post from django.views.generic import ListView, DetailView class BlogList(ListView): model = Post class BlogDetail(DetailView): model = Post blog_list.html (for each post) <a href="{% url 'blog:blog_detail' blog.slug %}">{{ blog.title }}</a> blog_detail.html (short) <h1>{{ blog.title }}</h1> NoReverseMatch at /blog/ -
Learning django but i get an error in a simple poll app
I'm trying to learn django from scratch. So I found a tutorial online:Tutorial simple poll app and I followed it and it just replies: in the terminal: Not Found: /polls/ [30/Jan/2021 00:12:39] "GET /polls/ HTTP/1.1" 404 1957 On the http://localhost:8000/polls/ web page: Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ The current path, polls/, didn't match any of these. I went over all the syntax and it all matches up. please help me I don't know how to solve this probleme