Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ContactForm not showing up in footer
I am trying to add a contact form in the footer of my base.html. Try tracking down everything I can but can't seem to find why the 3 fields in my form are not showing up. This is my codes: forms.py from django import forms class ContactForm(forms.Form): contact_name = forms.CharField(max_length = 50) email_address = forms.EmailField(max_length = 150) message = forms.CharField(widget = forms.Textarea) views.py from django.shortcuts import render, get_object_or_404, redirect from .models import CoollegeProductModel, NonCoollegeProductModel from .forms import ContactForm from django.core.mail import send_mail, BadHeaderError from django.http import HttpResponse def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): subject = "Website Inquiry" body = { 'contact_name': form.cleaned_data['contact_name'], 'email': form.cleaned_data['email_address'], 'message': form.cleaned_data['message'], } message = "\n".join(body.values()) try: send_mail(subject, message, 'admin@example.com', ['admin@example.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('product/home.html') form = ContactForm() return render(request, "product/contact.html", {'form':form}) contact.html <!--Contact form--> <div style="margin:80px"> <h1>Contact</h1> <h4>Contact us directly if you have any questions</h4> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> </div> base.html <footer style="background-color: #e3f2fd"> {% include "product/contact.html" %} </footer> This is what the footer display: enter image description here Appreciate your help!! -
Operational Error while running unit tests Django
I have dockerized my Django app together with my postgres Database. However after the dockerization, the unit tests that i have written (not the SimpleTestCase but the TestCase ones) stopped running. I thought it could be because of the new db so I modifies the setting for the tests to run with the default DJango db: import sys if 'test' in sys.argv: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3' } } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': 5432, } } Still, I get the following error: Creating test database for alias 'default'... Traceback (most recent call last): File ".../.local/lib/python3.8/site-packages/django/db/backends/utils.py", line 82, in _execute return self.cursor.execute(sql) File ".../.local/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 411, in execute return Database.Cursor.execute(self, query) sqlite3.OperationalError: near "[1]": syntax error Any ideas what might be the problem and how it can be fixed? -
Django: Create superuser() got an unexpected keyword argument 'password'
I am trying to define my own user module by following the documentation, but I receive the following error message whenever I try to create my first super user. TypeError: create_superuser() got an unexpected keyword argument 'password' Some people seem to have solved it by commenting user.is_staff and user.is_admin but it didn't work for me. Any suggestions? My models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin # Create your models here. class MyAccountManager(BaseUserManager): def create_user(self, email, first_name, last_name, password=None): if not email: raise ValueError("Users must have an email address") if not first_name or last_name: raise ValueError("Users must have a first and last name") user = self.model( email=self.normalize_email(email), first_name=first_name, last_name=last_name, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, first_name, last_name): user = self.model( email=self.normalize_email(email), password=password, first_name=first_name, last_name=last_name, ) #user.is_staff = True user.is_superuser = True #user.is_admin = True user.save(using=self._db) return user class Account(AbstractBaseUser, PermissionsMixin): email = models.EmailField(verbose_name="email", max_length=60, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now_add=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) # Stupid name in Django - Basically is the "Login field" USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] objects = MyAccountManager() def … -
Files in django template
i have a problem when i am trying to show files download link in django templates error: AttributeError: 'NoneType' object has no attribute 'split' File "c:\users\ramin\appdata\local\programs\python\python36-32\Lib\wsgiref\simple_server.py", line 35, in close self.status.split(' ',1)[0], self.bytes_sent ---------------------------------------- AttributeError: 'NoneType' object has no attribute 'split' ---------------------------------------- models.py: from django.db import models class Book(models.Model): Title = models.CharField(max_length=100) Writer = models.CharField(max_length=100) Description = models.TextField() Image = models.ImageField(default='default.txt') File = models.FileField(upload_to='PDF/') def __str__(self): return self.Title views.py: from django.views.generic.list import ListView from . import models class BookListView(ListView): queryset = models.Book.objects.all() template_name = 'Book/BookList.html' template: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Books List</title> </head> <body> {% for x in object_list %} <h2><a href="">{{ x.Title }}</a></h2> <img style="width:100px" src="{{ x.Image.url }}"> <p><a href="{{ x.File.url }}" download="{{ x.Title }}">Download</p> {% endfor %} </body> </html> when i click on download link , i can download file successfully but i see this message -
Response time is so slow in Django API connected with Apache and mod_wsgi
I have a Django API in the ubuntu ec2 which is connected to Apache web server and installed mod_wsgi in python itself using pip. The Django API takes about 4 seconds to run. When I make concurrent requests the response time increases to a minute sometimes even more. Modwsgi supposed to make all those call work independent of each other right rather than making it work one after the other. I have no solution right now -
How is it possible to pass class attributes as arguments of my model class in django
How is it possible to pass class attributes as arguments of my model class? Maybe I am missing something For example: from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) I can get an instance of the above just by doing for example user=User.objects.filter(username='me')[0] Post(title='random title', content='dqwdf', author=user) which I find strange since the fields of the class are class attributes and not instance attributes. For example from Python: class Whatever: pay = 3 profit = 2 I know I cannot do Whatever(pay=3,profit=2) On topic another question: Does models.Model have its own init ? If yes since my Post class inherits from it then it should have same init. Is it correct for me to assume that it takes no arguments other than self? -
Django media files are not being display
I am trying to display the uploaded media files to a user on Django, however, although the GET request returns 200 which means the file exists I still cannot the image being displayed properly below is my configuration for uploading media files. MEDIA_URL = '/media/' MEDIA_DIRS = [ os.path.join(BASE_DIR,'media') ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') and in my project urls.py I have: static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT ) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) On my model the upload path is: image = models.ImageField(upload_to=upload_to_uuid('media/users_images/'), blank=True) which when an image is uploaded I can see that the file is added however, on my page I do not see the file and it shows me a thumbnail. How can I fix this? -
Unify multiple records of a cvs file - Django
I'm generating a CVS file from a database but I want to unify some records in only one row. The original CVS look like this: Model Name Configurations_variatons MODEL-1 Lipstick Grand Rouge Mate cod=23432, color=23432-150 MODEL-1 Lipstick Grand Rouge Mate cod=23770, color=23770-151 And I want to show with only one row per model but unifying the Configurations_variatons column: Model Name Configurations_variatons MODEL-1 Lipstick Grand Rouge Mate cod=23432, color=23432-150 - cod=23770, color=23770-151 The code to generate the cvs file: def cvs_file_generator(request): # Get all data from UserDetail Databse Table products = Products.objects.all() # Create the HttpResponse object with the appropriate CSV header. response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="csv_database_write.csv"' writer = csv.writer(response) writer.writerow(['Model', 'Name', 'Configurations_variatons']) for product in products: writer.writerow([product.model, product.name, product.configurations_variatons]) return response -
Cannot commit relation 'workorder_images' on an unsaved model
I am implementing an email_dispatch app, which contains an EmailObjectManager manager class that implements create_email_object, which creates the respective model EmailObject. My end goal is to use Celery to query the database and dispatch these emails at a periodic interval. I tried to do this in the save() function, but since EmailObject has a foreign key to the model being saved (WorkOrder), I have determined I need to use a post_save signal. I am getting an error relating to my WorkOrder's Image orderable, but am not sure how to resolve this issue. Here's my code: post_save signal function definition def create_email(sender, instance, created, **kwargs): if (EmailObject.objects.all(related_workorder=instance, status=instance.status).count() == 0): EmailObject.objects.create_email_object(workorder=instance, workorder_status=instance.status) print("Email created!") EmailObject & Manager class EmailObjectManager(models.Manager): """EmailObject Manager""" def create_email_object(self, workorder, workorder_status): email_object = self.create(related_workorder=workorder, status=workorder_status) print("Workorder email created") return email_object class EmailObject(models.Model): """EmailObject model.""" STATUS_CHOICES = ( ('o', 'Open'), ('c', 'Closed'), ('x', 'Cancelled'), ) related_workorder = models.ForeignKey('workorders.WorkOrder', related_name="emails", on_delete=models.CASCADE) status = models.CharField(max_length=1, blank=False, default="o", choices=STATUS_CHOICES) has_sent = models.BooleanField(default=False) objects = EmailObjectManager() def get_context(self, request): context = super().get_context(request) return context def __str__(self): return self.related_workorder.related_customer.name def save(self, *args, **kwargs): return super(EmailObject, self).save(*args, **kwargs) WorkOrder(models.Model) class WorkOrder(index.Indexed, ClusterableModel, models.Model): """Workorder model.""" same_as_customer_address = models.BooleanField(blank=True, default=False, verbose_name="Same as Customer") ....more Django … -
How to move from page refresh to dynamic in django
My Django website currently runs everything through page refresh. If i click on an upvote button, it updates the model and refreshes the page to show the question as voted up. What is the best way to move from this page refresh to a more dynamic in-page refresh? I have heard i should be using Ajax and Django rest framework. Is there a difference between this method and using something like React? -
How to limit Django's builtin auth allowed username characters?
I'm using the builtin auth app of Django not the django-allauth. Is it possible to limit the allowed special characters in Django's builtin auth app usernames? the default allowed characters are: Letters, digits and @/./+/-/_ I want to be: Letters, digits and ./_ Regards -
how to solve it when i get 'pythn is not found' as message?
hello everyone i hope you're all doing great basically i start developing in python using django , and for the editor im using VScode , i did already install python,django,pip and all of what is necessary in the terminal but i have a problem when try execute a command in the terminal using python (ig: python .\manage.py makemigrations) i get this message (Python cannot be found. Execute without argument to proceed) and literally i couldn't find any solution to this problem in the intrnet , i hope i can find some answers ps: i have windows 10 as ES thanks for everyone -
Django tag showing errors in html
I have this block of code in my django project: <div class="avatar-preview"> <div id="imagePreview" style="background-image: url({{ request.user.img_url }});"> </div> In Virtual Studio Code, it returns these errors: VSCODE PROBLEMS IMAGE But it's actually working, I mean, like the 'syntax' is wrong but the code works, the image is displayed correctly. How can I get rid of these errors? -
what is wroung in this code after data in this view?
I'm trying to save values in respected model by it shows error like this: File "/home/bikash/tt/nascent/nascent_backend/home/views.py", line 72, in dispatch user.save() AttributeError: 'NoneType' object has no attribute 'save' class CheckoutSessionView(TemplateView): def dispatch(self, request, *args, **kwargs): if request.method == 'POST': price1 = request.body price2 = price1.decode('utf-8') price11 = json.loads(price2) print(price11) print(type(price11),990, price11['json_data']['priceId']) password1 = price11['json_data']['password1'] password2 = price11['json_data']['password2'] name = price11['json_data']['name'] company = price11['json_data']['company'] contact = price11['json_data']['contact'] email = price11['json_data']['email'] user = User(name = name, username = company, email = email, contact=contact ) if password1==password2: user = user.set_password(password1) user.save() company = Company(title = company) company.owner = user company.save() company.members.add(user) how can i save this? -
Return something that is not a part of any model in Generics.listAPIView
How do you format data returned from the Generics.ListAPIView class before sending it to the front end? I want to add metadata to the return value, but I can't add any metadata that isn't already part of a model. For instance: class someList(generics.ListAPIView): serializer_class = someSerializer def get_queryset(self): return someQueryset() class someListSerializer(SurveySerializer): class Meta: model = someListModel fields = ['modelField'] class someListModel(Base): modelField=models.TextField(default="", blank=True) This would yield [{modelField:information},{modelField:information},{modelField:information}] What if I want [ {modelField:information, informationCalculatedFromQueryset:butNotPartOfModel}, {modelField:information, informationCalculatedFromQueryset:butNotPartOfModel},{modelField:information, informationCalculatedFromQueryset:butNotPartOfModel} ] informationCalculatedFromQueryset is not part of someListModel, so I can't just add it into fields. How do I manually append this information to the front end? Is this possible? -
How to display search results with ajax in django project?
I am working in a Django project where one of the functionalities will be that user could search a name (using a form), the view will search that name in database (after some transformation), and the results will be displayed below the form. At the moment, It is necesary that the entire page loads every time a search is submitted. I am working in apply ajax to make this dynamic. The problem is that when I return the search result as a JsonResponse, I am not able to see the data in the success function of ajax. Views.py def indexView (request): form = FriendForm () friends = Friend.objects.all () return render (request, "index.html", {"form": form, "friends": friends}) def searchFriend(request): if request.method =="POST": form = FriendForm (request.POST) if form.is_valid(): if request.is_ajax(): name = form.cleaned_data['name'] query = Friend.objects.filer(first_name__contains=name) print(query) return JsonResponse(list(query), safe=False) else: return JsonResponse(form.errors) Main.js $(document).ready(function() { $("#form1").submit(function() { // catch the form's submit event var search = $("#searchField").val(); $.ajax({ // create an AJAX call... data: $(this).serialize(), // get the form data method: 'post', dataType: 'json', url: "search/ajax/friend/", success: function(data) { // on success.. console.log(data) } }); return false; }); }); -
Django admin returns forbidden after saving in model
I have deployed my Django application using Apache with mod-wsgi and Nginx. However, when I try to add items using Django admin and after saving then it redirects me to a forbidden page like " You don't have permission to access /admin/core/item/ on this server". I have tried with permission solution and I gave my folder permission 777 but nothing changed. -
in django how to add data from html table without using form.py
how to save data from html table in django without using form.py. I am currently creating table in html with add button and after adding all rows in table i want to save it but i am not using form.py only view.py,html,model.py views.py school_name = request.POST['school_name'] m_pass_out = request.POST['m_pass_out'] medicalschool = MedicalSchool(school_name=school_name, m_pass_out=m_pass_out) medicalschool.save() models.py class MedicalSchool(models.Model): school_name = models.CharField(max_length=100) m_pass_out = models.DateField(max_length=100) doctor_profile = models.ForeignKey(DoctorProfile, on_delete=models.CASCADE) created_at = models.DateTimeField() updated_at = models.DateTimeField(blank=True, null=True) class Meta: db_table = 'medical_school' html <div class="container-lg"> <div class="table-responsive"> <div class="table-wrapper"> <div class="table-title"> <div class="row"> <div class="col-sm-8"> <h2>Medical School</h2> </div> <div class="col-sm-4"> <button type="button" id="medical" class="btn btn-info add- new"><i class="fa fa-plus"></i> Add New</button> </div> </div> </div> <table id="medicaltable" class="table table-bordered"> <thead> <tr> <th>Name of School</th> <th>Year of Graduation</th> <th>Actions</th> </tr> </thead> <tbody> <tr> <td id="medicaltext" name="school_name"></td> <td id="medicaldate" name="m_pass_out"></td> <td> <a id="medicaladd" class="add" title="Add" data- toggle="tooltip"><i class="material-icons">&#xE03B;</i></a> <a id="medicaledit" class="edit" title="Edit" data- toggle="tooltip"><i class="material-icons">&#xE254;</i></a> <a id="medicaldelete" class="delete" title="Delete" data- toggle="tooltip"><i class="material-icons">&#xE872;</i></a> </td> </tr> </tbody> </table> </div> </div> </div> -
Delete wordpress on website and replace it with django - Setting up website entirely with django
I own a webpage which has wordpress.org preinstalled. I have never done anything with it, but now it's about time. As I'm learning django, I would like to build my webpage with it instead of using the preinstalled wordpress. How do I go about it? I haven't found anything related to this topic searching the internet. This is the webpage with preinstalled wordpress I'm talking about. -
Can anyone explain why I am getting this exception?
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
Trying to find the ImproperlyConfigured error in Django
I know this error has been asked a lot, but I read lots of posts, but I couldn't find the solution to my problem. Can anyone please help me identify where is my error? It keeps appearing the following error: django.core.exceptions.ImproperlyConfigured: The included URLconf 'outside_world.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. outside_world\urls.py: from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path(r'admin/', admin.site.urls), path(r'', views.detail, name='detail'), path(r'trip/', include("trip.urls")), ] trip\urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('<int:question_id>/', views.detail, name='detail'), path('<int:question_id>/results/', views.results, name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ] trip\views.py: from django.shortcuts import render from django.http import HttpResponse def detail(request, question_id): return HttpResponse("You're looking at question %s." % question_id) def results(request, question_id): response = "You're looking at the results of question %s." return HttpResponse(response % question_id) def vote(request, question_id): return HttpResponse("You're voting on question %s." % question_id) When I remove path(r'trip/', include("trip.urls")), from outside_world\urls.py, it works perfectly, but I need to maintain this line. -
django.db.utils.ProgrammingError: relation does not exist
I developed a Django application deployed on DigitalOcean's Ubuntu server with Postgres db. Everything worked fine, without any problems, but today after adding new model, I'm getting this error: relation "documents_app_document" does not exist although I have this model, where some of my models inherits from Document model. But somehow it was deleted from database, and now I can't add it back to database after migration. How can I add that model as a table again to database ? -
why the form is invalid on post
I have records in my model. I want to list the existing records and edit and add more records. I successfully got the records to my template and edit. I can add new records also. it is working fine in template. But when I post the form is invalid and print invalid message as per my code http response. I can not figure out what is the mistake. Please advise. forms.py: class NewTransForm(forms.ModelForm): th_no = forms.DecimalField(max_digits=5,error_messages={"max_digits":"Transaction number should be less than 6 digits.","unique":"Transaction number already exists."}) class Meta: model = TransHeader fields = ['th_no','th_dt','th_type', 'th_code','th_cust_code','th_sm_code','th_ref'] ... urls.py: path('edit_sales_transaction_details/<int:trans_id>/',views.EditSalesTransaction, name="edit_sales_transaction"), views.py: def EditSalesTransaction(request,trans_id): # template_name= "wstore/edit_sales_transheader_input.html.html" # trans_id =kwargs['trans_id'] if request.method == "POST": print(request.POST) form = NewTransForm(request.POST) if form.is_valid(): # trans_id =kwargs['trans_id'] exist_trans_header = TransHeader.objects.get(id=int(trans_id)) TransBody.objects.filter(trans_header=exist_trans_header).delete() exist_trans_header.delete() obj = form.save() books = request.POST.getlist('book_code') quantities = request.POST.getlist('quantity') prices = request.POST.getlist('price') for book_code,quantity,price in zip(books,quantities,prices): try: book = TextBook.objects.get(code=book_code) TransBody.objects.create(trans_header_id=obj.id,quantity=quantity,price=price,book=book) except Exception as e: print(e) if request.POST.get('save_home'): return redirect('saltransactions') else: print(NewTransForm.errors) # return redirect(reverse('view_sales_transaction', kwargs=kwargs['trans_id'])) return HttpResponse("form is invalid.. this is just an HttpResponse object") else: form = NewTransForm() context = {} # trans_id =kwargs['trans_id'] context['trans_header'] = TransHeader.objects.get(id=int(trans_id)) trans_body = TransBody.objects.filter(trans_header=context['trans_header']) context['trans_body'] = trans_body context['total_quantity'] = trans_body.aggregate(Sum('quantity')) context['total_price'] = trans_body.aggregate(Sum('price')) context['current_date'] = datetime.datetime.strftime(datetime.datetime.now(),"%Y-%m-%d") … -
How to implement carousel in django with col-md?
I would like to load django model instance in a js carousel with col-md. How should i do that? -
Django pre-save
I'm working on my first project with Django ,it's a personal blog the story model has 'beginning' filed that is first 100 characters of the story itself I want to create beginning with pre_save but I got error always : in admin section when I add a story and leave the beginning blank ,Django say 'this field is required'!! this works very good in another file here is the code : from django.db import models from django.db.models.signals import pre_save from my_blog_tags.models import Tag # Create your models here. class Story(models.Model): title = models.CharField(max_length=75) story = models.TextField() beginning = models.CharField(max_length=100) tags = models.ManyToManyField(Tag, blank=True) active = models.BooleanField(default=True) views = models.IntegerField(default=0) def __str__(self): return self.title class Meta: verbose_name = "story" verbose_name_plural = "stories" def story_pre_save(sender, instance: Story, *args, **kwargs): if not instance.beginning: story = str(instance.story) instance.beginning = story[:100] pre_save.connect(story_pre_save, sender=Story)