Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Ajax function not working properly for deleting without refreshing page
I am working on a problem where I need to delete an entry in database without refreshing the list page. However, with the ajax function and view that I have created, the data is getting deleted but success function is not changing to true.The list page is displayed as it is, and on manually refreshing the deleted data is not displayed. Also, since I am new to ajax I have less idea about what to put in data dictionary in ajax for deleting.What am I doing wrong in the code? Please help me in doing so without page refresh.(I need to stay on the centrelist page).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 url = "{% url 'NewApp:centredelete' pk=1%}" var id = $(this).attr('name') $.ajax( { type:"GET", url: url.replace('1',id), data:{ delete:true }, success: function( data ) { if(data.success == true){ $(id).remove(); } } })} }); </script> views.py def CentreDeleteView(request, pk): data = {'success': False} centre = Centre.objects.get(pk=pk) print(centre) if request.method == 'GET': try: if centre: centre.delete() data['success'] = True else: data['success'] = False data['error'] = "unsuccessful!" except Centre.DoesNotExist: return redirect('/NewApp/centrelist') return JsonResponse(json.dumps(data)) -
select columns with group by one column django orm
I trying to get the name, today_date, date_2 from event table with group by name of the event with sql I am able to get the details but while using django orm I am getting duplicate records. select name, today_date, date_2 from event group by name; --> SQL Query Can anyone help me to convert above SQL query to django ORM query? -
ModelMommy makes Django JSONField as a blank
I had tried this snippet By customizing the MySQL line with PostgresQL from model_mommy import mommy def generator_function(): return {} mommy.generators.add('django.contrib.postgres.fields.JSONField', generator_function) It does not work model_mommy fills my JSONField with {}. Question: How can I have a dummy key: value in it? -
How to select objects of a model related to my model
I'm creating a filtering system for my application and I would like to render <select> fields, pre-filled with options possible. Lets assume I have a model called Exam which has relation to Student and this has relation to StudentProfile - I'm filtering Exam objects by field has_passed in student's profile so I'm creating a query such as: student__student_profile_has_passed and passing it to django's filter() function and it works. Now however, I'd like to render html form with and all possible <option>s, to do so I need to find the mentioned possible options. How can I find all objects from such a query string as above to get all the objects of student__student_profile from my Exam model? This also has to work regardless of how long the chain of relations is assuming the relations are all correct. -
object.save() seems to be created but is not registered in db
How is it possible? This is the strangest bug I ever had. I register an object from a form like I ever do. if request.is_ajax() and request.POST: if form.is_valid(): mission = form.save(commit=False) mission.generic_name = p.generic_name mission.created_by = request.user mission.save() At runtime, inspecting this, I can see that mission seems to be created. It has a pk and I can run save() method as well without any errors. Despite all of this, mission is not inserted in the database. If I check in a python console and try to get it using the same pk I got in the ipdb traces, it raises a DoesNotExistsException. Mission.objects.get(pk=4915) (...) rdt.prestations.models.Mission.DoesNotExist: Mission matching query does not exist. Here is the form: class MissionForm(forms.ModelForm): prestaId = forms.CharField(widget=forms.HiddenInput) files = forms.ModelMultipleChoiceField(queryset=None, required=False) class Meta: model = Mission fields = ['name', 'length', 'expected_delivery_date', 'supplier', 'guideline', 'prestation'] widgets = { 'prestation': forms.HiddenInput(), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) p = kwargs['initial'].get('prestation') self.fields['supplier'] = forms.ModelChoiceField( queryset=Supplier.objects.available_for_langs( p.price.lang_src, p.price.lang_dest) ) self.fields['files'] = forms.ModelMultipleChoiceField( queryset=p.files.source().exclude( is_duplicate=False, file='', ), required=False ) I precise that form.is_valid() and form.save() doesn't throw any exception at all. It's just that the object is not created despite it has at runtime a pk. save() method is … -
Django formTypeError: signupinfoform.Meta.fields cannot be a string
I created the model with the below fields and it is raising ann error as TypeError: signupinfoform.Meta.fields cannot be a string. Did you mean to type: ('confirm_password',)? from django.db import models from django.contrib.auth.models import User # Create your models here. class signup(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) confirm_password = models.CharField(max_length=200) def __str__(self): return self.user.username forms.py from django import forms from . models import signup from django.contrib.auth.models import User class signupform(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta: model = User fields = ('username','password','email') class signupinfoform(forms.ModelForm): confirm_password = forms.CharField(widget=forms.PasswordInput()) class Meta: model = signup fields = ('confirm_password') -
Why does python stop when django starts?
After creating a new Django project that is linked to the MySql database, if I try running it with runserver, I get a message that "Python has stopped working" This concerns a new Python 3.5.3, running MySQL 8.0, Django 1.11. There is not a long time any marchair properly. workon my_virt_env python manage.py runserver Python stopped -
annotation for time difference
I have some models and I have to calculate some value like sum of all (difference between date created and today) in days. 1st order - 01/07/2019, diff from now = 4 days * 2(quantity) 2nd order - 03/07/2019, diff from now = 2 days * 3(quantity) Sum = 14 # same foe sales model correct formula is this: Sum(Each Sale.time from now in month)/Sum(Each order.time from now in month) '.' is for multiply First, I am tried this to calculate Sum of time differences. current_date = datetime.date.today() time_diff = OrderItemTable.objects.annotate(days=Sum((F('prev_order_items__order_id__created_at')-current_date))) but output is this 181715600.0. This is not correct if it's in seconds. These are relavent models and fields. class Sales(models.Model): # sales detail of items item_id = models.ForeignKey('Item', models.DO_NOTHING) date = models.DateField() sale_qty = models.IntegerField() item_id = models.ForeignKey('OrderItemTable', models.DO_NOTHING, related_name='sales_order_items') # some more fields class Item(models.Model): # detail of items, around 3000 items item_name = models.CharField(max_length=127) # some more fields class Order(models.Model): # order detail of each order created_at = models.DateField(auto_now_add=True) # some more fields class Ordered_items(models.Model): # item detail for all order order_qty = models.IntegerField() item_id = models.ForeignKey(OrderItemTable, models.DO_NOTHING, blank=True, null=True, related_name='prev_order_items') order_id = models.ForeignKey(OrderOrderTable, models.DO_NOTHING, blank=True, null=True, related_name='prev_order_order') # some more fields -
How can I display the db values of a row in a form before I update the form?
I'm trying to display the employee data after filtering the DB by pk which I passed via the URL. I can update the form, although I don't want the form fields to be empty since I just want to update, which means its not all the fields I'm going to touch forms.py class AddEmployeeForm(forms.Form): genderset = [(0,'--Select an Option--'),('Male','Male'), ('Female', 'Female')] marital_status_set = [(0,'--Select an Option--'),('Married','Married'), ('Single', 'Single')] employment_type_set = [(0,'--Select an Option--'),('Contract','Contract'), ('Full-Time', 'Full-Time'),('Intern', 'Intern')] employment_status_set = [(0,'--Select an Option--'),('Active','Active'), ('Inactive', 'Inactive')] first_name = forms.CharField(label = "First Name ", max_length = 200) last_name = forms.CharField(label = "Last Name ", max_length = 200) employee_id = forms.IntegerField() email = forms.EmailField(label = "Email ", max_length = 200) address = forms.CharField(label = "Address", max_length = 200) role = forms.CharField( max_length = 200) date_of_birth = forms.DateField() join_date = forms.DateField() end_date = forms.DateField() location = forms.CharField( max_length = 200) hod = forms.ModelChoiceField(queryset=Department.objects.only('lead')) phone_number = forms.CharField( max_length = 200) employment_type = forms.ChoiceField( choices = employment_type_set) employment_status = forms.ChoiceField( choices = employment_status_set ) marital_status = forms.ChoiceField( choices = marital_status_set ) gender = forms.ChoiceField( choices = genderset ) department = forms.ModelChoiceField(queryset=Department.objects.only('dept_name')) credentials = forms.FileField() passport = forms.FileField() date_added = forms.DateTimeField( initial = datetime.now, widget=forms.HiddenInput()) views.py @login_required(login_url='/accounts/login') def edit(request, … -
Django GenericForeignKey vs set of ForeignKey
I would like to discuss the case of using GenericRelation and GenericForeignKey. I have the 2 models, Appartement and Mission. And I need to create LockCode model which will be connected to Appartment or Mission. I have added the GenericForeignKey to the LockCode and GenericRelation to the Appartement and Mission: class LockCode(TimeStampedModel): context_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) context_id = models.PositiveIntegerField() context = GenericForeignKey('context_type', 'context_id') class Mission(DirtyFieldsMixin, models.Model): lock_codes = GenericRelation( LockCode, content_type_field='context_type', object_id_field='context_id', related_query_name='mission' ) class Appartment(DirtyFieldsMixin, models.Model): lock_codes = GenericRelation( LockCode, content_type_field='context_type', object_id_field='context_id', related_query_name='appartment' ) It works ok. But added the complexity level to compare with adding 2 ForeignKeys, for appartement and for mission. class LockCode(TimeStampedModel): appartement = models.ForeignKey(Appartement, null=True, blank=True) mission = models.ForeignKey(Mission, null=True, blank=True) So wdyt should I keep the GFK or use 2 simple FK? -
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"), ..., ..., ..., ]