Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
some fields aren't being saved in django-models
am inserting new records in a model using a function-based view but the problem is some fields aren't being saved. I get all fields through request.POST.get(field_name) and them asssign to a varible before saving them to corresponding field in a particular model. ------- start of View ------- if request.method == "POST": st_exam = exam() topic = request.POST.get("topic") auth = request.POST.get("author") date_now = request.POST.get("date_now") st_exam.topic = request.POST.get("topic") st_exam.auth = request.POST.get("author") st_exam.date = date_now st_exam.total_grade = request.POST.get("total_grade") st_exam.semester_id = request.POST.get("semester") st_exam.exam_id = auth[0:2] + topic[0:2] + date_now # st_exam.course = request.POST.get("course") y = datetime.now() st_exam.semester_id = str(y.year) +'-'+request.POST.get("semester") st_exam.save() return redirect('/teacher/') else: return render(request, '500.html', {"error": "Ooops Illegal access"}) ------end of view---- ------start of model ---- exam_id = models.CharField(max_length=40,null=True) date = models.CharField(max_length=40,null=True) total_grade = models.FloatField(null=True) author= models.CharField(max_length=40,null=True) topic = models.CharField(max_length=40,null=True) course = models.CharField(max_length=40,null=True) semester_id = models.CharField(max_length=40,null=True) -----end of model---- -----start of html---- <form method="post" action="/teacher/create/exam/"> {% csrf_token %} <div class="form-group col-md-8"> <label for="topic">Topic</label> <input type="text" name="topic" class="form-control" id="topic"/> </div> <div class="form-group col-md-8"> <label for="grade">Author</label> <input type="text" name="author" class="form-control" id="author"/> </div> <div class="form-group col-md-8"> <label for="date">Date</label> <input type="date" name="date_now" class="form-control" id="date"/> </div> <div class="form-group col-md-8"> <label for="grade">Course</label> <input type="text" name="course" class="form-control" id="grade"/> </div> <div class="form-group col-md-8"> <label for="grade">grade</label> <input type="number" name="total_grade" class="form-control" id="grade"/> … -
How to set foreign key to a field of another model?
I want to set a foreign key to a field of another model. I have tried Foreign Key to_field='field_name' class Banks(models.Model): name = models.TextField() id = models.IntegerField(unique=True) class Meta: db_table = 'banks' class Branches(models.Model): ifsc = models.CharField(max_length=20, null=False) bank_id = models.ForeignKey(Banks, to_field='id', on_delete=models.CASCADE) branch = models.CharField(max_length=50)``` ProgrammingError: column branches.id does not exist LINE 1: SELECT "branches"."id", "branches"."ifsc", "branches"."bank_... -
Unit tests project with multiple application and databases - Circular dependency in TEST[DEPENDENCIES]
So I've got a django project with several applications. Each application use its own database, and they share a common database containing django tables (such as auth, sessions). For this I've got several database routers, so my settings looks like this : DATABASES = { 'default': { .. }, 'app1_db': { .. }, 'app2_db':{ .. } } DATABASE_ROUTERS = ["site.db_router.App1Router", "site.db_router.App2Router"] # no router for default database Each application also got its unit tests. To troubleshoot my problem I extracted one of the application. It contains a tests module with four test files. Test file number one looks like below: class ExcelTestCase(TransactionTestCase): databases = ["app1_db"] # some tests Test case 1 python manage.py test app1.tests.testfile1 raises this error django.core.exceptions.ImproperlyConfigured: Circular dependency in TEST[DEPENDENCIES] Test case 2 I comment the databases section : only default test database is created (not the application one) and this error is raised: AssertionError: Database queries to 'app1_db' are not allowed in this test. Add 'app1_db' to app1.tests.testfile1.ExcelTestCase.databases to ensure proper test isolation and silence this fai lure. Test case 3 I uncomment databases setting and run python manage.py test app1.tests so every test are runned. Three test files out of four are TransactionTestCase and therefore … -
Djoser with DRF Error username field is required
I am using djoser with django rest framework , and i want to remove the username field from the create user form so i did that this so far settings.py 'SERIALIZERS':{ 'user_create': 'user.serializers.UserRegistrationSerializer', }, serializers.py class UserRegistrationSerializer(BaseUserRegistrationSerializer): class Meta(BaseUserRegistrationSerializer.Meta): fields = ('email', 'password') Error TypeError at /auth/users/create create_user() missing 1 required positional argument: 'username -
Linkedin oAuth2 raises a value error, email required, Django
I am using LinkedIn OAuth in a Django app but not fetching an email address so it raises an email address error in the app. It is set in settings.py as follows: SOCIAL_AUTH_LINKEDIN_OAUTH2_SCOPE = ['r_basicprofile', 'r_emailaddress',] SOCIAL_AUTH_LINKEDIN_OAUTH2_FIELD_SELECTORS = ['email-address', 'formatted-name', 'public-profile-url', 'picture-url'] SOCIAL_AUTH_LINKEDIN_OAUTH2_EXTRA_DATA = [ ('id', 'id'), ('firstName', 'first_name'), ('lastName', 'last_name'), ('emailAddress', 'email_address'), ('pictureUrl', 'picture_url'), ('publicProfileUrl', 'profile_url'), ] What's missing here? -
Is there an effcient way to perform search query in django?
I'm creating a blog in which i want to perform a search query based on ones rating (1-5). Here my search would be like query:"smart phone tech updates", rating:"3". Result should be list of post that contains query word(at least one word) which has rating 3. My models.py file has the following : class Post(models.Model): title = models.CharField(max_length=50) content = models.CharField(max_length=500) rating = models.IntegerField(default=1) enter code here date = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) My view.py file has the following: def search(request): contents = Post.objects.all() if request.method == 'GET': query = request.GET['query'] rating = request.GET['rating'] # search function # contents = InSearch.search_fun(contents,query,rating) vector = SearchVector('title', weight='A') + SearchVector('content', weight='B') qry = SearchQuery(str(query)) contents = Post.objects.annotate(rank=SearchRank(vector, qry)).order_by('-rank') #print("---->\n\t"+query+ str(contents)) context = { 'contents': contents } else: context = { 'contents': Post.objects.all() } return render(request, 'feed/home.html', context) My urls.py is: urlpatterns = [ #... path('feed/search-result/', views.search, name='feed_search'), ] I'm getting this error django.db.utils.OperationalError: no such function: plainto_tsquery -
Django invalid literal for int() with base 10: 'PK' Error
I have a ListView which gives me a list of houses from the db. I'm using a form to make these houses and it works fine. But as soon as I use an attribute I get an error, which I'm not sure why occurs. The idea is that the user enters data by selecting his city from a drop down. I'm using django-cities_light to get it and works great. But i'm unable to render from database if I call the cities_light related FK in the template. error Template error: In template C:\Users\Bitswits 3\Desktop\Maala\MaalaWeddings\hallfiles\templates\hallfiles\hall_list.html, error at line 199 invalid literal for int() with base 10: 'PK' 189 : <li> 190 : <time datetime="2014-07-20"> 191 : <span class="day">{{ object.hall_capacity }}</span> 192 : <span class="month">Persons Capacity</span> 193 : </time> 194 : <div class="info"> 195 : 196 : <h4> Name: {{ object.hall_name }}</h4> 197 : <p class="desc"><b>Address:</b> {{ object.hall_address }}</p> 198 : <p class="desc">{{ object.hall_address }}</p> 199 : <p class="desc"> {{ object.hall_city }} </p> 200 : </div> 201 : </li> 202 : 203 : </ul> 204 : </div> 205 : </div> 206 : </div> 207 : 208 : 209 : Traceback: File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\core\handlers\base.py" in _get_response 217. … -
Not able to display image in django
files of whole project I have correctly setup path for media url and still not able to find images in allproducts.html where as in categories.html it is able to find images from media directory. I am not able understand the cause of this bug. allproducts.html {% for sub in subcategory %} {% for p in sub.product_set.all %} <div class="product"> <div><h3 class="logo header_content d-flex flex-row align-items-center justify-content-start">{{sub.name}}</h3></div> <div class="product_image"><img src="media/{{p.image}}" alt=""></div> <div class="product_content"> <div class="product_title"><a href="/shop/product/{{p.id}}">{{p.name}}</a></div> <div class="product_price">{{p.price}}</div> </div> </div> {% endfor %} <div></div> {% endfor %} settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ STATIC_DIR, ] MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' urls.py urlpatterns = [ path('',views.index, name="index"), path('cart',views.cart, name="cart"), path('categories',views.categories, name="categories"), path('checkout',views.checkout, name="checkout"), path('contact',views.contact, name="contact"), path('product/<int:pk>/',views.product, name="product"), path('allproducts/<int:pk>/', views.allproducts, name="allproduct"), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py def allproducts(request, pk): products = Product.objects.all() category = Category.objects.get(pk=pk) subcategory = Subcategory.objects.filter(category = category) return render(request, 'shop/allproducts.html', {'products':products, 'subcategory':subcategory, 'category':category}) project files kh kh .idea __init__.py settings.py urls.py wsgi.py media shop images test.jpg shop db.sqlite3 manage.py -
How to assign different Datepicker data to different rows within a for loop in HTML?
There is this projects i am on currently. Under date column i pass start and end date and store it in db along with the progress i.e dev, cr fix,etc. What i am trying to do is make a page where the story listed below the user name has its own progress date picker for example: if i have to assign mark on his story aggregator a progress. Then i will select start and end date and along with the progress and then click submit. I want this to be updated with its specific color in the check datepicker. The check datepicker is only for displaying the progress of the user under the current story. Every user and each of its story can have different progress. What i did for the same is took the start and end date for the story, its id and its progress and stored it in the db. Then i passed the developer name, id, start and end date and progress from controller to the script of the datepicker using json. The problem is that every datepicker is showing the combined progress of all stories and users. Please help me out for the same. I … -
How to decode base64 encoded query params in Django Rest Framework?
I am using Django Rest Framework quite extensively. The version I am on now is v3.7.7 I am researching on how to handle query params when they exceed the 2000 character limit and I found this suggestion about using base64 encoding. https://softwareengineering.stackexchange.com/a/353105/16777 I like to know how to use Django Rest Framework's native code to handle the base64 encoding of the query params if possible. -
Can django be used for deploying Apache spark machine learning as a web application?
We want to develop an application which helps in machine learning prediction using Apache Spark. We are planning to develop in Python. Hence, can we use Django to deploy this application? -
How can I pass current logged in user while form submission in django?
I am trying to create a form that allows current logged in user to submit data. The form comprises of the field - amount, rate(interest), timestamp(automatically picked up), and currently logged in user. Data is not passing into the database and giving an error like - The view investors.views.InvestView didn't return an HttpResponse object. It returned None instead. views.py def InvestView(request): if request.method == 'GET': investment_form = InvestorsForm(request.user) context = {'investment_form': investment_form} return render(request, 'investors/form.html', context) if request.method == 'POST': investment_form = InvestorsForm(request.POST or None, instance=request.user) if investment_form.is_valid(): amount = investment_form.cleaned_data['amount'] interest = investment_form.cleaned_data['rate'] saving = investment_form.save(commit=False) # Passing Logged in user investor = request.user print(investor) saving.investor = request.user.id saving.save() messages.success(request, f'New Investment Done!') return redirect('/myinvest/') forms.py class InvestorsForm(forms.ModelForm): class Meta : model = Investment fields = ['amount', 'rate'] def __init__(self, user, *args, **kwargs): self.user = user super(InvestorsForm, self).__init__(*args, **kwargs) models.py class Investor(models.Model): name = models.CharField(max_length=99) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name class Investment(models.Model): amount = models.FloatField(blank=False) rate = models.FloatField(blank=False) timestamp = models.DateField(default=datetime.now) investor = models.ForeignKey(Investor, on_delete=models.CASCADE) def __str__(self): return str(self.investor) Data must be stored into the database and redirect the page to myinvest section simultaneously. -
Why is this sending an empty file?
I am trying to attach a file to an email in Django. I am creating the file first, doing some processing and then sending the file. When I check the file on my PC it has content, but within the email I receive the attached file is empty. master_file = "all.txt" file_object = open(master_file, 'w') count = 0 for website in Website.objects.all(): ... do stuff ... file_object.close if count > 0: #send email email = EmailMessage() email.subject = settings.EMAIL_CONTACT_FORM_TITLE email.body = "File Attached" email.from_email = settings.DEFAULT_FROM_EMAIL email.to = [settings.EMAIL_RECIPIENT] email.attach_file(master_file) email.send() Email is sent with an attached file but the file is empty. The file on the PC (where I am running this) has content. -
How to run an external program to python when starting django?
I would like to know if it is possible to run a python program automatically when starting the django application? Thanks for your feedback. -
Django 2.2.3 How get all urls patterns and all views name
I code app with Django == 2.2.3 By now i want to get all urls_patterns of all my project and associated view name. How can i get something like this: urls_patterns_view_names_list = [ ("view_name", "view_name: url_pattern"), ..., ..., ..., ] -
AJax does not seem to work on the delete button
I am really new to ajax. I want to delete the entry from database on button click and I do not want the page to reload. but the ajax doesn't seem to work at all. What is wrong in my code? Please suggest the correct code. Thanks in advance. <script> $(document).on('click','#delete',function(){ var a ; a=confirm("Do you really want to delete the user?"); if(a==true){ var newurl = "{% url 'NewApp:centredelete' pk=1%}" var id = $(this).attr('name') $.ajax( { type:"GET", url: "newurl.replace('1',id);", data:{ delete:True }, success: function( data ) { if(data.success == true){ $(id).remove(); } else{ alert(data.error) } } })} }); </script> views.py def CentreDeleteView(request, pk): centre = Centre.objects.get(pk=pk) centre.delete() return HttpResponseRedirect(reverse('NewApp:centrelist')) -
How to add checkboxes on a very specific point on the image in django?
There are two questions here. 1) I want to make check boxes solder points for a chip. So how do I go about displaying those specific soldering points/check boxes on the image? 2)If I have multiple such chips with varying number of solder points, how do I proceeding making such number of check boxes without making too many tables in my db? So far I have thought of changing the background of the page and displaying check boxes. But since I have too many images I cant keep having to specifically 20-25 check boxes. I though of using a grid layout to help, but in that case a new grid layout for each image separately will be required because some places the solder joints are too close to each other. I don't know how to make one dynamic multiple choice field that will change the number of choices depending on the image. I don't know how to set said choices in a particular pattern on the image itself either. PS: I'm fairly new to Django and web development as a whole so any help whatsoever is most welcome -
How to limit the choices of foreignkey in Inline Admin model?
I'm working on this survey application. So the questions are classified into sections of different survey forms. The designing of the form is to be done from the admin panel. (I use grappelli). Each survey design form has section inline form and multiple question inline forms. When deciding the section for question, the drop down lists all the sections, irrespective of the survey form it is associated with. How do I populate the dropdown with the sections of the same survey form? This is for python 3.7 and Django 2.1.5. I've the models hierarchy as -> Survey -user ... Section -survey ... Question -section -survey ... The admin form has these components -> FeedbackAdmin -QuestionInline -SectionInline In the SectionInline I tried defining it like this after many attempts and reading multiple answers, but in vain field = super(QuestionInline, self).formfield_for_foreignkey(db_field, request, **kwargs) if db_field.name == 'sections': if request._obj_ is not None: field.queryset = field.queryset.filter(sections = request._obj_) else: field.queryset = field.queryset.none() return field This works without any error but doesn't do as expected. If the survey I has sections A and B, survey II has sections C and D, every question in survey should have a choice between A and B, but … -
Django: can we alter filefield such that when a file is selected, it immediately gets uploaded
I was just wondering: Will it be possible to alter the File Field such that when a file is selected, it immediately gets uploaded, without the means of additional button? Assuming that I imported everything from .models, .forms, urls.py, etc successfully, Codes in models.py: class data(models.Model): Datas = models.FileField(upload_to='datas/upload') Codes in forms.py: class form1(forms.ModelForm): class Meta: model = data fields = ('Datas',) Codes in views.py: def upload(request): if request.method == 'POST' and 'btnform1' in request.POST: newform1 = form1(request.POST, request.FILES) if newform1.is_valid(): newform1.save() return redirect('list') Codes in upload.html: <h2>Data</h2> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{newform1.as_p}} <!-- <button type="submit" class="btn btn-primary" name="btnform1">Upload Data</button>--> </form> Can anyone guide me and possibly give a solution on how to do it if it is even possible? Thank you. -
Django Celery & Django-Celery-Beat
I'm new to asynchronous tasks and I'm using django-celery and was hoping to use django-celery-beat to schedule periodic tasks. However it looks like celery-beat doesn't pick up one-off tasks. Do I need two Celery instances, one as a worker for one off tasks and one as beat for scheduled tasks for this to work? -
Want to Authenticate only Superuser
I want want give access to an html file to only the Superuser. Just how {% if user.is_authenticated %} authenticates all the users including the superusers, is there any way i can only authenticate superusers and not non superusers? {% block title %}base{% endblock %} {% block content %} {% if user.is_authenticated %} {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>{% block title %}Django{% endblock %}</title> </head> <body> <main> {% block content %} {% endblock %} </main> </body> </html> {% else %} <p>You are not logged in</p> <a href="{% url 'login' %}">login</a> {% endif %} {% endblock %} -
How to write a django filter query for multiple values selected from a dropdown list?
I wrote a views function to search/filter my data in django based on certain parameters. In the fields categories and locations the user can select multiple options to make the search. My views function is as follows: def search(request): queryset_list = Influencer.objects.order_by('-followers').distinct().values('id', 'full_name','username','photo','email_id','location_city','categories__name','website') if 'username' in request.GET: username = request.GET['username'] if username: queryset_list = queryset_list.filter(username__icontains=username) #Full Name if 'fullname' in request.GET: fullname = request.GET['fullname'] if fullname: queryset_list = queryset_list.filter(full_name__icontains=fullname) if 'location' in request.GET: location = request.GET['location'] for i in location: queryset_list = queryset_list.filter(location_city__icontains=i) if 'categories' in request.GET: categories = request.GET['categories'] if categories: queryset_list = queryset_list.filter(categories__name__iexact=categories) The search function should return the data of all the categories and location for which the search is made. For e.g. if search is made for location Delhi and Mumbai then it should return all the Influencers which have their location as Delhi or Mumbai, same is for categories also. The search function works perfect for single values but doesn't work for multiple values. For e.g if Delhi is send in the location category, then it returns correct results but if Delhi, Mumbai is selected then it reads only the first value i.e Delhi and applies the filter accordingly. How should I modify the search … -
How to do unit testing in django?
Here I am trying to do testing for my add_course view but it is not working even though the add_course function works properly .I think the problem is in test.py file .This is my first unit-testing so is there any mistake in my code ? Got this when i do python manage.py test: AssertionError: 302 != 200 ---------------------------------------------------------------------- Ran 1 test in 0.022s FAILED (failures=1) Destroying test database for alias 'default'... app/urls.py app_name = 'admin' urlpatterns = [ path('add-course/', views.add_course, name='add_course'), ] views.py def add_course(request): if request.method == 'POST': form = AddCourseForm(request.POST or None) if form.is_valid(): course = form.save() course.save() messages.success(request, 'course with title {} added.'.format(course.title)) return redirect('admin:add_course') else: form = AddCourseForm() return render(request, 'admin/add_course.html', {'form': form}) tests.py import unittest # from django.test import TestCase from django.test import Client from django.urls import reverse # Create your tests here. COURSE_URL = reverse('admin:add_course') class AddCourseTest(unittest.TestCase): def setUp(self): self.client = Client() def test_details(self): response = self.client.post('/admin/add-course/') self.assertEqual(response.status_code, 200) -
how to get date after some specific number of days from given date in django template
I am new in django. I want to get date after some specific number of days or number of weeks in html template file. my template file code: {% for factors in c.factor %} {% for factor_details in factors.factor_values %} {{factor_details.id}} {{factor_details.factor_value}} # here this is given date {{order_detail.oderdate}} and this is number of days and weeks {{factor_details.factor_value}}. {% endfor %} {% endfor %} -
django field required erroe while submitting form
I am trying to submit my problem but again and again it is showing "this field is required" instead of filling all fields. models.py class Cabin(models.Model): random_string = str(random.randint(100000, 999999)) centre_name = models.ForeignKey(Centre, on_delete=models.CASCADE ) code = models.CharField(max_length=6, blank=False, unique=True, default=random_string) total_seats = models.IntegerField(blank='False') views.py class CabinCreateView(CreateView): fields = '__all__' model = Cabin success_url = reverse_lazy("NewApp:logindex") "this field is required"