Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding constraint on Django Models based on values of another field
I have a simple model with 1 primary key and 3 fields (simplified): passing score max score max attempt This model is created by inheriting from django.db.models. This is the minimal reproducible code: class QuestionSet(models.Model): passingscore = models.PositiveSmallIntegerField("passing score") maxscore = models.PositiveSmallIntegerField("passing score") maxattempt = models.PositiveSmallIntegerField("passing score") I would like to add a constraint such that passingscore should never be greater than maxscore in the database. I've used constraint that span across multiple fields such as unique_together, as per this thread on StackOverflow. But clearly this is a different use-case. I've also briefly considered to add constraint directly writing PostgreSQL code: ALTER TABLE tableB ADD CONSTRAINT score_policy_1 CHECK (maxscore >= passingscore) But this defeats the purpose of using an ORM and violate the "loosely coupled" philosophy, making it hard to migrate between different database backends. If this is at all possible, please point me to a more idiomatic way of writing this constraint in Django. -
How to populate a ManyToMany Field in Django using a .csv file?
I have 2 models Influencer and Category. Influencer has a many to many relationship with Category.The models look like this: class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name and class Influencer(models.Model): full_name = models.CharField('Full Name',max_length=100) username = models.CharField('Username',max_length=100,unique=True) photo = models.ImageField(upload_to = 'photos/%Y/%m/%d/',blank=True) location_city = models.CharField('Location City',max_length=100,null=True,blank=True) categories = models.ManyToManyField(Category) I have written a python script that parses a csv file and sends the data to a PostgreSQL database. In the csv file the column categories is present as an array, like the one given below ['Food', 'Bar', 'Bar', 'Student', 'Student', 'makeup', 'makeup', 'India', 'India'] When I print the type of column categories in python it shows it as a string. The function which I wrote to parse and send data to database is as follows.I have excluded the categories option from the function for now. ef write_to_db(file): with open(str(file),encoding='utf-8') as csvfile: csvreader = csv.reader(csvfile) next(csvreader,None) for row in csvreader: try: if not Influencer.objects.filter(username = row[1]).exists() and check_email(row[2]): _,created = Influencer.objects.get_or_create( full_name = row[0], username = row[1], email_id = clean_email(row[2]), external_url = row[8], ) except Exception as e: print(e) How should I write the code so that I can insert the categories in the many to many field with … -
NoReverseMatch for Class-based delete view
I am having trouble trying to implement a class-based delete view as I have been having a NoReverseMatch error and I am unsure what is causing the problem. This is my urls.py: path('post/lesson_delete/<int:pk>', LessonDeleteView.as_view(), name='lesson_delete'), This is my views.py for my DeleteView: class LessonDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Lesson success_url = '../' def test_func(self): lesson = self.get_object() # if self.post.request.user == lesson.post.author: return True # return False These are my Models: class Lesson(models.Model): title = models.CharField(max_length=100) file = models.FileField(upload_to="lesson/pdf") date_posted = models.DateTimeField(default=timezone.now) post = models.ForeignKey(Post, on_delete=models.CASCADE, null=False, blank=False) def __str__(self): return self.title def get_absolute_url(self): return reverse('lesson_upload', kwargs={'pk': self.pk}) def delete(self, *args, **kwargs): self.file.delete() self.title.delete() super().delete(*args, **kwargs) class Post(models.Model): title = models.CharField(max_length=100) image = models.ImageField(default = 'default0.jpg', upload_to='course_image/') description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=6) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) rating = models.IntegerField(default = 0) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk' : self.pk}) This is my html template to render the delete view: {% extends "store/base.html" %} {% block content %} <div id="main"> <table class="table mb-0"> <thead> <tr> <th>Title</th> <th>Author</th> <th>Download</th> <th>Delete</th> </tr> </thead> <tbody> {% for l in lesson %} <tr> <td> {% if l.file %} {{ l.title }} {% else %} <h6>Not available</h6> {% … -
How to redirect to another page with context, after posting a form?
After posting my form, I want to redirect to another page and send some data to that page with context. I need to send a string and boolean value to the other page, depending if the post to the database was successful or not. With the view I have, the admin.html is rendered but the url is not updated (it still shows the form page). How can I achieve this I've tried to play around with the redirect. return redirect(reverse('app:view', kwargs={ 'bar': FooBar })) But no luck yet. def report_view(request): if request.method == 'POST': form = ReportForm(request.POST) if form.is_valid(): report_title = form.cleaned_data['report_title'] report_link = form.cleaned_data['report_link'] new_report = Report(title = report_title, link = report_link) new_report.save() return render(request, 'dashboard/admin.html', {'title': Admin Page, 'added':True}) -
I have a project in Python and i have to make a U.I (HTML PAGE) to present it .Please tell me how to do same
I have created a project of machine learning using python. The project is about text summarization using python libraries. Now our seniors have asked us to present it using an interface. I tried using django but failed. Need immediate assistance with the same ! -
Django test how to check if function was Not called
I want to write a test in order to check that a specific function was not called. Below is a pseudo example of my code: Code TestFunctionA(): if a > b: TestFunctionB() In order to check if it is called i do the following which is working with mock.patch('TestFunctionB') as mock_TestFunctionB: TestFunctionA() mock_TestFunctionB.assert_called_once_with() If i want to check if the function TestFunctionB was not called i tried the following but is not working with mock.patch('TestFunctionB') as mock_TestFunctionB: TestFunctionA() assert not mock_TestFunctionB.assert_called_once_with() -
NameError in Django Rest Framework, it's showing my model name is not defined
I am trying to serialize the data from the database so that I can access the data on the client side apps. I am new to the Django for just 1 month. Kindly help me out. What is the correct method to execute this problem? I just want it to be generated in the data in JASON format. And it's giving me an error. What am I doing wrong here? Is this not the way? I have tried this where Jobcard is my model name from jobcard_api.models import Jobcard ``` then this gives a new error of NameError of "name 'JobcardSerializer' is not defined" This is my models.py inside an app and the app is inside a project, there are three apps and all of them giving the same kind of error with different names ``` from django.db import models class Jobcard(models.Model): """Database model for the jobcard""" id = models.AutoField(primary_key=True) jobcard_number = models.CharField(max_length=30, unique=True, blank=False), ..., observation = models.TextField(blank=True) def get_jobcard_number(self): """Retrieve jobcard number""" return self.equipment_name ``` This is my serializers.py inside an app called jobcard_api. ``` from rest_framework import serializers from jobcard_api import models class JobcardSerializer(serializers.ModelSerializer): """Serializer for the jobcard object""" class Meta: model = models.Jobcard fields = ('id', … -
Input text box : unable to retrieve the data (Django)
I'm developing a web application with Django and I have a little problem I couldn't solve. I'm using input text box with a default value so the user knows what is currently in the database but they can change it by typing text and send the new information. Here is my html: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> Annotate: {{video.title}}</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script> <link rel="stylesheet" type="text/css" href="https://www.w3schools.com/w3css/4/w3.css"> {% load static %} <script type="text/javascript" src='{% static "annotationTool/jsScript/garnmentAnnotation.js" %}?v=00003'></script> </head> <body> <h1>{{video.title}}</h1> <div id = {{mannequin.mannequinID}} class = "mannequin"> <img class = "mannequinImg" src="/media/{{mannequin.frame}}"/> </div> <nav> <ul> {% for garnment in garnments %} <li><a href="#{{ forloop.counter }}">{{garnment.type}}</a></li> {% endfor %} </ul> </nav> <div hidden class="garnments"> {% for garnment in garnments %} <div class="garnment" id="garnment_{{ forloop.counter }}"> <img class = "garnmentImg" src="/media/{{garnment.frame}}"/> <form> <p>Model name:</p><input type="text" id="garnment_{{ forloop.counter }}_modelName" name="modelInput" value="{{garnment.mannequin}}"><br> <p>Brand:</p><input type="text" id="garnment_{{ forloop.counter }}_brand" name="brandInput" value="{{garnment.brand}}"><br> <p>Name of the product:</p><input type="text" id="garnment_{{ forloop.counter }}_productName" name="productNameInput" value="{{garnment.productName}}"><br> <p>Price:</p><input type="text" id="garnment_{{ forloop.counter }}_price" name="priceInput" value="{{garnment.price}}"><br> <p>URL:</p><input type="text" id="garnment_{{ forloop.counter }}_url" name="urlInput" value="{{garnment.url}}"><br> <input type="button" value="Validate" onclick="sendNewInfo({{mannequin.mannequinID}},{{garnment.pk}},{{ forloop.counter }})"> </form> </div> {% endfor %} </div> <div class="currentGarnment"> </div> </body> </html> So I want to retrieve like what the user putted in this box: … -
How to display all months dynamically in django template
Here i am trying to display the line chart of students added in every month of the particular year.But i got some little problem here.The problem is in the script.For example i only have students added in june(1 students) and july(6 students) and in other month the number of student is zero.But while displaying june and july students number is in jan and feb month.I think the one solution is making the labels in the script dynamic like this {{student.month|date:'F'}}, but i want to add all 12 months in the labels even if there is not any students in some month.How can i do it ? views.py def home(request): students_according_to_month = Student.objects.annotate(month=TruncMonth(F('joined_date'))).values('month') .annotate(total=Count('pk')) template <script> /* LINE CHART */ var ctx3 = document.getElementById('chartLine1'); var myChart3 = new Chart(ctx3, { type: 'line', data: { labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun','July','Aug','Sep','Oct','Nov','Dec'], datasets: [{ label: '# of Votes', data: [ {% for student in students_according_to_month %} {{student.total}}, {% endfor %} ], borderColor: '#dc3545', borderWidth: 1, fill: false }] }, options: { legend: { display: false, labels: { display: false } }, scales: { yAxes: [{ ticks: { beginAtZero:true, fontSize: 10, max: {{students|length}} } }], xAxes: [{ ticks: { beginAtZero:true, fontSize: 11 } … -
I can't makemigration appname in Django project
After completed, I pushed and rebase git master, database in my project is locked. I removed database and create new, but I don't see table for Model in models.py. How should I fix? Help me -
saving an object in django table
I am trying to save a django object in a table but it automatically gets converted in a string object which I am trying to save w = [<ItemBatch: Survey>] models.py items = ArrayField(models.CharField(max_length=300), default=default_thing) def default_thing(): return ['No Items Packed'] what I did: DispatchPlan.objects.create(items=w) but when I check the same in my table it is saved like this {Survey} I want to save it as an object itself, how do I do that? -
How to loop though users how object in django
I want to show the user all objects he made. Currently I can only show 1 object my_items.html (where i want it to show) {% extends 'base.html' %} {% block content%} <main role="main"> <div class="container"> <!-- Example row of columns --> <div class="row"> {% for item in item %} <!--{% if item.id == request.user.id %}--> <div class="col-md-4"> <div class="col-md-4"> <img style="max-width: 100px; max-height: 300px" src="{{ item.thumb.url }}"> </div> <h2><a href="{% url 'items:detail' slug=item.slug %}">{{ item.name }}</a></h2> <p>{{ item.snippet }}</p> <p>{{ item.date }}</p> <p><a class="btn btn-warning" href="#" role="button">Edit</button></a></p> <p><a class="btn btn-danger" href="#" role="button">Delete</a></p> </div> <!--{% endif %}--> {% endfor %} </div> <hr> </div> <!-- /container --> </main> {% endblock %} items views.py def item_myitems(request): item = Item.objects.all().order_by('date') return render(request, 'items/my_items.html', {'item': item}) i tried using filter() and get() on views.py -
How to send data to view from form after asking for confirmation?
I created a simple form where I'm asking for user input and then posting that to the database. Now I would like the user to confirm the data in form is correct, and for that I'm using a Bootstrap modal. How can I send the data from the form to the view when pressing the 'OK' button on the modal. I'm new to the Django framework, and maybe there is another better way without using bootstrap modals. -
how to display errors of signup (or any) form and presenting same form to users?
I have a form called SignupForm for the users signup. I want to display the errors generated by the Django to the users if there is some introduced like password!=password2. I have tried everything but there are different types of errors. my template signup.html is {% extends 'blog/base.html' %} {% block content %} <h2>Sign up</h2> <form method="post" > {% csrf_token %} {% if form.errors %} <!-- Error messaging --> <div id="errors"> <div class="inner"> <p>There were some errors in the information you entered. Please correct the following:</p> <ul> {% for field in form %} {% if field.errors %}<li>{{ field.label }}: {{ field.errors|striptags }}</li>{% endif %} {% endfor %} </ul> </div> </div> <!-- /Error messaging --> {% endif %} {{ form.as_p }} <button type="submit">Sign up</button> </form> {% endblock %} and views.py is def signup(request): if request.method=='POST': form =SignupForm(request.POST) if form.is_valid(): form.save() return redirect('login') else: err=form.errors return HttpResponseRedirect('/') else: form = SignupForm() #form=UserCreationForm() return render(request,'registration/signup.html',{'form':form}) There are different errors. For example, if I use else: err=form.errors return HttpResponseRedirect('/') it shows The current path, signup/signup, didn't match any of these and when I use return redirect('signup') it shows - 'str' object has no attribute 'get' and when I use a errors dictonary ``err=form.errors return … -
How to count records of each 12 months in django?
Here i am trying to count the students record that are added in the particular year's every month.I tried like this but didn't worked.I also got the database error.I am using mysql for the database. Exception Type: ValueError Exception Value: Database returned an invalid datetime value. Are time zone definitions for your database installed? models.py class Student(models.Model): name = models.CharField(max_length=100) courses = models.ManyToManyField(Course) joined_date = models.DateField(auto_now_add=True) views.py from django.db.models import Count from django.db.models.functions import TruncMonth students_according_to_month = Student.objects.annotate(month=TruncMonth('joined_date')).values('month').annotate(total=Count('pk')) print('students',students_according_to_month) -
Exclude constraint with partial index - Postgresql
I have the following tables: class Slot(models.Model): time_range = models.DateTimeRangeField() calendar = models.ForeignKey('Calendar') campaign = models.ForeignKey('Campaign', null=True) class Appointment(models.Model): calendar = models.ForeignKey('Calendar') campaign = models.ForeignKey('Campaign', null=True) slot = models.ForeignKey('Slot', models.DO_NOTHING, unique=True, null=True) timezone = models.CharField(max_length=120) I want to make Slot.time_range unique so not other slot overlap with it but just is that slot have an appointment. I have the following SQL so far ALTER TABLE appointments_slot ADD CONSTRAINT time_range_unique EXCLUDE USING gist (time_range WITH &&) WHERE (MISSING PART); Is there any way to join or something here, I have tried many ways without success. Maybe I will finish adding an appointment_id column to Slot table. -
Check Json data is none in python
this is my json may be thousands of record data we request in django rest framework. { "a":1, "b":2, "c":3, ..... } if request.data['a'] == '': return JsonResponse({'error':1}) elif request.data['b'] == '': return JsonResponse({'error':1}) elif ..... ....... else: ...... I want to check data is not blank like above if... else. we can add if else condition but this is not possible to check all data from if else Please suggest me what is the best way to check this line of code in python. -
Return data to ajax wihout invoking
I use one ajax to pass data, execute some code and finally return a populated list via second ajax. The problem is when the second ajax returns data, Javascript does not realise some data is returned. Even though Django has already processed and returned successfully. I get the poulated list when I call the ajax second time not the first and sometimes the list is not updated. My question is: Why Ajax does not get data each time Django returns? Is not possible to return data to ajax without invoking? Is there any other way to solve the problem? This is what I am trying: views.py data_list = [] def invoke_ajax(request): if request.method == 'POST': try: # call is made to 'process_data' function # this return is always successful return JsonResponse('invoked successfully', safe=False) except Exception as e: return JsonResponse("failed", safe=False) else: return JsonResponse("failed", safe=False) def process_data(request): # populates 'data_list' return get_data(request) def get_data(request): # sends data back to ajax # fails sometimes or list is not updated return JsonResponse(data_list, safe=False) Ajax // first ajax document.addEventListener('DOMContentLoaded', function(){ $.ajax({ url: '/invoke_ajax/', dataType: 'json', type: 'POST', data:{ 'movie': 'pets' }, success: function (response) { console.log("response= ",response); }, error: (error) => { console.log(error); } … -
How can I use objects ( not string ) in django email module
I'm developing some alert system. I want to use objects with django Email. as the code below; 'sshFailResult' is the object from some tasks. but that email send 'sshFailResult' of string type. how can I use objects with Email module ? thanks in advance. sshFailResult=[] for i in range(0,sizeOfList): sshFailResult=sshFailResult +[preSshFailResult[i].split("=>")[0] i +=1 sshFailEmail = EmailMessage('[SOC SYSTEM]','sshFailResult',to=['myEmailAddr']) if sshFailResult: sshFailEmail.send() else: pass -
Python basics for before starting learning Django
I want to learn Django and I need some suggestions on how to start learning Django and what python basics should I need to learn before starting learning Django. -
Do I need to commit .env files into the repository?
I have just started learning backend dev using django. This is a very basic question. I have done the following : 1. I have created virtual environment and I have also installed django in venv. 2. I have setup a django server and super admin. 3. I have setup the config.json to protect my API key. 4. Included the same in .gitignore. My question is do I just commit the project files in the server folder alone? or should I also commit the .env folder to the repository? What happens if I do commit or do not? Please advice -
Single Code Base for Cross Platform and Mobile Django Project
My goal is to eventually learn to create cross platform mobile apps using Django as the backend, and react native. I currently only have experience using Django, and Flask for web development on the backend, and html, css, and JavaScript for the front end. I currently have no experience with react native but will begin learning it soon My first cross platform app I want to create will be a web app, and cross platform marketplace app similar to Craigslist or Letgo. If I use Django and react, will I be able to have only one code base that is shared for the web, IOS, and Android? Also, is a market place app with Django and react-native realistic? -
How to properly install Python and Django
I'm trying to set up a Python/Django dev environment on my LinuxMint 19.1 machine. I installed the newest version of Python 3.7.3, Pip and Django. It seemed to be working until I figured out it was not using the correct version of Python. All attempts to correct this have been difficult. When I typed python -V it would display Python 2.x. When I typed python3 -V it would display Python 3.6.8. So I updated the alternatives and configured python so now when I type python -V I get Python 3.7.3 and when I type python3 -V I still get Python 3.6.8. I saw that I had to reinstall Django for it to be associated with the new version of Python so I tried to install again using Pip but got an error (the same ModuleNotFoundError: No module named 'pip' error as below). So I uninstalled Pip and reinstall it. I went ahead and installed Pip. sudo apt install python-pip This reported that it worked fine. I then tried to install Django and got the same error again. pip install django Traceback (most recent call last): File "/usr/bin/pip", line 9, in <module> from pip import main ModuleNotFoundError: No module named 'pip' … -
Saving many-to-many relationship through intermediate model
I have a model that looks like this: class Post(models.Model): title = models.CharField(max_length=100, null=False) content = HTMLField() created_at = models.DateField(auto_now_add=True) authors = models.ManyToManyField(User) When I create a post like this: x = Post(title="blah", content="blah) How can I add multiple authors to this Post? The authors model is created as an intermediate model and I have not defined it. -
How to redirect to profile page with id user paramater?
I want redirect to user profile after click "Profile" dropdown. But profile need id user, I don't know to link views.py def profile(request, user_id): #Something.... return render(request, 'profile.html') urls.py path('profile/<int:user_id>/', views.profile, name='profile'), profile.html <a class="dropdown-item" href="{% url ???? %}">Profile</a>