Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin - "Please enter the correct email address and password for a staff account" AND user exists
Screenshot failing attempt to log in to django admin panel with an existing user Using a custom User model where the required fields are email, DOB, phone and password. models.py class UserManager(BaseUserManager): def create_user(self, email, date_of_birth, phone, password=None): """" Creates and saves a User with the given email,phone, date of birth and password. """"" if not email: raise ValueError('Users must have an email address') if not phone: raise ValueError('Please provide a phone number') user = self.model( email=self.normalize_email(email), date_of_birth=date_of_birth, phone=phone ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, date_of_birth, phone, password=None): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( email=email, password=password, date_of_birth=date_of_birth, phone=phone ) user.is_admin = True user.save(using=self._db) return user class User(AbstractBaseUser, auth_models.PermissionsMixin): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) first_name = models.CharField(max_length=80) last_name = models.CharField(max_length=80) phone = models.CharField(max_length=80) city = models.CharField(max_length=80) province = models.CharField(max_length=80) street = models.CharField(max_length=60) postcode = models.CharField(max_length=16) date_of_birth = models.DateField() date_joined = models.DateTimeField(default=datetime.now, blank=True) # Is the user currently active? is_active = models.BooleanField(default=False) # Is the user an app administrator? is_admin = models.BooleanField(default=False) # Is the user a Point Of Sale Owner? is_manager = models.BooleanField(default=False) objects = UserManager() class Meta: ordering = ('id',) USERNAME_FIELD = … -
Django with ajax Request
I have below code function OpenModal() { var fname="Quartz"; var mname="Rohit"; var lname="Patel"; var url="{% url 'display_modal' %}"+fname +"/"+mname+"/"+lname; alert(url); xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById('divcontent').innerHTML=this.responseText; } }; xmlhttp.open("GET",url,true); xmlhttp.send(); } How to execute the above code on click of a button in django templating language. url is like path('member/search/', views.displayModalView, name="display_modal"), -
Display all of a Users info on the one page within Admin
My Users have both a ONE-ONE personal_information table, and a ONE-ONE previous_studies table. I know that I could use Inline to display both the personal_information and previous_studies tables on the one page if they had a relationship, but within the admin panel I am instead wanting to click a User, then see both their personal_information and previous_studies (at the moment I need to access the User, personal_information and previous_studies on different pages). Any pointers on how to accomplish this would be greatly appreciated. Thank you. -
Populate dropdonw and multiselect from get_initial()
I am trying to prefill a CreateView form with date, get_initial() seems the right way. It uses a dict to prefill data. But how to fill dropdown and multiselect? What should I put in the dict? -
Django take value from url
I have problem with take value from url (? Site = value). When I had function in views.py it was work, but now I moved this to another file. Can someone solve this problem? functionAjax.py: def htmlMain(request): if request.is_ajax and request.method == "POST": UrlCut = request.GET.get('site','Main') Messages = NewsMessage.objects.all().order_by('-Data').values() context = { "Messags" : Messages } return render(request, 'ajax'+UrlCut+'.html', context) -
Name error at / in django while trying to use Users.objects.save_user
I am trying to create a bank form which can be saved to the database.I am getting name error exception value: name txt1 is not defined my app/views: from django.shortcuts import render,redirect from django.contrib.auth.models import User,auth # Create your views here. def formregister(request): if request.method=='POST': Name_of_branch=request.POST['txt1'] Purpose_of_loan=request.POST['POL1'] Type=request.POST['TOL1'] Amount=request.POST['A1'] Full_name_of_Ap=request.POST['FN1'] Minorities_zororashtrians=request.POST.get('r2', False) user=User.objects.create_user( Name_of_branch=txt1, Purpose_of_loan=POL1, Type=TOL1, Full_name_of_Ap=FN1, user.save(); print('user created') return redirect('form.html') else: return render(request,'form.html') This is my views. -
Select a specific button in Javascript/AJAX
I have a list where a user can save various items in a Django app. Next to each items I have a button that can be used to delete this item. Items are stored in a database and are displayed with a for loop. The problem is whatever button I press, the first one is selected and deleted. I am new to JavaScript but I do understand that my issue is coming from my var.product selector because .val() returns the first element that matches ('.substitut'). I have tried to tweak a little with $(this) but with no luck... How can I select each product in each button individually? My HTML: {% for saved in saved_list %} <form class="form_id" method='post'>{% csrf_token %}{{ saved.id}} <button class='substitut' value='{{ saved.id}}'><i class='fas fa-trash'></i></button> </form> {% endfor %} My AJAX: $(".form_id").on('submit', function(event) { event.preventDefault(); var product = $('.substitut').val(); console.log(product); var url = '/register/delete/'; $.ajax({ url: url, type: "POST", data:{ 'product': product, 'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val() }, datatype:'json', success: function(data) { if (data['success']) console.log(product); $("#fav_list").load(location.href + " #fav_list > *"); } }); }); -
How to add the option that checks if checkbox is checked and deletes checked objects in Django
Hello I'm a new comer to Django. I'm confused now having the thought of how django admin panel deleting option works and how to use that option in my site.The purpose is to use all CRUD options in one template not just with url like deleting one by one. I have a models.py: GRADES = ( ('1', '1',), ('2', '2',), ('3', '3',), ('4', '4',), ('5', '5',), ('6', '6',), ('7', '7',), ('8', '8',), ('9', '9',), ('10', '10',), ('11', '11',), ) class Grade(models.Model): grade = models.CharField(null=True, max_length=200, choices=GRADES, unique=True) def __str__(self): return self.grade class Unique_grade(models.Model): grades = models.ForeignKey( Grade, null=True, on_delete=models.SET_NULL, verbose_name="Sinf raqamini kiriting", ) A_B_C = models.CharField(max_length=1, null=True,) motto = models.TextField(max_length=200, null=True, verbose_name='Shior', blank=True, unique=True, default=None) class Meta: unique_together = ['grades', 'A_B_C'] def clean_motto(self): if self.cleaned_data['motto'] == "": return None else: return self.cleaned_data['motto'] def __str__(self): return f"{self.grades}-{self.A_B_C}" class Pupil(models.Model): first_name = models.CharField(max_length=200, null=True) surname = models.CharField(max_length=200, null=True) date_of_birth = models.DateField( null=True) nation = models.CharField( max_length=100, null=True, verbose_name="Nation") grade = models.ForeignKey(Unique_grade, null=True, on_delete=models.SET_NULL) m_full_name = models.CharField( max_length=200, null=True, verbose_name="Mother's full name") f_full_name = models.CharField( max_length=200, null=True, verbose_name="Father's full name") date_added = models.DateTimeField(auto_now_add=True) class Meta: unique_together = [ ['first_name', 'date_of_birth', 'surname', 'nation', 'grade', 'm_full_name', 'f_full_name'], ] def __str__(self): return f"{self.first_name} {self.surname}." my forms.py: … -
Django retrieve checkbox values sent by Ajax POST request
I am trying to send form data to Django server via Javascript Ajax request specifically checkbox values, but at the server I read None values. here's the server code that reads: @csrf_protect def order_pizza(request): if request.is_ajax() and request.method == "POST": topps = Topping.objects.all() for topp in topps: mytop = request.POST.getlist('topping') print(f"topp is {topp.__str__()} mytop is {mytop}") return HttpResponse("pizza order!!") And here's the html for the form: <form id="form_pizza_order" class="form_pizza_order" method="post"> {% csrf_token %} <div class="row"> <div class="order_topp_col col-12"> <header> Topping </header> {% for topp in toppings %} <input type="checkbox" id="{{ topp.name }}" name="topping" value="{{ topp.name }}"> <label for="{{ topp.name }}"> {{topp.name}}</label> {% endfor %} </div> ... the print function returns a result : topp is Pepperoni mytop is [] topp is Sausage mytop is [] topp is Mushrooms mytop is [] topp is Onions mytop is [] topp is Ham mytop is [] etc ... what do I have to do to be able to read the checkboxes values ? thanks. -
Django html form data is invalid with function as well as class based view
Unable to save the create view in the database as the POST request says all fields are required, even though the data is mentioned in the form fields before submitting. All the data fields are provided before submitting and the dropdown and checkboxes data is pre-populated as per context data correctly. models.py class RawMaterial(models.Model): rm_code = models.CharField(max_length = 10, unique = True) rm_name = models.CharField(max_length = 100, unique = True) rm_unit = models.ForeignKey(RMUnit, blank = False, on_delete = models.CASCADE) rm_category = models.ForeignKey(RMCategory, on_delete = models.CASCADE) rm_rate = models.FloatField() rm_tax = models.FloatField(null = True) rm_price = models.FloatField(blank = False) rm_vendor = models.ManyToManyField(Vendor) rm_store_issue_price = models.FloatField(null = True) rm_dept_use = models.ManyToManyField(Department) def __str__(self): return self.rm_name def get_absolute_url(self): return reverse('rm-create', kwargs=None) views.py class RawMaterialCreateView(CreateView): model = RawMaterial fields = '__all__' template_name = 'rm_registration.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['itemcode'] = generateCode(RawMaterial, 'RM', 'rm_code') context['categories'] = RMCategory.objects.all() context['units'] = RMUnit.objects.all() context['departments'] = Department.objects.all() context['vendors'] = Vendor.objects.all() return context def form_valid(self, form): itemcode = self.instance.itemcode print("Item Code is : " + itemcode) instance = form.save(commit=False) instance.save() return super(RawMaterialCreateView, self).form_valid(form) registration.html <form method="POST" action=""> {% csrf_token %} <div class="row"> <div class="form-group col-6"> <label for="rm_code">Item Code : </label> <input type="text" class="form-control form-control-sm" id="rm_code" value = "{{ … -
How to mutate django taggit in graphql?
@property def get_tags(self): return self.article_tag.all() @convert_django_field.register(TaggableManager) def convert_field_to_string(field, registry=None): return List(String, source='get_tags') conversion is working but mutation is not?? -
Django Rest Framework using Viewsets with different renderers
does it make sense to use Django Rest Framework also to render my HTML Code with Bootstrap and so on...? If no, what is the best solution to split the API endpoints and HTML view? I exposed an API with DRF Viewsets and JSON serializers. It's working pretty well. Additionally I would like to add a HTML rendered version of this API and design a HTML form for it. Both API and HTML rendered version are supposed to run on the same machine. Thanks in advance -
Getting not not a valid UUID when I migrate in Django
I added a field called transaction_id in my models.py I want that field to be used to track every transaction on my DuesLevy model I imported uuid for this to happen, but each time I migrate I get this error. How do i prevent this error from occurring each time I migrate (python manage.py migrate) "C:\Users\Benedict\Miniconda3\envs\django3\lib\site-packages\django\db\models\fields\__init__.py", line 2344, in to_python params={'value': value}, django.core.exceptions.ValidationError: ["'13615773708697' is not a valid UUID."] This issue have been reported Here but seems no solution yet. I am using Django 3 + MySQL models.py trans_id = uuid.uuid4() trans_str = trans_id.int pass_trans = str(trans_str)[:12] class DuesLevy(models.Model): class_of_dues = models.CharField(max_length=30, default=options.CHOOSE, choices=options.CLASS_OF_DUES, blank=True) payment_circle = models.CharField(max_length=30, default=options.CHOOSE, choices=options.PAYMENT_CIRCLE) payment_option = models.CharField(max_length=30, default=options.CHOOSE, choices=options.PAYMENT_OPTION) amount = models.DecimalField(max_digits=8, decimal_places=2) transaction_id = models.UUIDField(max_length=100, unique=True, null=True, blank=True, editable=False, default=pass_trans) payment_channel = models.CharField(max_length=30, default=options.CHOOSE, choices=options.PAYMENT_CHANNEL_TYPE) payment_date = models.DateField() date_recorded = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) description = models.TextField(blank=True, null=True) def __str__(self): return self.amount def get_absolute_url(self): return reverse('backend:detail_dues', kwargs={'pk': self.id}) -
How to implement Behaviour driven development (BDD) in Django rest framework?
My current company is planing to switch to behaviour driven development also known as BDD. After a long google search I came to the conclusion that behave is the semi official python package for BDD in python. I am wondering how could we practically implement BDD along with drf. What is the correct ideal way to Structure our test files. Where should we keep the BDD feature, step files? Which category would add fall under, unit testing, integration testing or acceptance testing? Thanks Ref : https://behave.readthedocs.io/en/latest/ -
Unable to redirect user to login page after registration using the redirect funtion in django
I am trying to redirect user to login page after registration and i am getting the Reverse for login not found error accounts/urls.py from django.urls import path,include from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', views.home, name='home'), path('about/', views.about, name='about'), path('articles/', include('articles.urls')), path('accounts/', include('users.urls')), path('admin/', admin.site.urls), ] users/urls.py from . import views app_name = 'users' urlpatterns = [ path('register/', views.register, name='register'), path('login/', views.login, name='login'), ] views.py def register(request): form = RegisterForm() if request.method == 'POST': form = RegisterForm(request.POST) print(request.POST) if form.is_valid(): form.save() user = form.cleaned_data.get('username') messages.success(request, 'Account was create for ' + user) return redirect('login') return render(request, 'register.html', {'form': form}) The error i got NoReverseMatch at /accounts/register/ Reverse for 'login' not found. 'login' is not a valid view function or pattern name. -
Dropdown menus inside the Django admin
I have a project foreign key in by Phase model. I'm having hard time Create a dependent drop-down list inside my Django admin page. I want to when user select a project from (project drop-down) phase of that project show in second dop-down What would be the best way to achieve this? It would be great if the dropdowns filter items based on the value of its parent. class Project(models.Model): name = models.CharFieldmax_length = 100, unique= True) short_name = models.CharField(max_length= 4, unique= True) slug = models.SlugField(max_length= 100, allow_unicode=True, null=True, editable= False) location = models.OneToOneField(Location, on_delete = models.SET_NULL, null= True, blank= False, verbose_name= 'موقعیت') start_date = models.DateField(default= timezone.now, null= True, blank= True) end_date = models.DateField(default= timezone.now, null= True, blank= True) duration = models.IntegerField(default= 0, editable= False) class Phase(models.Model): title = models.CharField(max_length= 20) class ProjectPhase(models.Model): project = models.ForeignKey(Project, on_delete= models.CASCADE, related_name= 'phase') phase = models.ForeignKey(Phase, on_delete=models.CASCADE, related_name= 'project') start_date = models.DateField(default= timezone.now) end_date = models.DateField(default= timezone.now) duration = models.IntegerField(default= 0, editable= True) -
Failed building wheel for python-ldap on centos8 and python 3.8.2
I am trying to install djang-auth-ldap on centos 8 with python3.8 on venv pip 20.1 from /home/centos/***/python38/lib/python3.8/site-packages/pip (python 3.8) ip install django-auth-ldap Collecting django-auth-ldap Using cached django_auth_ldap-2.1.1-py3-none-any.whl (20 kB) Requirement already satisfied: Django>=1.11 in ./***/python38/lib/python3.8/site-packages (from django-auth-ldap) (3.0.5) Collecting python-ldap>=3.1 Using cached python-ldap-3.2.0.tar.gz (367 kB) Requirement already satisfied: pytz in ./***/python38/lib/python3.8/site-packages (from Django>=1.11->django-auth-ldap) (2020.1) Requirement already satisfied: asgiref~=3.2 in ./***/python38/lib/python3.8/site-packages (from Django>=1.11->django-auth-ldap) (3.2.7) Requirement already satisfied: sqlparse>=0.2.2 in ./***/python38/lib/python3.8/site-packages (from Django>=1.11->django-auth-ldap) (0.3.1) Requirement already satisfied: pyasn1>=0.3.7 in ./***/python38/lib/python3.8/site-packages (from python-ldap>=3.1->django-auth-ldap) (0.4.8) Requirement already satisfied: pyasn1_modules>=0.1.5 in ./***/python38/lib/python3.8/site-packages (from python-ldap>=3.1->django-auth-ldap) (0.2.8) Building wheels for collected packages: python-ldap Building wheel for python-ldap (setup.py) ... error ERROR: Command errored out with exit status 1: how can I fix it? I have to use this package for exists project. can you help me please? thanks -
Table 'login' does not exists in database
I don't know why i am getting this problem now.It was working fine before,did i made some mistake at codes or so?Table exists in database Note: I use djongo (Mongodb) for database class User(AbstractBaseUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField( verbose_name='email address', max_length=255, unique=True ) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email class Meta: db_table = "login" -
How to take in user input in a Django website for internationalization?
I can translate my site but I am confused how to to translate my site in the language my user wants it to be. Should I make a form and take the input to change the language variable in my settings file? -
Why is Django migration not migrating table?
My django migration is not working properly. Out of three models I altered one model(table) in the initial version of my app and ran the makemigrations and then the migration command but the migration for that particular table did not happen properly so I thought there was some problem with the app. I deleted the table from the database and also created a new app and copied all the code from the first app to this one (including the code in the models, views, etc.). But when I use the migration commands, I still do not see the table in the database. The commands I use are python manage.py makemigrations python manage.py migrate Can anyone please help? -
Starting Dev Server for Django on windows
I installed Python 3.7, it was added to Path during installation, Then installed Django using the command "pip install django" and it got installed. I started a new project with the command "django-admin startproject pyshop ." and it created that folder with some .py files in it. Then I tried to run the dev server with the command "py manage.py runserver" and I get the response "Unable to create process using 'C:\Users\Prince M\AppData\Local\Microsoft\WindowsApps\python.exe manage.py runserver'" in my terminal. What can I do to fix this because this is what I am supposed to do even according to the django documentation. -
ManytoMany objects access in template django
There are 2 objects with a many-to-many relationship, trying to access one in the template through the other and an error POPs up: NoReverseMatch at /decision/livingrooms/kitchen/provans/ Reverse for 'style' with keyword arguments '{'rmslg': 'bathroom', 'stslg': ''}' not found. 1 pattern(s) tried: ['decision/livingrooms/(?P<rmslg>[-a-zA-Z0-9_]+)/(?P<stslg>[-a-zA-Z0-9_]+)/$'] But bathroom styles is not empty html: {% for room in all_rooms %} <li class="menu__item menu__item_interiors"><a href="{% url 'decision:style' rmslg=room.slug stslg=room.styles.slug|first %}">{{ room.name }}</a></li> {% endfor %} -
Django 3 TemplateSyntaxError: 'css/bootstrap.min.css' is not a registered tag library
I added bootstrap.min.css to my simple Django v3 project. So my home.html is something like so: {% load static %} <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Boards</title> <link rel="stylesheet" href="{% load static '/css/bootstrap.min.css' %}"> </head> <body> <div class="container"> <ol class="breadcrumb my-4"> <il class="breadcrumb-item active">Boards</il> </ol> <table class="table"> <thead class="thead-dark"> <tr> <th>Boards</th> <th>Posts</th> <th>Topics</th> <th>Last Post</th> </tr> </thead> <tbody> {% for each in boardlist %} <tr> <td> {{ each.name }} <small class="text_muted d-block">{{ each.description }}</small> </td> <td class="allign-middle">0</td> <td class="allign-middle">0</td> <td></td> </tr> {% endfor %} </tbody> </table> </div> </body> </html> And my project structure is: $ tree -I "*.pyc" forum/ forum/ ├── boards │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ ├── 0001_initial.py │ │ ├── __init__.py │ │ └── __pycache__ │ ├── models.py │ ├── __pycache__ │ ├── static │ │ └── css │ │ └── bootstrap.min.css │ ├── templates │ │ ├── home.html │ │ └── home.html.bak │ ├── tests.py │ └── views.py ├── database │ └── db.sqlite3 ├── forum │ ├── asgi.py │ ├── __init__.py │ ├── __pycache__ │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── manage.py 10 directories, 18 files But at the end when I run project I … -
How do I limit a text length and add dots to show continuation python django
Am working on an Ecommerce website using django. My problem is that some products name are longer that the other, which makes the product display look odd. Question: How do I limit the length of product name and add dots to show that it continue Example: product_name = "Men Suede Loafers Moccasins Shoes -Black" will look like product_name = "Men Suede Loafers Mocca...." -
Count(distinct) with multiple fields in django
Here I trying to convert Django rawsql quey to Django queryset. But the problem is - How to implement distinct in two fields. SQL quey - count(distinct ra, category) as order_type Django queyset - order_type=Count('ra', 'category', distinct=True) - giving error queryset = Model.objects.raw("select id,category,count(category) as total_orders, count(distinct ra, category) as order_type, SUM(CASE WHEN service_status = 'success' THEN 1 ELSE 0 END) as total_success_order, SUM(CASE WHEN service_status = 'failed' THEN 1 ELSE 0 END) as total_failed_order from table group by ra;") queryset = Model.objects.values('ra').annotate(category=F('category'),\ order_type=Count('ra', 'category', distinct=True),total_orders=Count('category'),\ total_success_order=Count('service_status', filter=Q(service_status='success')),\ total_failed_order=Count('service_status', filter=Q(service_status='failed'))).order_by() What should be the right syntax?