Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to collect the pk of the model that you are currently viewing (django)
hey I'm trying to make a question and answer project for django, how do I get the pk of the question that I am viewing right now to send an answer? I already set it up so that the url of the answer has /answer/pk of the question but I dont know how to get that info so the code knows where to post the model, how do I do that? also here is my code, thanks! views: class AnswerForm(SuccessMessageMixin, CreateView): template_name = 'forum/answer-question.html' model = Answer form_class = AnswerForm success_message = 'Success!' def form_valid(self, form, pk=None): form.instance.question_id = Question.objects.only('id') form.instance.user = self.request.user form.save() return super().form_valid(form) forms: class AnswerForm(ModelForm): class Meta: model = Answer fields = ['detail'] exclude = ('user', 'add_time') urls: from django.urls import path from . import views urlpatterns = [ path('questions/', views.QuestionsView.as_view(), name='questions'), path('ask/', views.AskForm.as_view(), name='ask'), path('answer/', views.AnswerForm.as_view(), name='answer'), path('answer/<pk>', views.AnswerForm.as_view(), name='answer_with_pk'), path('question/<pk>', views.QuestionDetailView.as_view(), name='detail'), path('save-text', views.WriteCommentAnswerView.as_view(), name='save-text'), path('save-vote', views.SaveVoteView.as_view(), name='save-vote'), ] models: class Answer(VoteModel, models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) detail = models.TextField() add_time = models.DateTimeField(auto_now_add=True) def get_absolute_url(self): return f"/questions/" def __str__(self): return self.detail -
Django Queryset with multiple joins and filtering
I need a list of jobs joined with houses joined with owners Results row should contain: job_id, job_worker_role1, job_worker_role2, job_worker_role3, house_id, *owner_name, owner_status_name, owner_assigned_user Given that there is a many to many relationship between houses and owners it is acceptable to have multiple result rows for each job, with each owner. class Worker: name = models.CharField() class OwnerStatus: name = models.CharField() class Owner: name = models.CharField() status = models.ForeignKey(OwnerStatus, related_name='owners') assigned_worker = models.ForeignKey(Worker, related_name='assigned_user_owner') class House: owners = models.ManyToManyField(Owner, related_name='assets') class Job: house = models.ForeignKey(House, related_name='jobs') worker_role1 = models.ForeignKey(Worker) worker_role2 = models.ForeignKey(Worker) worker_role3 = models.ForeignKey(Worker) updated_at = models.DateTimeField(auto_now=True) Also, I need to filter by: owner status name or owner status id owner name as string owner assigned worker name as string I am using Django 4.0.1 with postgres -
How to fully test Django ImportMixin via excel
I have an admin model that uses django-import-export via an excel file typically. I want to test it as thoroughly as I can. I can test the file format & headers should be as expected, as well as the widgets used by the resource that controls the import validation. However, I do some changes to the data when its saved & imported, I can't figure out how to test that with the below method or via selenium since it involves an excel file. Tips? I would just like to test that when we import via excel, the things I do in the resource take effect, namely I upload users & add them to groups, but the test method below only tests the dataset is properly setup, it doesn't create any records. I also use Selenium to test user functionality, but didn't find how I could mimic an excel file. from import_export.admin import ImportMixin class CustomUserAdmin(ImportMixin, UserAdmin): # this resource controls the custom checks for the import mixin resource_class = UserResource A snippet of the resource I use, uses several widgets to control validation class UserResource(resources.ModelResource): id = fields.Field(column_name='id', attribute='id') # only here to keep the id on the left, preference … -
Whats wrong with my search string? I am not getting proper data
I want to implement search on my django project. On my following queryset, with else condition its passing correct data. But with if condition whatever I search, it shows nothing. def get_queryset(self): category = self.request.GET['category'] query = self.request.GET['q'] if category == 'all': products = Products.objects.filter(Q(name__icontains=query) | Q(category__name__icontains=query)).all() else: products = Products.objects.filter(Q(category__slug=category), Q(category__slug__icontains=self.request.GET['q']) | Q(name__icontains=self.request.GET['q'])) -
Django Admin Login Form
How do I change the login form used by django admin (want to add a captcha field)? I am using the cookiecutter template and have followed the suggestions in other SO answers, and guides: forms.py class AuthAdminForm(AuthenticationForm): captcha = ReCaptchaField(widget=ReCaptchaV3) show_something_different = forms.TextInput() class Meta(AuthenticationForm): fields = ('email', 'password', 'show_something_different', 'captcha') urls.py from django.contrib import admin from myapp.forms import AuthAdminForm admin.autodiscover() admin.site.login_form = AuthAdminForm admin.site.login_template = 'admin/login.html' urlpatterns = [ # Django Admin, use {% url 'admin:index' %} path(settings.ADMIN_URL, admin.site.urls), ...] I was able to add admin/login.html to my templates dir and extend it. This works to add the google js to the header (can see it in source). But the captcha field and my dummy extra field don't show up. -
How do I make the QuerySet filter use an overloaded comparison operator?
I have a model with a OneToOneField pointing to a parameter model. The latter overloads the python comparison operators, such as <. models.py: class SomeComplexParameter(models.Model): fid = models.UUIDField(primary_key=True, default=uuid.uuid4) value = models.PositiveIntegerField(default=10) def __lt__(self, other): return self.value < other.value class SomeModel(models.Model): ... param = models.OneToOneField(SomeComplexParameter,on_delete=models.CASCADE, null=True) ... When I try to filter SomeModel querysets by chaining param__lt, the overloaded __lt__ method does not get invoked! For example: If I define a threshold SomeComplexParameter instance p_threshold = SomeComplexParameter.objects.create(value=30) and filter SomeModel querysets using SomeModel.objects.filter(param__lt=p_threshold) it returns random set of SomeModel instances each time. What I tried so far: print(SomeModel.objects.filter(param__lt=p_threshold).query) yields SELECT "bricks_somemodel"."fid", "bricks_somemodel"."param_id" FROM "bricks_somemodel" WHERE "bricks_somemodel"."param_id" < 68e1c73401c5412bb91f4cb75ce57e8e which points to the fact that Django isn't using the overloaded operator. Instead it's comparing the uuids (pk for this model). This explains the randomness! I checked that SomeModel.objects.filter(param__value__lt=30) filters correctly, as it uses the native python < operator. But this won't be an option for me, as I must use the overloaded __lt__ method on SomeComplexParameter. Is there some way to configure my models so that filtering with param__lt=p_threshold uses the overridden __lt__ operator? Version info: Django 3.2.13, Python 3.9.0, sqlite -
Static file doesn't exist
output: 'static' in the STATICFILESDIRS setting does not exist. I've tried os.path.join(BASE_DIR, '/static'), but it is doesn't work. I didn't have this problem before adding new html-file and I didn't change static-folder. Setting.py STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / 'static' ] -
Error Iteration with Django in template two variables in same time
I want to iterate two lists in one loop, and I am getting this error. <ul> {% for protein, ligand in protein_list, ligand_list %} <li> {{protein, ligand}} </li> {% endfor %} </ul> Error during template rendering In template C:\Users\Narsil\dev\django-project\templates\RMSD\main.html, error at line 10 'for' statements should use the format 'for x in y': for protein, ligand in protein_list, ligand_list -
How can I make my Navigation Bar responsive?
I am working on a web-development project. I can not make my Navigation Bar responsive for mobile devices. For desktop, the navigation bar looks right, for mobile devices it is not working. I referred How can I make my navbar responsive? and https://getbootstrap.com/docs/5.1/components/navbar/. I was able to partially make it responsive but the search bar and dropdown menu disappeared from my navBar if I viewed it on a mobile. Here is my original code: {% load static %} <header class="section-header" style="text-align:center;padding:10px;font-weight: 600;position:sticky;top:0;z-index:999; background-color: #000; margin: -40px;"> <section class="header-main"> <div class="container"> <div class="row align-items-center"> <div class="col-lg-2 col-md-3 col-6"> <a href="{% url 'home' %}" class="logo" style="color: #fff; font-weight: 700; font-size: 2em; text-decoration: none;">Py<span style="color: #e7315a;">Tech</span></a> </div> <div class="col-lg col-sm col-md col-6 flex-grow-0"> <div class="category-wrap dropdown d-inline-block float-right"> <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown"> <i class="fa fa-bars"></i> All category </button> <div class="dropdown-menu"> <a class="dropdown-item" href="{% url 'store' %}">All Products </a> {% for category in links %} <a class="dropdown-item" href="{{ category.get_url }}">{{ category.category_name }} </a> {% endfor %} </div> </div> <!-- category-wrap.// --> </div> <!-- col.// --> <a href="{% url 'store' %}" class="btn btn-outline-primary">Store</a> <div class="col-lg col-md-6 col-sm-12 col"> <form action="{% url 'search' %}" class="search" method='GET'> <div class="input-group w-100"> <input type="text" class="form-control" style="width:60%;" placeholder="Search" … -
How to use action attribute in form correctly
<form action="/contact-us/done"> <input type="submit" name="submit" class="btn btn-primary pull-right" value="Submit"> </form> I want to go to the link in action attribute after i submit, but it not work. Do i misunderstand something? Please help me, thanks!! -
List products in relation to the vendor clicked in django ecommerce
I have listed all the vendors (users which are staff) in my django tempelate using the following code. In tempelates: {% for stf in staff %} <li><a href="{% url 'vendor_products' %}">{{stf.username}}</a></li> {% endfor %} In views: def vendor_products(request): vend_prod = Product.objects.filter(user_id=request.user.id) context={ 'vend_prod': vend_prod } return render(request, "vendor_products.html", context) The usernames of the suppliers(vendors) is already listed. What I want is the products of the respective vendor will be dispalyed in a separate html page when the vendor username is clicked. Now the above code is displaying just the products of the user who is logged in. Here is the products model incase it is needed. class Product(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField(max_length=150) keywords = models.CharField(max_length=255) description = models.TextField(max_length=255) image = models.ImageField(null=False, upload_to='images/') price = models.DecimalField(max_digits=12, decimal_places=2,default=0) amount = models.IntegerField(default=0) detail = RichTextUploadingField() Thank you in advance! -
How to display Predictive model graph on Django framework?
I've made a predictive model using LSTM which predicts future prices for raw materials like cotton,fibre,yarn etc. At the end of code I used matplotlib library to plot graph which displays the original prices, predicted prices and future predicted prices. This is the graph which shows future prices according to dates How do I display this graph on Django framework? Because I need to deploy this model on a web application using Django but the tutorials I've seen so far show predictive models which take user input and don't really show anything related to plots or graphs. Following is the code: import numpy as np import pandas as pd import matplotlib.pyplot as plt import datetime as dt from datetime import datetime import warnings warnings.simplefilter(action='ignore', category=FutureWarning) from keras.callbacks import EarlyStopping, ReduceLROnPlateau, ModelCheckpoint, TensorBoard import os import glob import pandas import numpy from sklearn import preprocessing import numpy as np # Importing Training Set dataset_train = pd.read_csv('201222-yarn-market-price-china--034.csv1.csv') dataset_train.info() # Select features (columns) to be involved intro training and predictions cols = list(dataset_train)[1:5] # Extract dates (will be used in visualization) datelist_train = list(dataset_train.iloc[0]) datelist_train = [dt.datetime.strptime(date, '%m/%d/%Y').date() for date in datelist_train] print('Training set shape == {}'.format(dataset_train.shape)) print('All timestamps == {}'.format(len(datelist_train))) print('Featured selected: … -
'course_custom_tags' is not a registered tag library. Must be one of:
I am trying to add templatetags in using django, but i get this error after creating the template tags, i don't know if there is something i need to change in my settings.py to make this work. template.html {% extends 'base/base.html' %} {% load static %} {% load course_custom_tags %} {% block content %} course_custom_tags.py from course.models import UserCourse , Course register = template.Library() @register.simple_tag def is_enrolled(request , course): user = None if not request.user.is_authenticated: return False # i you are enrooled in this course you can watch every video user = request.user try: user_course = UserCourse.objects.get(user = user , course = course) return True except: return False ```[![enter image description here][1]][1] [1]: https://i.stack.imgur.com/39yyT.jpg -
Python Django 'HTTPSConnection' object has no attribute 'rfind''HTTPSConnection' object has no attribute 'rfind'
I'm trying to connect an url for a payment system but I am getting this error: 'HTTPSConnection' object has no attribute 'rfind'. I checked and connection is good. url is sandbox-api.iyzipay.com and here is my code: iyzicoApiKey = data2['iyzicoApiKey'] iyzicoSecretKey = data2['iyzicoSecretKey'] url = data2['url'] options = { 'api_key': iyzicoApiKey, 'secret_key': iyzicoSecretKey, 'base_url': connection } connection = httplib.HTTPSConnection(url) request = dict([('locale', 'tr')]) request['conversationId'] = '123456789' request['subMerchantExternalId'] = subMerchantExternalId request['subMerchantType'] = 'PRIVATE_COMPANY' request['address'] = address request['taxOffice'] = taxOffice request['legalCompanyTitle'] = legalCompanyTitle request['email'] = email request['gsmNumber'] = gsmNumber request['name'] = name request['iban'] = iban request['identityNumber'] = identityNumber request['currency'] = 'TRY' sub_merchant = iyzipay.SubMerchant() sub_merchant_response = sub_merchant.create(request, options) I have tried to search but I couldn't find any info about HTTPSConnection and rfind error. Thanks in advance. -
Does django rest framework query all objects from database for a single instance?
When working with RetrieveAPIView queryset must be defined and usually it is defined as queryset = <Model>.objects.all() Why does retrieving a single instance require loading all the objects? -
I am trying to set up the environment for Django, but facing the following errors. Can someone please help me out in complete set up process of django
Fatal error in launcher: Unable to create process using '"c:\python39\python.exe" "C:\Python39\Scripts\pip.exe" install virtualenv': The system cannot find the file specified. -
on click event with JavaScript doesn't work in Django
this is the code for (cart.js) in the static/js folder var updateBtns = document.getElementsByClassName('update-cart') for (i = 0; i < updateBtns.length; i++) { updateBtns[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId:', productId, 'Action:', action) }) } and in the HTML file in the bottom: <button data-product="{{ product.id }}" data-action="add" class="update-cart btn btn-outline-secondary add-btn ">Add to Cart</button> and call the js in main.html <script type="text/javascript" src="{% static 'js/cart.js' %}"> </script> and I add static in the setting.py, and everything correct. and everything working well, when I try to (console.log) without a button click event... the problem is only with the button event because it doesn't work -
form.is_valid() always returns false perhaps issue with "This field is required" error
I am learning django. I am stuck with this problem. The problem is that form.is_valid() always returns false. I tried to debug and I think that the problem is because of "This field is required" error and I think that the field is file_name. I tried to resolve the issue but I am unable to do so. Just to give a context of what I am trying to do - I have created a form in which a user uploads a text file and selects a gender. In the backend I want to save the name of the text file along with the gender in a model. The purpose of doing this is because when multiple users will use the application, I should know which user selected what gender so that I can produce the desired output. Here is the link to my git repository - git repository As I already said I am new to django and some help will be appreciated. -
Why is my Django session not storing keys correctly when path converter is used in URLconf?
I'm working on the basket app of my eCommerce project and stumbled upon this error that I cannot figure out. When a user adds an item to the basket, it should store the product id and quantity in a dictionary. The quantity should be incremented if the user adds more of the same item. I've noticed that when I specify an 'int' path converter in the URLconf that this doesn't behave as expected. The second time a user adds another amount of the same item, instead of it incrementing the current value, it instead adds another key of type string to the dictionary. Form to accept desired quantity: <form action="{% url 'add_to_basket' product.id %}" method="POST"> {% csrf_token %} <div class="row justify-content-center"> <div class="col-10 col-md text-md-end"> <label class="col-form-label" for="qty_input_{{ product.id }}">Quantity:</label> </div> <div class="col-10 col-md"> <input name="quantity" type="number" class="form-control" value="1" min="1" max="99" id="qty_input_{{ product.id }}"> </div> <div class="col-10 col-md mt-2 mt-md-0"> <input type="submit" class="btn bg-red btn-outline-dark border-0" value="Add to Basket"> </div> <input type="hidden" name="redirect_url" value="{{ request.path }}"> </div> </form> View: def add_to_basket(request, product_id): if request.method == 'POST': quantity = int(request.POST['quantity']) basket = request.session.get('basket', {}) url = request.POST['redirect_url'] if product_id in basket: basket[product_id] += quantity else: basket[product_id] = quantity request.session['basket'] = basket … -
Read uploaded fasta file in django using Bio library
in index.html I used <input type="file" name="upload_file"> in views.py from Bio import SeqIO def index(request): if request.method == "POST": try: text_file = request.FILES['upload_file'] list_1, list_2 = sequence_extract_fasta(text_file) context = {'files': text_file} return render(request, 'new.html', context) except: text_file = '' context = {'files': text_file} return render(request, 'index.html') def sequence_extract_fasta(fasta_files): # Defining empty list for the Fasta id and fasta sequence variables fasta_id = [] fasta_seq = [] # opening a given fasta file using the file path with open(fasta_files, 'r') as fasta_file: print("pass") # extracting multiple data in single fasta file using biopython for record in SeqIO.parse(fasta_file, 'fasta'): # (file handle, file format) print(record.seq) # appending extracted fasta data to empty lists variables fasta_seq.append(record.seq) fasta_id.append(record.id) # returning fasta_id and fasta sequence to both call_compare_fasta and call_reference_fasta return fasta_id, fasta_seq The method sequence_extract_fasta(fasta_files) work with python. But not on the Django framework. If I can find the temporary location of the uploaded file then using the path, I may be able to call the method. Is there any efficient way to solve this? your help is highly appreciated. Thank you for your time. -
How to unit test "if request.user.is_superuser:" and "if request.method == 'POST':" using unittest framework
I've a view which is add_product. So, now I want to unit test this view using python unittest framework. In my add_product function I'm checking that if user is a superuser and if the request.method == 'POST' how can I do this? views.py def add_product(request): if request.user.is_superuser: if request.method == 'POST': product_name = request.POST['product_name'] product_category = request.POST['product_category'] product_price = request.POST['product_price'] product_photo = request.FILES['product_photo'] product_description = request.POST['product_description'] add_product = Product(product_name = product_name, category = product_category, price = product_price, description = product_description, pub_date = datetime.today(), image = product_photo) add_product.save() return render(request, 'home/home.html') else: return HttpResponse("404-Not Found") else: return render(request, 'html_view_with_error', {"error" : "PERMISSION DENIED"}) here is my try so far test_views def test_add_product(self): product = Product.objects.create( product_id = 16, product_name = "Mango", category = "Fruit", price = 350, description = "Fresh Mangoes", pub_date = "2022-02-18", ) client = Client() response = client.get(reverse('home')) self.assertEquals(response.status_code, 200) self.assertEqual(str(product), "Mango") -
IntegrityError - Exception Value: null value in column "username_id" of relation "post_comment" violates not-null constraint
I'm building out a comments section for the post app and I'm coming across this error that I can't resolve. This is arising once I submit the comment.body with the form loaded in the views. If possible I would like the authenticated user to be assigned to the username of the comment model as well as the date_added. models.py class Comment(models.Model): post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE) username = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self) -> str: return f"{self.post.title} - {self.username}" def get_absolute_url(self): return reverse("new-comment", kwargs={"slug": self.post.slug}) forms.py class NewCommentForm(forms.ModelForm): class Meta: model = Comment fields = [ "body" ] views.py def add_comment(request,slug): if request.method == "POST": form = NewCommentForm(request.POST, request.FILES) if form.is_valid(): form.instance.post_slug = {'slug': slug} form.save() messages.success(request, "Your comment was added successfully.") return redirect("food-feed") messages.info( request, "There was an problem trying to add your comment.", ) form = NewCommentForm() return render(request, "post/new_comment.html", {"new_comment_form": form}) views.py path("post/<slug:slug>/new-comment", views.add_comment, name="new-comment") -
Django ForeignKey как заменить выпадающий список на простое поле для ввода в админ панели?
Всем привет. Я новичок в Django и уже дня 4 пытаюсь найти как заменить выпадающий список ForeignKey на обычное поле для ввода в админ панели. Дело в том что, у меня если будет очень много записей о заказчиках, то создавать новые записи о заказах в админ панели будет очень не удобно через выпадающий список, а так же, мне не нужно, чтобы другим админам были видны данные о заказчиках (их номера), поэтому решил поискать информацию о замене с выпадающего списка на простое поле для ввода (в котором будут проверятся данные, существует данный заказчик или нет). Очень сильно надеюсь, что правильно описал свою проблему. Заранее спасибо!!! -
Heroku permanent database - Django project [duplicate]
I have uploaded my Django project on Heroku, However, all inserted data in my database, after being uploaded will be deleted after a while. do you have any ideas on how to have a permanent database? or any other free hosts to deploy a Django project? -
React unable to find html document while using Django Backend
I am trying to configure a react frontend with a django backend and everything is fine, it complies, it loads etc. The issue i am facing is that my react component is unable to find the actual index.html document Uncaught ReferenceError: root is not defined my react app is constructed the standard way in ./src/components/App.js //proper imports up here {react, reactDOM} export default function App(){ return ( <h1>hello world</h1> ) } root = reactDOM.createroot(document.getElementById('root)) root.render(<App />) In my index.js located in .src/index.js import App from './components/App.js' and my webpack config file points to this index.js file Yes, I have ensured there is a div with an id of root in my boilerplate HTML The django backend compiles fine, and using webpack/babel things seem to be fine on that end. Bu that error is what pops up in the chrome console upon loading. The urls and views are properly set up and any html/css I add to the page displays as expected Thank you in advance