Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: form_valid and model validation
I am creating a car reservation application in Django. Users can create a Reservation for a given Car. This happens at /reservation/<car_id>/add. This form does not contain the Car field because the id is given in the URL. Now I want to add a validation to the Reservation model so no reservations can overlap. I have the following code (minimal version): # models.py class Car(models.Model): name = models.CharField(max_length=200) class Reservation(models.Model): car = models.ForeignKey(Car, on_delete=models.CASCADE) owner = models.ForeignKey(User, on_delete=models.CASCADE) start_time = models.DateTimeField() end_time = models.DateTimeField() def clean(self): # Check if overlaps with other reservations in self.car.reservation_set # views.py class ReservationAdd(LoginRequiredMixin, CreateView): template_name = 'reservation/reservation_add.html' model = Reservation form_class = ReservationAddForm def form_valid(self, form): form.instance.car = Car.objects.get(pk=self.kwargs['car_id']) form.instance.owner = self.request.user return super().form_valid(form) # forms.py class ReservationAddForm(forms.ModelForm): class Meta: fields = ('start_time', 'end_time') model = Reservation Now I get the following error at the Reservation.clean method: reservation.models.Reservation.car.RelatedObjectDoesNotExist: Reservation has no car. It seems to me that the clean method gets called before the form_valid method. So my design is not entirely correct I think. What is the correct way to do this? -
how to iterate all the column value using filters in Django
I'm trying extract user information from database. I have Signup database. If user already registered it will allow to login and i want to fetch login user all information from database and i want to store that information to variable. -
Django TypeError: keys must be str, int, float, bool or None, not News_Channel
Thisi is my login view. def login(request): username = request.data.get("username") password = request.data.get("password") if username is None or password is None: return Response({'error': 'Please provide both username and password'}, status=HTTP_400_BAD_REQUEST) user = authenticate(username=username, password=password) if not user: return Response({'error': 'Invalid Credentials'}, status=HTTP_404_NOT_FOUND) token, _ = Token.objects.get_or_create(user=user) voting_result = Count.objects.filter(userId=user.id) print(voting_result) channel = {} for e in voting_result: channel[e.channelId] = e.rate return Response({'token': token.key, 'user': user.username, 'email': user.email, 'id': user.id, 'stats': channel}, status=HTTP_200_OK) I want to add a dictionary channel in my response. But I am getting this error. keys must be str, int, float, bool or None, not News_Channel What should I do so that I have channel dictionary also in my response? I will use it in my react app. -
Processing files stored on cloud (S3 or Spaces)
I've setup a script to process excel files uploaded by a user. The scripts works fine when the file is stored on the local disk. from openpyxl import load_workbook wb = load_workbook("file_path.xlsx") # Load workbook from disk works fine ws = wb.worksheets[0] I've then setup django-storages to allow user uploaded files to be stored on digital ocean spaces. My problem now is how to access and process the cloud stored file. For the record, if I pass the file URL to load_workbook it fails with the error No such file or directory: file_url. Do I have to download the file using wget and then process it as a local file? Feels inefficient? What options do I have? -
Implementing multiple window support in a chatbot
I am currently implementing a Chatbot purely in python with the following technologies: Django as the main backend, with Django Channels for WebSockets RASA NLU for the NLU component of the chatbot and a finite state machine model implemented using pytransitions for the dialog management in python In my current implementation, each time the user starts a new chat from a session, another Chatbot instance is launched and hence the Chatbot starts from the initial state. I wish to change that behaviour and make it similar to let's say chat on Facebook/Messenger, in which you can seamlessly move between sessions while having a chat without inconsistencies. Namely, I want these attributes: If the user enters anything from let's say session A it should be immediately visible in all ongoing sessions. Similarly, the Chatbot reply should be visible in all the devices immediately. Have all sessions show the same chat history To implement the first point, I used this example from the django-channels docs and modified it by creating a single group/chatroom for each user. All the sessions from the same user get connected to the same group/chatroom and hence receive all the messages in the group/chatroom regardless of where they … -
Unable to display Post title at comment delete page
my community site has post objects and comments can be related to them. I have a extra comment delete template where i want to display the post title at the breadcrumbs of the page but for some reasone im unable to display the title as soon as i set the post object at the views.py context, any hint would be helpful. What im doing wrong here? views.py def comment_delete(request, pk): comment = get_object_or_404(Comment, pk=pk) post = get_object_or_404(Post, pk=pk) if request.user == comment.author: if request.method == 'POST': comment.delete() messages.success(request, 'You have successfully deleted the comment.') return redirect('post_detail', pk=comment.post.pk) else: template = 'app/Post/post_comment_delete.html' form = CommentForm(instance=comment) context = { 'comment': comment, 'form': form, 'post': post } return render(request, template, context) else: messages.warning(request, 'Comment could not be deleted.') return redirect('post_detail', pk=comment.post.pk) template.html: <a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }} </a> -
How to avoid django test methods interfering with each other
I am currently writing some django tests for my app1 and run into a weird error. I have a test method which simply performs a get request and checks the status_code of the response. That test works fine, but whenever this test is included in my test run, tests in app 2 suddenly fail. I have these type of get requests in other suits which work fine and cause no problems. Taking out the test method, or simply the get request resolves the issue again. I tried to call different urls, resulting always in the same error. I also tried to give the test method different names without success. test_folder |_ init.py |_ base.py |_ test_app_1 | |_ test_view1.py | |_ init.py |_ test_app_2 |_ test_view_2.py |_ init.py # test_folder/test_app_1/test_view1.py from tests_folder.base import BaseTestCase class CaseOneGIPTestCase(BaseTestCase): def setUp(self): self.client.login(username='temporary', password='temporary') def test_app1(self): resp = self.client.get(reverse('planning1')) self.assertIs(resp.status_code, 200) def test_true(self): self.assertTrue(True) # test_folder/base.py from django.test import TestCase from django.contrib.auth import get_user_model class BaseTestCase(TestCase): @classmethod def setUpTestData(cls): User = get_user_model() user = User.objects.create_user('temporary', 'temporary') The following traceback is only present when the test method test_app1 is present and a get request is contained in the method: Traceback (most recent call last): File … -
How to fix "TypeError at /orders/create/ argument of type 'DeferredAttribute' is not iterable" when using Django Payment Gateway (Paytm)
My issue is with implementing Payment Gateway in my e-commerce project . The Payment Gateway I am using is "Paytm" from the country India. After visiting their Website , https://developer.paytm.com/docs/v1/payment-gateway. I collected my Test ID and Secret Key. I have a checkout page where once the user enter his/her details. He is redirected to a successful ordered placed page with a order ID. Everything is working fine. However, now when i start implementing my payment gateway , I run into an error "argument of type 'DeferredAttribute' is not iterable" in my views.py file of my orders app. Firstly I installed pycryptodome with pip3 I made a directory named "payTm" under my src folder. I made a new python file named "Checksum.py".(which i copy pasted from paytm's website) So my problem arises under my views.py file. views.py (In the orders app) from django.shortcuts import render from .models import OrderItem , Order from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import csrf_exempt from .forms import OrderCreateForm from cart.cart import Cart from payTm import Checksum from django.http import HttpResponse MERCHANT_KEY = 'my_merchant_key'; @csrf_exempt def handlerequest(request): return HttpResponse('done') pass @login_required def order_create(request): cart = Cart(request) if request.method == 'POST': form = OrderCreateForm(request.POST) if form.is_valid(): order = … -
Using crispy in django to change the field size
I have a very simple form for my template. I would like to change its size. How can you do this? by adding a widget in my forms.py file or by adding a certain class in my template? My template: <form method="POST"> {% csrf_token %} <div class="form-row"> <div class="form-group col-md-12 mb-0"> {{ basic_form.choices_product|as_crispy_field }} </div> </div> <button type="submit" class="btn btn-lg btn-block btn-danger">Wyszukaj <i class="fas fa-heart fa-lg"></i></button> </form> I was looking for information on the internet, but to no avail. Any help will be appreciated. I use Bootstrap 4, Django 2+. -
How load template from another App through Main App
I just started learn Django and got a problem. I have a Main App, that must include another apps. My Main app has url localhost: port/main/. I have main template, which consist header, content and footer. In header I load Menu. How load News template in content block, when url will localhost: port/main/news. I use CBV. -
How to change color of stars (for ratings) by retrieving the rated value from database in Django?
I am working on Django.I am taking ratings from user through stars (radio buttons) by using Ajax and saved them in Django database. But the problem is when i move back to that page the stars become unrated. I want to save the changed color of stars, once rated by the user by retrieving that particular value from database. How would I do this? Please if any one could help it would be really appreciated. Note: I have tried django-star-ratings but the next logic I have to implement from ratings is not compatible with star-ratings. -
Handle large number of html form fields in django
I have a huge form with almost hundred fields and some of the fields are dynamically created. I am using pyodbc for database connection that is why I am not using django forms. I have to collect all hundred fields from post request and then save them after validation. Collecting all fields is not easier especially due to dynamic fields. Form is divided into multiple tabs and I have to submit complete form in one attempt. I am looking for a better solution than if there is any. -
urls of another apps?
i have Two Apps in Django , Student and Class which has One to Many Relationship , now i want to make views Student List and Student Add , which work perfectly once i import other App Class Views it does not work below are the code from django.contrib import admin from django.urls import path from StudentClass import views from Student import views urlpatterns = [ path('', views.StudentAdd,name='home'), path('list/',views.StudentList,name='list'), path('enrol/',views.StudentEnroll,name='enrol'), path('classhome',StudentClass.views.ClassEntry, name='classhome'), path('classhome',views.ClassEntry, name='classhome'), path('admin/', admin.site.urls), ] -
How to get the field name based on the field type?
I want to get the field name and do some operation on it based upon the field type. Let's say, the model is: class Model1(models.Model): m1 = models.FileField(...) m2 = models.CharField(...) m3 = models.IntegerField(...) I want to create a method which detects the fieldfield and deletes it. I thought of using meta dictionary. This is the method I created: from django.db.models.fields.files import FieldFile def method_name(instance): for nm, cls in instance.__dict__.items(): if type(cls) is FieldFile: instance.nm.delete() The above method didnt work as the type for the filefield is 'str' rather than a filefield. I will appreciate any solutions. -
django form errorlist "This field is required" with extra field and upload file
I have problems to get data back to my django view with a form. I have a model form with a filefield ("file"), and added an extra charfield ("paths"). My initial view allow to get the uploaded file, but when I tried to integrate the other charfield, it doesn't work, and I always get the error bellow (at the end): I should precise that I m working with jquery.uploadfile and I use Drag and Drop to set the "file" field. At the beginning the form wasn't necessary in the template, it should be created automatically with the jquery.uploadfile library I think. I think I already read all the related answers in other posts, can't find a solution :) this is my form : class MonsterForm(forms.ModelForm): paths = forms.CharField() class Meta: model = Monster fields = ('file','paths',) this is my post function view that works fine for the upload, where I got the error: def post(self, request): form = MonsterForm(self.request.POST, self.request.FILES) print(form.errors) if form.is_valid(): ''' trying to get the field value here ''' print("post : ",self.request.POST.get('paths')) temp_file = form.save(commit=False) ''' some code ''' temp_file.save() # data.result sent back to template : data = {'is_valid': True, 'name': temp_file.title, 'url': temp_file.get_absolute_url()} ''' just … -
Tinymce is not showing in django admin
I´ve installed tinymce on my localhost, and everything worked fine. Then i copied it to the pythonanywhere server and there is only the normal content field witouht tinymce. Maybe someone know where the problem is? I think there is a mistake with pip and python, but i dont know how to search for it. On my localhost i use python 3.7, but on pythonanywhere i created a env. with python 3.5. My configs are fine, because i copied everything from my localhost. Every requirement is also satisfied. Maybe someone has a tip for me where my mistake is? The error log says: from django.urls import path, include, re_url ImportError: cannot import name 're_url' 2019-05-17 11:12:21,984: Not Found: /favicon.ico 2019-05-17 11:12:33,240: Not Found: /static/django_tinymce/jquery-1.9.1.min.js 2019-05-17 11:12:33,263: Not Found: /static/django_tinymce/init_tinymce.js 2019-05-17 11:12:33,267: Not Found: /static/tiny_mce/tiny_mce.js 2019-05-17 11:12:33,533: Not Found: /static/tiny_mce/tiny_mce.js 2019-05-17 11:12:33,677: Not Found: /static/django_tinymce/jquery-1.9.1.min.js 2019-05-17 11:12:33,821: Not Found: /static/django_tinymce/init_tinymce.js 2019-05-17 11:12:41,567: Not Found: /static/tiny_mce/tiny_mce.js 2019-05-17 11:12:41,573: Not Found: /static/django_tinymce/init_tinymce.js 2019-05-17 11:12:41,581: Not Found: /static/django_tinymce/jquery-1.9.1.min.js 2019-05-17 11:12:41,727: Not Found: /static/django_tinymce/init_tinymce.js 2019-05-17 11:17:45,313: Not Found: /favicon.ico 2019-05-17 11:17:52,891: Not Found: /static/tiny_mce/tiny_mce.js 2019-05-17 11:17:52,912: Not Found: /static/django_tinymce/jquery-1.9.1.min.js 2019-05-17 11:17:52,917: Not Found: /static/django_tinymce/init_tinymce.js 2019-05-17 11:17:53,181: Not Found: /static/tiny_mce/tiny_mce.js 2019-05-17 11:17:53,324: Not Found: /static/django_tinymce/jquery-1.9.1.min.js 2019-05-17 11:17:53,480: … -
Django/Python How can I Localize Quotes for Rendered Text?
I generate a text like this: Are you sure to delete "{{ object.name }}"? The name of the object is sometimes set into quotes, sometimes not. I am aware, I could just create a localized string with quotes like "„%s“" add a comment, and let it get translated for each language. This would be my plan B, because choosing the correct quotes is more a topic of typography as of translation and often done wrong. Therefore if it is somehow possible to resolve the correct quotes for the current locale would make this simpler and safer. Therefore my question: Is there a way/function to automatically generate correct quotes for the currently selected locale? -
How can I add padding to fields in Django admin?
I am using Django Admin to access to data of some projects. To be able to have a proper view I have some class: class Whatever(models.Model): user = models.ForeignKey(User, blank=True, null=True, on_delete=models.CASCADE) date = models.DateTimeField(blank=False, null=False, default=datetime.utcnow) view = models.CharField(max_length=256, blank=False, null=False) To which I added the __str__ method with a specific formatting that contains the {:X} padding to set X characters to a field: def __str__(self): username = self.user.username if self.user else "" return "{:25} - {:30} - {:32}".format(self.user., self.view, self.date) However, in the Django admin, all the padding is ignored, so all I got is a set of lines on the format: bla - my_view - 2019-05-14 17:18:57.792216+00:00 another_user - another_view - 2019-05-14 16:05:27.644441+00:00 Without any padding, while I would like something like: bla - my_view - 2019-05-14 17:18:57.792216+00:00 another_user - another_view - 2019-05-14 16:05:27.644441+00:00 In normal Python, if I do: class M(object): def __init__(self): self.a = "hola" self.b = "adeu" def __str__(self): return "{:25} - {:30}.".format(self.a, self.b) It works well: >>> print(m) hola - adeu . I'm in Python 3.6.8 and Django 2.1.5. -
I'd like to know the best Django course to do on Pluralsight for someone withouth any Django experience
I want to do a Django tutorial on Pluralsight but I don't know which one -
Python. Django. Models. Generating unique slug for existing database records. "TypeError: id() missing 1 required positional argument: 'self'"
I'm getting an error TypeError: id() missing 1 required positional argument: 'self' when doing this: class BlogPost(models.Model): def __str__(self): return self.title def id(self): return self.id default_slug = 'this-is-myslug-{}'.format(id()) title = models.TextField() slug = models.SlugField(unique=True, default=default_slug) content = models.TextField(null=True, blank=True) and then creating migrations with Django. I would like the default slugs look like this: - this-is-myslug-1 - this-is-myslug-2 - this-is-myslug-3 etc. PS. Just in case... I have added default_slug object to BlogPost model later in the course of development but been getting this kind of error django.db.utils.IntegrityError: UNIQUE constraint failed: new__blog_blogpost.slug so I guess I had to make it unique. -
Upload Generated Pdf to Django Model
I am currently building a web app in which I generated a pdf of data from Django models, with the reportlab library and downloading it as HttpResponse(content_type='application/pdf') and its working correctly. Its returning from a view now I want to upload it to a Django model instead of downloading it. Is it possible please help me out it's about my Final Year Project? I shall be very thankful to you. I am currently using Django latest update and the reportlab library for generating pdf. Below is the function which is generating pdf and returing it as HttpResponse. def format1(personal_info,education,skills,experience,statement,languages,user): education_list = list() skills_list = list() experience_list = list() for i in education: temp_dict = dict() temp_dict["degree"] = i.Degree temp_dict["institute"] = i.Institute temp_dict["city"] = i.City temp_dict["grade"] = i.Grade education_list.append(temp_dict) for i in skills: temp_dict = dict() temp_dict["skill"] = i.Skill_Title temp_dict["level"] = i.Level temp_dict["description"] = i.Description skills_list.append(temp_dict) for i in experience: temp_dict = dict() temp_dict["job"] = i.Job_Title temp_dict["organization"] = i.Organization temp_dict["city"] = i.City temp_dict["timeperiod"] = i.TimePeriod experience_list.append(temp_dict) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment;filename=' + user + ".pdf" c = canvas.Canvas(response, pagesize=letter) width,height = letter # profile information c.setFont("Helvetica-Bold",22) c.drawString(0.5*inch,height-0.7*inch,personal_info[0].FullName) c.setFont("Helvetica",12) c.drawString(0.5*inch,height-0.9*inch,personal_info[0].PermanentAddress) c.drawString(0.5*inch,height-1.1*inch,personal_info[0].Email) c.drawString(0.5*inch,height-1.3*inch,personal_info[0].Phone) # horizontal line c.line(0.5*inch,height-1.5*inch,width-0.5*inch,height-1.5*inch) # education section c.setFont("Helvetica-Bold",18) c.drawString(0.5*inch,height-2*inch,"Education") … -
Access blocked by CORS headers
I am working on a project with Django that serves data through API via Django Rest Framework on a React frontend. The Browsable API works fine, however, the react frontend is giving an error in the console. I have installed django-cors-headers successfully. import './App.css'; class App extends Component { state = { products: [] }; async componentDidMount() { try { const res = await fetch('http://127.0.0.1:8000/products/'); const products = await res.json(); this.setState({ products }); } catch (e) { console.log(e); } } render() { return ( <div> {this.state.products.map(products => ( <div key={products.id}> <h1>{products.prodName}</h1> <span>{products.description}</span> </div> ))} </div> ); } } export default App; Access to fetch at 'http://127.0.0.1:8000/products/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. -
httpd.conf error on include django.conf and duplicate wsgi name
want to set up my Django in Apache server using wsgi I have already install mod_wsgi but when I make django.conf and try to include it in my etc/apache2/conf.d/includes/pre_main_global.conf to get include to my httpd.conf i got this error in my whm Sorry, you cannot update the include files at this time. Your Apache configuration file currently has a syntax error. Error: The “/usr/sbin/httpd -DSSL -t -f /etc/apache2/conf/httpd.conf -C Include "/etc/apache2/conf.modules.d/*.conf"” command (process 17945) reported error number 1 when it ended. Configuration problem detected on line 12 of file /etc/apache2/conf.d/django.conf: Name duplicates previous WSGI daemon definition. --- /etc/apache2/conf.d/django.conf --- 6 7 8 Require all granted 9 10 11 12 ===> WSGIDaemonProcess centos python-path=/home/zporta6/public_html/cgi-bin/django1/project1:/home/zporta6/public_html/cgi-bin/django1/lib/python2.7/site-packages <=== 13WSGIProcessGroup centos 14WSGIScriptAlias / /home/zporta6/public_html/cgi-bin/django1/project1/project1/wsgi.py --- /etc/apache2/conf.d/django.conf --- I try to change the name of project1 I thought maybe name duplicated but still the same result any idea what should I do my django.conf is Alias /static /home/zporta6/public_html/cgi-bin/django1/project1/static <Directory /home/zporta6/public_html/cgi-bin/django1/project1/static> Require all granted </Directory> <Directory /home/zporta6/public_html/cgi-bin/django1/project1> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess centos python-path=/home/zporta6/public_html/cgi-bin/django1/project1:/home/zporta6/public_html/cgi-bin/django1/lib/python2.7/site-packages WSGIProcessGroup centos WSGIScriptAlias / /home/zporta6/public_html/cgi-bin/django1/project1/project1/wsgi.py -
Duplicate when refreshing a div
I'm trying to update the div of a template with Django, so I use AJAX to refresh. The refresh works but during the first refresh, everything that was outside the div is doubled but only for the first refreshment . I've been blocking for quite a few days and I don't understand why, I applied the method found on this subject:Refresh a div to shows new rating in Django using JQuery and AJAX So I include another page "update.html" which contains my variables to update. And with ajax, I refresh this page. I'm sorry for the amount of code I provide, but I despair. Thank you for your feedback My view.py def RPI(request,rpi_id): form = ContactForm(request.POST or None) form2 = Boutons(request.POST or None) formtest= test(request.POST or None) Pactive = sql.run("Pactive") ## peut être passer en thread pour eviter l'attente de la nouvelle informaion et ralentir le code Preactive = sql.run("Qreactive") Courant = sql.run("I") conf_thread = connect.conf() conf_thread.start() time.sleep(1) power,statut=conf_thread.getConf() val ="" if form2.is_valid(): val=form2.cleaned_data.get("btn") if val == "Start" : connect.start() if val == "Reboot" : connect.reboot() if val == "Stop" : connect.stop() if val == "Code" : connect.code_util() if val == "fichier" : print("fichier") #file.FilepathName if val == "Envoyer code": … -
how to read subfolders of a directory and write to a text file in django view
I have to read subfolder names of a directory and write it to text file in a django view I have already tried the following code but the UI doesnt load with this code. def start(request): try: cwd=os.getcwd() os.chdir("/Volumes/localStorage2/DHLData/DHLs") subfolders=os.listdir() os.chdir(cwd) file = open("/Volumes/localStorage2/DHL/UI/dhl_list.txt", "w") for i in subfolders: file.write(i) file.close() I have written the whole code of the view def start(request): try: #cwd=os.getcwd() # os.chdir("/Volumes/localStorage2/DHLData/DHLs") #subfolders=os.listdir() # os.chdir(cwd) # file =open("/Volumes/localStorage2/DHL/UI/dhl_list.txt","w") # for i in subfolders: # file.write(i) # file.write("\n") # file.close() dhl_list = [] if os.path.exists("/Volumes/localStorage2/DHLData/DHLs"): with open("/Volumes/localStorage2/DHL/UI/dhl_list.txt") as dhlListFile: for dhl_name in dhlListFile: dhl_list.append(dhl_name) return render(request, "i3_flow.html",{"dhl_list":dhl_list}) except Exception: print(traceback.format_exc()) return render(request, "i3_flow.html")