Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can Get two fields in one Model.py by use foreign key in django
**> How can Get two fields in one Model.py by use foreign key in django? > I want Fields are Course_Name, Branch_Name in Institutes Model and Show My other Courses Model** **This is the Model one >>>** ''''' class Institutes(models.Model): InstituteNo = models.AutoField(primary_key=True) Institute_Name = models.CharField(max_length=300) Course_Name = models.CharField(max_length=300) Course_Code = models.CharField(max_length=100) Branch_Name = models.CharField(max_length=300) Branch_Code = models.CharField(max_length=100) Course_Duration = models.CharField(max_length=100) '''' **#How can Retun Two Fieldsclass Meta: And def __str__(self): only one Value is show in Both Columns.** ''' class Meta: verbose_name_plural = "CourseName" def __str__(self): return self.Course_Name ''' This is the Model two ''' class Courses(models.Model): CourseNo = models.AutoField(primary_key=True) Institute_Name = models.ForeignKey(Facultys, verbose_name="Institute Name", default="0", on_delete=models.CASCADE) Course_Name = models.ForeignKey(Institutes, related_name="CourseName", default="0", on_delete=models.CASCADE) # Show one Filed Here Branch_Name = models.ForeignKey(Institutes, related_name="BranchName", default="0", on_delete=models.CASCADE) # Show Seccond Filed Here Year_or_Sem = models.CharField(max_length=100) ''' **> the output is show same value both drop down...but i want both drop down value Course_Name, Branch_Name** -
Creating a model and linking an existing model by id with a nested serializer
Can I use a nested serializer to link an object created by the parent serializer, to an existing model? I have 2 simple models, Client and Account. Let's say they both have just an id, and a name, the Account also has a (not null) foreign key to the Client. I create 2 serializers, and I nest the ClientSerializer in the AccountSerializer, as I want to see data about the Client when looking at the Account. class ClientSerializer(serializers.ModelSerializer): class Meta: model = Client fields = '__all__' class AccountSerializer(serializers.ModelSerializer): client = ClientSerializer(required=False) class Meta: model = Account fields = '__all__' This works fine for reads, but if I wanted to POST to create an account, can I do this with the AccountSerializer as it stands? Trying the following: serializer = AccountSerializer(data={ "client_id": 1, "name": "new account" }) I get the error {'client': [ErrorDetail(string='This field is required.', code='required')]}, even though the nested ClientSerializer is required=False. If I try this: serializer = AccountSerializer(data={ "client": {"id": 1}, # Client of id 1 already exists "name": "new account" }) Then I'll get {'client': {'name': [ErrorDetail(string='This field is required.', code='required')]}}, even though I wouldn't want to create a Client nor edit the client's name. I just … -
Django testing - logging in with Selenium not working
I'm trying to test the login page of a django app using Selenium - but I keep getting the error message 'Your email and password do not match'. from django.test import LiveServerTestCase from selenium import webdriver from accounts.models import User class TestInitiationFlow(LiveServerTestCase): def setUp(self): self.browser = webdriver.Firefox() self.user = User.objects.create(email='user@test.co.uk', admin=True) self.user.set_password('Test1234') self.assertEqual(User.objects.count(), 1) self.assertTrue(User.objects.get(email='user@test.co.uk')) def tearDown(self): self.browser.quit() def test_initiating_new_project(self): # The user navigates to the homepage of the app # And sees the login screen self.browser.get('http://localhost:8000') # The user enters an email and password username_input = self.browser.find_element_by_id('id_username') password_input = self.browser.find_element_by_id('id_password') submit_button = self.browser.find_element_by_id('submit_button') username_input.send_keys('user@test.co.uk') password_input.send_keys('Test1234') # The user presses enter and is taken to the startup screen submit_button.click() self.assertEqual(self.browser.current_url, 'http://localhost:8000/startup') Any help gratefully received! -
Says 'django.contrib.auth.models.DoesNotExist' even though item created
I've created a population script to test my website - please see below - but I get the following error message: django.contrib.auth.models.DoesNotExist: User matching query does not exist. Given that I've created a hypothetical user, I'm not sure why this is? Some of the indentation formatting below is incorrect - I couldn't get the original formatting to copy over correctly for some reason - but it is correct in the original. Any suggestions would much appreciated. Thank you. Jeff import os import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mynowandthen.settings') django.setup() from django.contrib.auth.models import User from nowandthen.models import Picture, Comment, UserProfile def populate(): banana_user = [ {'username': 'Banana', 'email': 'Banana@cat.com', 'password': 'Banana1234'}, ] johann_user = [ {'username': 'Banana', 'email': 'Banana@cat.com', 'password': 'Banana1234'}, ] wmffre_user = [ {'username': 'Wmffre', 'email': 'Wmffre@cat.com', 'password': 'Wmffre1234'}, ] maryhill_comments = [ {'user': banana_user, 'body': 'wowo I love this photo - reminds me of when I used to live there!'}, {'user': johann_user, 'body': 'I love Maryhill - its such a pretty part of Glasgow lol'}, {'user': wmffre_user, 'body': 'gonnae no dae that lol', 'user_id': 3}], fireworks_comments = [ {'user': banana_user, 'body': 'amazing fireworks - thanks for sharing :)'}, {'user': johann_user, 'body': 'love fireworks, love this, love YOU!'}, {'user': wmffre_user, 'body': 'whoop!'}] … -
testing views in django: unable to set session variable
This is the first time i'm writing tests for my functions and having a tough time figuring out the right way of doing it. in urls.py path('/b/', views.main), in my views.py, i have def main(request): if "user_id" not in request.session: return HttpResponseRedirect('/') user = Users.object.get(id=request.session['user_id']) d = datetime.datetime.now() - user.last_password_change_date if d.days > 90: return HttpResponseRedirect('/b/my-profile/change-password/?message=90') return render(request, 'backoffice/main.html', { 'user': user, }) in my tests.py file from django.contrib.auth.models import User from django.test import TestCase, Client class TestMain(TestCase): def setUp(self): self.client = Client() def test_backoffice_landing_page_with_session_GET(self): session = self.client.session session['user_id'] = [1] session.save() response = self.client.get('/b/') self.assertEqual(response.status, 200) however this throws me error stating TypeError: int() argument must be a string, a bytes-like object or a number, not 'list' Since, I'm just starting to learn testing django application. I want to test if user gets redirected if session is not available, and is allowed is user_id is available in request.session -
Django signals did not emited
I am stuck in a problem. I am trying to send signal from where I got message from websocket. Websocket message comes, but receiver never gets signal Here is my code plugins/init.py default_app_config = 'plugins.apps.PluginsConfig' plugins/apps.py from django.apps import AppConfig class PluginsConfig(AppConfig): name = 'plugins' def ready(self): import plugins.signals plugins/signals.py plugin_install_started = Signal(providing_args=['message']) plugin_install_error= Signal(providing_args=['message']) @receiver(plugin_install_started, dispatch_uid='ws_plugin_install_started') def handle_plugin_install_start(sender, message, **kwargs): event = 'plugin_install_start' group_name = signal_receive(event, sender) #plugin_group print("got message from install_started") @receiver(plugin_install_error, dispatch_uid='ws_plugin_install_error') def handle_plugin_install_error(sender, error, **kwargs): event = 'plugin_install_error' group_name = signal_receive(event, sender) #plugin_group print("got signal from install_error") And this is the where I try to send signals plugins/consumers.py def receive(self, text_data): text_data_json = json.loads(text_data) if text_data_json["command"] == "install": print(got message from websocket --> install) plugin_install_started.send(sender=self, message=text_data_json) elif text_data_json["command"] == "error": print("got message from websocket --> error") plugin_install_error.send(sender=self, message=text_data_json) When I send install command I can see below "got message from websocket --> install" "got message from install_started" but when I send error command result is below. So signal does not emmitted. plugin_install_error.send(sender=self, message=text_data_json) returns an empty list while plugin_install_install.send(sender=self, message=text_data_json) returns a Signal object "got message from websocket --> error" -
GeoDjango - classview does not register template name
I am trying to display a geographical db on a leaflet map using geodjango. However the view just ignores the template i pass it, I know that this code should work with a regular django class view. models.py: from django.contrib.gis.db import models class WorldBorder(models.Model): name = models.CharField(max_length=50) mpoly = models.MultiPolygonField() views.py: from .models import WorldBorder from djgeojson.views import GeoJSONLayerView class MapLayer(GeoJSONLayerView): template_name = 'world/map_layer.html' model = WorldBorder geometry_field = 'mpoly' properties = ['name'] def get_queryset(self): return WorldBorder.objects.filter(name='Spain') urls.py: urlpatterns = [ path('my_map/', MapLayer.as_view(), name='data'), ] however no matter what is inside of the html file all I get what I load this page is just the json of this object. Am i doing something wrong ? -
in django, On select of dropdown get selected value in views without submit
On change in dropdown, I need to get "cc_value" value in views.py without click on submit button. I referred few blog there they have mentioned that we need to write ajax code for this issue But is there any other way in Django to get the value of the selected option in dropdown without using ajax. In purchase_settings.html <form method = "post" id="Purchase_setting" > <div>Company Code:<br/> <select name="cc_value" id="cc_value"> {% for cc_value in user_setting_list.9 %} <option value="{{cc_value}}">{{cc_value}}</option> {% endfor %} </select> </div> <div >Purchase Organisation:<br/> <select name="purch_org_value"> {% for purch_org in user_setting_list.10 %} <option value="{{purch_org}}">{{purch_org}}</option> {% endfor %} </select> </div> <button class="button" type="submit">SAVE</i></button> </form> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $("#cc_value").change(function () { var company_code = $(this).val(); $.ajax({ type: "GET", data: { 'ccvalue': company_code }, success: function (data) { $("#purch_org_value").html(data); } }); }); </script> in view.py def user_settings(request): .... // need to get cc_value in views on select without submiting form cc_value1 = request.GET.get('ccvalue') //on select of dropdown i m not getting value.I just tried giving cc_value = request.GET.get('cc_value') print(cc_value1)//none # user setting form user_setting_list = user_setting.user_settings_form(client,login_username,db_username) print(user_setting_list) context = { 'user_setting_list':user_setting_list } return render(request, 'purchase_settings.html',context) -
Validating a contact name in python
Suppose I have three fields in my CSV sheet: Conditions: 1) If contact Name is not given then the other two will also be not given. 2) if contact Name is given then: a) Both the values would be given b) one of the values from Contact Number and Contact Email would be given Possible Scenarios: Case 1: Contact Name Contact Number Contact Email Adhiraj Blank adhi@gmail.com Adhiraj 9999999999 Blank Output 1: This should not pop an error as This is a unique contact. Case 2: Contact Name Contact Number Contact Email Adhiraj 9819999999 adhi@gmail.com Adhiraj 9999999999 adhi@gmail.com Output 2: This should result in an error as the first entry and second entry conflicts. Case 3: Contact Name Contact Number Contact Email Adhiraj 9819999999 Blank Adhiraj 9999999999 Blank Output 3: No Error Case 4: Contact Name Contact Number Contact Email Adhiraj Blank adhi@gmail.com Adhiraj Blank raj@gmail.com Output 4: No error Case 5: Contact Name Contact Number Contact Email Adhiraj 9819999999 Blank Adhiraj 9819999999 Blank **Output 5 **: Error Case 6: Contact Name Contact Number Contact Email Adhiraj 9819999999 Blank Adhiraj 9819999999 Blank Raman 9819999999 Blank Output 6 : Error for the third row So, these were the combinations I could … -
Django models DateTimeField index on Date
Is it possible to index only the date aspect of a models.DateTimeField in Django? I cant seem to find it in the documentation, and i'm not sure if doing something like this works class Meta: indexes = [ models.Index(fields=['created_at__year', 'created_at__month', 'created_at__day']), ] -
Celery Flower opens 21 connections to Redis
I am using celery Flower on Heroku with a free dyno to monitor my tasks and noticed that it opens 21 Connections to my redis instance causing troubles with the max connection limit. Does someone know, how to limit the connections to a minimum? -
How to render a javascript function that comes from view as a str?
I'm trying to implement a payment api to my django app. It returns a dict when i do a request. The content of this dict is like that; {...,'checkoutFormContent':'<script type="text/javascript">if (typeof ...</script>'...} How can i render this js function in template? -
Django drf executing function once a day
I have apartments for rent, and each apartment has status (free or not) And my main purpose is to execute function (that changes apartment's status) once a day because of complexity of algorithm. Any solutions will be fine) -
Python, Django rest framework, create a field that contains a choices or free text
I have a Django rest framework API. I'm looking to add to it a field, which contains either choices or free text. I want that if the user decided to add a new value to the field, it will be added to the DB. The I have an the following exsiting model: class Points(models.Model): mission_name = models.CharField(name='MissionName', verbose_name="Mission Name", unique=True, max_length=255, blank=False, help_text="Enter the mission's name" ) location_name = models.CharField(choices= # fetch known locations from the DB #or create a new one) # Show existing options or input a new one. # If an existing location has been chosen then it's Latitude and Longitude are of the fetched object. # Pretty sure that this kind of action belongs in the serializer or the view. latitude = models.FloatField(name="GDT1Latitude", verbose_name="GDT 1 Latitude", unique=False, max_length=255, blank=False, help_text="Enter the location's Latitude, first when extracting from Google Maps.", default=DEFAULT_VALUE) longitude = models.FloatField(name="GDT1Longitude", verbose_name="GDT 1 Longitude", unique=False, max_length=255, blank=False, help_text="Enter the location's Longitude, second when extracting from Google Maps.", default=DEFAULT_VALUE) area = models.CharField( name='Area', max_length=8, choices=AREAS, ) -
Getting error Invalid block tag on line 80: 'NOUN_LIST|count_ordered', expected 'endblock'. Did you forget to register or load this tag?
I created a custom tag and getting error as : Request Method: GET Request URL: "" Django Version: 2.2.1 Exception Type: TemplateSyntaxError Exception Value: Invalid block tag on line 80: ''NOUN_LIST|count_ordered'', expected 'endblock'. Did you forget to register or load this tag? My Project Structure is : custom_tag.py : from django import template register = template.Library() @register.simple_tag def count_ordered(value): dict = sorted(value, key=lambda val:len(val.list),reverse=True) return dict I am calling this tag as : {% load custom_tag %} {% NOUN_LIST|count_ordered as list %} {{ list }} -
Laravel vs Django [closed]
Please I am currently in between choosing a framework for a web project. Between Django and Laravel which one is best in terms of Efficiency, Memory Management and deployment?? Thank You. -
Why is the button not being shown in form?
I'm trying to develop a website for an online store and after I added my css files to the base.html file, everything is working fine,but an input button for update cart is not being shown properly although it was working fine before adding the css static file.What can I do? Can someone please help me with this? My cart.html: {% extends 'base.html' %} {% block content %} {% if empty %} <h1 class='text-center'>{{ empty_message }}</h1> {% else %} <div class="container text-black py-5 text-center"> <h1 class="display">MyShop Cart</h1> </div> <div class="container-md"> <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script> <script src="//code.jquery.com/jquery-1.11.1.min.js"></script> <!------ Include the above in your HEAD tag ----------> <script src="https://use.fontawesome.com/c560c025cf.js"></script> <div class="container"> <div class="card shopping-cart"> <div class="card-header bg-dark text-light"> <i class="fa fa-shopping-cart" aria-hidden="true"></i> Shipping cart <a href="{% url 'myshop-home' %}" class="btn btn-outline-info btn-sm pull-right">Continue shopping</a> <div class="clearfix"></div> </div> <!-- PRODUCT --> <div class="pb-5"> <div class="container"> <div class="row"> <div class="col-lg-12 p-5 bg-white rounded shadow-sm mb-5"> <!-- Shopping cart table --> <div class="table-responsive"> <table class="table"> <thead> <tr> <th scope="col" class="border-0 bg-light"> <div class="p-2 px-3 text-uppercase">Product</div> </th> <th scope="col" class="border-0 bg-light"> <div class="py-2 text-uppercase">Price</div> </th> <th scope="col" class="border-0 bg-light"> <div class="py-2 text-uppercase">Quantity</div> </th> <th scope="col" class="border-0 bg-light"> <div class="py-2 text-uppercase">Remove</div> </th> </tr> </thead> {% for … -
Django admin Add item button translation
I am struggling with the translation of an add button in django admin site. The one in the image below. Image How can i change its text? -
Django updating profile photo
Look I have a problem with displaying photos after updating. I have a function from my views.py def addHW(request): if request.user.is_authenticated: obj = Profile.objects.get(user=request.user.id) else: obj = '' profile = request.user.profile form = CustomerForm(instance=profile) template = 'HW/add.html' context = {'form': form, 'profile': obj} if request.method == 'POST': form = CustomerForm(request.POST, request.FILES, instance=profile) if form.is_valid(): Profile.objects.get(user=request.user.id).photo.delete() form.save() return render(request, template, context) and after deleting previous photo and saving of new photo, page must be reloaded. And page shows visual reloading, but HTML shows src of previous image. And after manual refreshing page displays new src of photo. How i can resolve it? -
Render shop items as grid or list in Django
I need to make some mechanism for users that allow switch between rendering items as grid or as list, how I can implement this? -
i am working on django forms with the password related
how i can set my own password at any login template in my django website without using django default login authentication. A sample of my website is given in screen shot of my project.I want to set a own password in that page.sample of my project -
How to pass data from Django Template to View
I have a template where customer details are displayed, along with a 'Create Lead' button at the bottom. This should take the user to the Lead creation form page where the customer field should be pre-selected. I'm new to django. Based on responses of previous similar questions, I came up with the below code. But when I click the 'Create Lead' button, the url changes from "http://127.0.0.1:8000/sales/customer/21" to "http://127.0.0.1:8000/sales/customer/21/?customer_id=21" but nothing happens on the page. I tried with POST method and csrf token also, but it gives HTTP ERROR 405. Could some please help here. Also, I've separate view for creating a Lead, which is sort of duplication of CreateView for Lead. And I believe that's not how it's supposed to be. What is the way to club them both in single view. Below are the code snippets. Models.py class Customer(models.Model): name = models.CharField(max_length=256) email = models.EmailField(unique=True) phone = models.PositiveIntegerField() class Lead(models.Model): customer = models.ForeignKey(Customer,related_name='Leads',on_delete=models.PROTECT) destinations = models.CharField(max_length=256) lead_source = models.CharField(max_length=256,choices=lead_source_choices,default='FNF') lead_source_id = models.CharField(max_length=25,blank=True) lead_status = models.CharField(max_length=25,choices=lead_status_choices,default='NEW') remarks = models.TextField(blank=True) trip_id = models.CharField(max_length=10,editable=False,unique=True,default="IN"+uuid.uuid1().hex[:5].upper()) creation_date = models.DateField(auto_now=True) Forms.py class LeadForm(forms.ModelForm): class Meta: model = Lead fields = ('customer','destinations','lead_source','lead_source_id','lead_status','remarks') class LeadFromCustomerForm(forms.ModelForm): class Meta: model = Lead fields = ('destinations','lead_source','lead_source_id','lead_status','remarks') Template <form method="GET"> … -
Render a dictionary with object list as values in django but template not showing values
I'm try to displaying dictionary values in my template that i render from my views file. but its not displaying any value. In my html template show my just blank or not any error. kindly guide me where i did a mistake. Thank you. views.py class BuyView(TemplateView): template_name = 'shop/buy.html' red_templateName = 'shop/receipt.html' def get(self, request, product_id): product = get_object_or_404(Product, pk=product_id) args = {'product':product} return render(request, self.template_name, args) def post(self, request, product_id): product = Product.objects.get(id=product_id) if request.POST['address'] and request.POST['quantity']: order = Order() order.or_proName = product.pro_name order.or_companyName = product.companyName order.or_quatity = request.POST['quantity'] order.or_quatity = int( order.or_quatity) orderPrice = order.or_quatity*product.Sale_Price order.or_bill = 100 + orderPrice order.pub_date = timezone.datetime.now() product.Quantity -= order.or_quatity product.save() order = order.save() args = {'order':order} return render(request, self.red_templateName, args) else: return render(request, self.template_name, {'error':'Please Fill the address field'}) template.py {% extends 'base.html' %} {% block content %} <div> <div class="container p-5" style="border:1px solid gray;"> <small class="lead" >Your Order Receipt: </small> {{ order.or_id }} {{order.or_proName}} {{order.or_companyName}} {{order.or_quatity}} {{order.pub_date}} Deliever Chargers=100 ----------------------- Total = {{or_bill}} </div> </div> {% endblock %} -
Django - Use model fields part in a create or update query
Given the following models in a Django 2.2 app: class ShelfPosition(models.Model): shelf_code = models.CharField(max_length=10) row = models.IntegerField() column = models.IntegerField() class Meta: constraints = [ models.UniqueConstraint(fields=["shelf_number", "row", "column"], name="shelfpos_unique") ] class Item(models.Model): name = models.CharField(max_length=255) position = models.OneToOneField(to=ShelfPosition, on_delete=models.SET_NULL, primary_key=True) I rely on Django's lookup feature to filter on Item objects depending on some ShelfPosition fields: Item.objects.filter(position__shelf_code="BF4") Is there any way I could implement a similar lookup functionality such as described above when using get_or_create or update_or_create? item, created = Item.objects.get_or_create( position__shelf_code="BF6", position__row=88, position__column=1, defaults={……} ) -
open and close time in django rest framework
I have project in django rest framework that has some stores and I want, owner of stores enter open hour and close hour and days that they work in their profiles of website. what should I do ?