Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to change header/page title of User Add Page in Django admin
I'm working on Django.And I wanted to change the header in the User Add Page in the Django admin as marked with red color in the pic : admin.py file is : from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import CustomUser class CustomUserAdmin(UserAdmin): list_display = ('first_name','last_name','email','is_staff', 'is_active',) list_filter = ('first_name','email', 'is_staff', 'is_active',) search_fields = ('email','first_name','last_name','a1','a2','city','state','pincode') ordering = ('first_name',) add_fieldsets = ( ('Personal Information', { # To create a section with name 'Personal Information' with mentioned fields 'description': "", 'classes': ('wide',), # To make char fields and text fields of a specific size 'fields': (('first_name','last_name'),'email','a1','a2','city','state','pincode','check', 'password1', 'password2',)} ), ('Permissions',{ 'description': "", 'classes': ('wide', 'collapse'), 'fields':( 'is_staff', 'is_active','date_joined')}), ) So how to change the header of User Add page?? Thanks in advance!! -
Changing the default authentication message in django-rest-framework
In a simple TokenAuthentication system in Django Rest Framework, the default message when you fail to send a proper authorization token is this { "detail": "Authentication credentials were not provided." } I want all my API responses to follow a certain template e.g. { success, message, data } How can I overwrite this error message? What is the best practice when creating these API templates? P.S. I checked out other questions but couldn't find anyone with a similar problem. If it was already answered I'd be glad if you could point me to it. -
How can I read a dicctionary in template in Django
Hi I'm trying to read a dicctionary in a template in django, but I would like to separate the keys and the value, the key is what will be showed, and the value is the next url it has to go (I know that diccionary is a little bit strage but I think that's not a problem. Here is my code if anyone can help me. <ul> {% for i in respuestas %} <li><a href="/{{'respuestas.[i]'}}"><h2>{{i}}</h2></a></li> {% endfor %} </ul> That's the idea. Obviously it doesn't work because I'm asking here so, anyone know how can I do it?? Thank you!!!! -
DJANGO-User switch account issue
I noticed that when I am logged in as my profile (http://127.0.0.1:8000/user/admin/ ) and I go to my template where I have the list of all users ( http://127.0.0.1:8000/users/ ) and I click on another user(mattia_mibe) to see his/her profile it switched my account, so I don't see his/her profile but I see my profile (admin) with all my descriptions but at the same time the url is http://127.0.0.1:8000/user/mattia_mibe/ and it recognize @mattia_mibe as users, even what it displays is my profile's descriptions(admin). It's a bit complicated to explain, I post here some pictures in the case I did not explain the issue clearly. core/urls.py from django.urls import path from . import views urlpatterns = [ path("", views.homepage, name='homepage'), path("users/", views.UserList.as_view(), name='user_list'), path("user/<username>/", views.userProfileView, name='user_profile'), ] core/views.py from django.shortcuts import render, get_object_or_404 from django.contrib.auth.models import User from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic.list import ListView # Create your views here. from quiz.models import Questions from jobs.models import post_job def homepage(request): return render(request, 'core/homepage.html') def userProfileView(request, username): user= get_object_or_404(User, username=username) jobs = post_job.objects.all() categories = Questions.CAT_CHOICES scores = [] for category in categories: score = Questions.objects.filter(catagory=category[0], student= request.user).count() scores.append(score) context = { 'user' : user, 'categories_scores' : zip( categories,scores), 'jobs': jobs } … -
Trying to insert file into sql light using django
I am trying to do following to update record with file in sql light. This is function i am using to update record from django.db import connection def execute_query_2(query, data): with connection.cursor() as cursor: cursor.execute(query, data) rows = cursor.fetchall() return rows with open("test.text", "rb") as f: data = f.read() query = myquery execute_query_2(query, (str_date, file, id)) my query is as follows: UPDATE mytable SET str_date = ? and file_data = ? WHERE id = ? however, I am getting following error TypeError: not all arguments converted during string formatting Any idea how to fix it? -
why does date time function don't need migration when I set it to default?
In Django when I set my date/time to default default=datetime.now() It automatically migrated in models.py. Why I do not need to do migration for it? -
How to change button text onclick using django?
I'm working on a school project and I'm trying to change a button's innerHTML to a value I got from a dictionary in views.py. However, when I load the page with this code: <script> var docFrag = document.createDocumentFragment(); for (var i=0; i < 3 ; i++){ var row = document.createElement("tr") for (var j=0; j < 3 ; j++){ var elem = document.createElement('BUTTON'); elem.type = 'button'; elem.id = 'r'+i+'s'+j; elem.value = 'r'+i+'s'+j; elem.onclick = function () { document.getElementById("klik").value = this.id; document.getElementById("ID").value = this.id; document.getElementById("klik").submit(); var id = this.getAttribute('id'); var novi = document.createElement('BUTTON'); novi.type = 'button'; //alert("This object's ID attribute is set to \"" + id + "\".") novi.value = id; novi.innerHTML = {{vrijednost}}; this.parentElement.replaceChild(novi,this); }; elem.innerHTML = elem.value; docFrag.appendChild(elem); } document.body.appendChild(docFrag); document.body.appendChild(row); } </script> Nothing happens. The page is blank. When I change novi.innerHTML to something else, 'x' for example, the x appears for a very short time and then it disappears. Now, I think that every time I click on a button, I go to a an url named 'klik' from the form, but I don't know how to fix it. Any ideas? This is a part of my views.py code: def klik(request): ID = request.POST['ID'] print(ID) vr = r[ID] … -
Django 3. Send email with attachment file
I have a simple contact form on my Django 3 project. It's working fine and I have got masseges, but how can I make a function to the attachment file to my mail? I have FileField and some code in views.py, but its doesn't work. Any ideas? Versions: Python 3.6.5. Django 3.0.5. forms.py class ContactForm(forms.Form): name = forms.CharField(required=False, max_length=150, help_text="Name") email = forms.CharField(required=False, max_length=150, help_text="Email") file = forms.FileField(widget=forms.FileInput, required=False) message = forms.CharField(widget=forms.Textarea, help_text="Text area") views.py @csrf_exempt def contact_us(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): sender_name = form.cleaned_data['name'] sender_email = form.cleaned_data['email'] sender_file = form.cleaned_data['file'] message = "{0} New massege:\n\n{1}\n\n{2}\n\n{3}".format(sender_name, sender_email, form.cleaned_data['message'], sender_file,) send_mail('Subject', message, sender_email, ['to.my.mail@gmail.com']) return render(request, 'pages/thank-you.html') else: form = ContactForm() return render(request, 'flatpages/report.html', {'form': form}) HTML. <div class="col-12 col-md-6"> <div class="report"> <h3 class="report-title">Ваші дані</h3> <form method="post" action="/pro-upravlinnya/report/"> <div style="display:none"> <input type="hidden" name="csrfmiddlewaretoken" value="$csrf_token"/> </div> <div class="report-control"> {{ form.name.help_text }} {{ form.name }} </div> <div class="report-control"> {{ form.email.help_text }} {{ form.email }} </div> {{ form.file }} <div class="report-control"> {{ form.message.help_text }} {{ form.message }} </div> <div class="report-btn-wrp"> <button type="submit" class="report-submit" >Send</button> </div> </form> </div> </div> Output to my email: subject, name, email, text, None -
How to add custom CSS properties like font-size to all the Django admin pages?
I'm working on Django.And I want to add custom CSS properties like font-size to all the Django admin pages like User change page, User add page,etc in one go so that I don't have to put different different CSS properties for each and every pages individually. So is there any way to do that?? Thanks in advance!! -
Firebase and Django API
I'm want to start coding web platform(and perhaps later also make a mobile app for iOS and Android) and I recently started considering using Firebase. I really want to use its auth system, database system, and file storage system. I'm not really good at DevOps and I feel like Firebase can really make my life better. I want to use Django to create API and React with Next.js for frontend. API will have to do a few things with data, manage user's access, and their possible actions. I'm confused after all I've read on the internet about Firebase. 1. My frontend and backend have to be hosted somewhere else or can I host them on Firebase. 2. Is it even possible to create a fully working API that uses Firebase systems? Would such a thing be efficient? And how could I do that? And the most important question: Is using Firebase like that expensive? Will I not overpay? Maybe some of you have actual commercial experience with Firebase. -
django: header drop down menu with language selection
I am trying to include a language selector in my website header but the structure of it is giving me hard time. I am a beginner in web development and I cannot figure out how to pass my django form into this drop down button in the header. Here is what I have been able to do on my own so far: html <form id= "#language" action="{% url 'set_language' %}" method="post">{% csrf_token %} <input type="hidden" name="text" value="{{ redirect_to }}"> <select name="language" id=""> {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}" {% if language.code == LANGUAGE_CODE %} selected {% endif %} > {{ language.name_local }} ({{ language.code }}) </option> {% endfor %} </select> <button></button> {# <button> type="submit" value="Go">#} </form> </div> </div> <div class="nav-link dropdown"> <a class="nav-link dropdown" id="#language" href="" data-toggle="dropdown">LANGUAGE</a> <div class="dropdown-menu" aria-labelledby="language"> <a class="dropdown-item" href="">ENGLISH</a> <a class="dropdown-item" href="">FRENCH</a> </div> </div> the form only contains two languages and as you can see I don't know how to have the two choices inside of the language header dropdown button. Would anyone has a clue that could help me out? -
How to log in to Django with model class User
i am newbie in Django and DRF. I created object of User class(which is in models.py) and i want with THAT user log in to django. In a nutshell, create django user with model User class. How can i implement it? models.py class User(models.Model): username = models.CharField(max_length=20, unique=True) #login field in Angular password = models.CharField(max_length=30) first_name = models.CharField(max_length=30) # name field in Angular last_name = models.CharField(max_length=30) email = models.EmailField( unique=True, max_length=254, ) views.py class UserCreateAPIView(generics.CreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = [permissions.AllowAny] SerializerClass class UserSerializer(serializers.ModelSerializer): username = serializers.CharField(write_only=True) password = serializers.CharField(write_only=True) class Meta: model = User fields = '__all__' -
how to get exact object in django rest framework using class based view?
i am trying to create comment for every single post from flutter front end but i dont know how to provide the exact post i wanted t comment django:2.2 models.py class Comment(models.Model): id = models.UUIDField(default=uuid.uuid4,primary_key=True,editable=False) author = models.ForeignKey(Account,on_delete=models.CASCADE,related_name='comments') post= models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments') comment_content = models.TextField(max_length=400) commented_at = models.DateTimeField(auto_now_add=True) edited_at = models.DateTimeField(auto_now=True) image = models.ImageField(upload_to=random_url,blank=True,null=True) parent = models.ForeignKey('self',null=True,blank=True,on_delete=models.CASCADE,related_name='replies') active = models.BooleanField(default=True) this is the serializers.py class CommentCreateSerialzier(ModelSerializer): class Meta: model = Comment fields = [ 'comment_content','image' ] and this is my views.py class CommentCreateSerializer(CreateAPIView): serializer_class = CommentCreateSerialzier message = 'you dont have permission to comment' permission_classes = [IsAuthenticated] def perform_create(self): serializer.save(author=self.request.user) how to add default post object in every single post ? and does it the same for replies as well thanks for replying -
How to get the data from database between the input dates in Django
I have two attributes in my database fromDate = models.CharField(max_length=100) toDate = models.CharField(max_length=100) By taking user input as <input type="date" name="fromDate"> <input type="date" name="toDate"> I want to get all the data from database between this two dates. -
How to do custom validation in my Django Modelform?
I have a ModelForm for this model, with this unique_together: class Registration(models.Model): student_name = models.CharField(max_length=50) selected_season = models.CharField(max_length=2) selected_subject = models.ForeignKey(Subject, on_delete=models.CASCADE) student_address = models.TextField() student_phone = models.CharField(max_length=11) class Meta: unique_together = (('student_name', 'selected_season', 'selected_subject'),) The modelform is like this: class RegistrationForm(forms.ModelForm): student_address = forms.CharField(label='', widget=forms.Textarea(attrs={'class':'materialize-textarea'})) class Meta: model = Registration fields = '__all__' How do I raise a validation error if the unique_together requirement is not met? -
Django-rest-framework : create serializer for registration of two diferent user-type foreignkey relation with one custom user model
I want to create two user registration using one custom user. MODELS.PY class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True ) phone_number = PhoneNumberField(_("Phone number"),unique=True, blank=True, null=True) username = models.CharField(_("Username"),max_length=254,unique=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(auto_now=True) date_joined = models.DateTimeField(auto_now_add=True) full_name = models.CharField(_("Full Name"), max_length=50, null=True) date_of_birth = models.DateField(_("Birth date"), auto_now=False, auto_now_add=False, null=True, blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username',] class Aesthete(models.Model): basicuser = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) is_verified = models.BooleanField(_("Verified"), default=False) class Artist(models.Model): basicuser = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) is_verified = models.BooleanField(_("Verified"), default=True) debutsong = AudioField(upload_to='songsfile', blank=True, ext_whitelist=(".mp3", ".wav", ".ogg"), help_text=("Allowed type - .mp3, .wav, .ogg")) How can I create registration serializer and view please help. Thank you. -
Storing the Django project with the PostgreSQL database on GitHub
I changed the database from SQLite3 to PostgreSQL in my Django project. Is it possible to store my new database in the GitHub repository so that after cloning and running by the command python manage.py runserver the project has started with the whole database? -
Exclude python file from executions with server start in Django
I have some separate python file which fetches data from GitHub and store as dictionary. Execution of these files consumes times which makes django server to run or restart slower. This delay makes development time consuming. What is the proper way to organize external python files in project. Execution of these file is not required to be executed each time. Fetched can be stored in database and executions can be weekly. myProject> home> -views.py -urls.py -ABC.py (file need to exlude) -
How to customize Django ModelForm fields?
Hi I am trying to customize my ModelForm in Django. The form looks like this: class RegistrationForm(forms.ModelForm): class Meta: model = Registration fields = ['name', 'age', 'details'......] I am trying to add different classes to different fields, along with placeholders and no labels. How do I do that? Is there a way to carry this out in the templates? -
How to correctly override account-confirm-email view for django-rest-auth package
I try to write api using djangorestframework and django-rest-auth. Almost all the urls working correctly, but account-confirm-email. So in the registration.urls I see: urlpatterns = [ url(r'^$', RegisterView.as_view(), name='rest_register'), url(r'^verify-email/$', VerifyEmailView.as_view(), name='rest_verify_email'), # This url is used by django-allauth and empty TemplateView is # defined just to allow reverse() call inside app, for example when email # with verification link is being sent, then it's required to render email # content. # account_confirm_email - You should override this view to handle it in # your API client somehow and then, send post to /verify-email/ endpoint # with proper key. # If you don't want to use API on that step, then just use ConfirmEmailView # view from: # django-allauth https://github.com/pennersr/django-allauth/blob/master/allauth/account/views.py url(r'^account-confirm-email/(?P<key>[-:\w]+)/$', TemplateView.as_view(), name='account_confirm_email'), ] I understand that I should to override the last url view. But I don't understand how I can do it. I also fount the same problem Django Rest Auth - Key error on Email Confirmation But I don't understand that code. Maybe someone's going to help me with the problem and explain what happens. -
DJANGO - Multiple Users
I am building a platform in django and for the User registration I followed some tutorials, at this point I think it would be nicer if I can add a "new user registration". In my case "students" can register, login and navigate the platform but I would like also to make a new type of user ( staff) where they can registrate as staff, login and visit only one page where they can create some new quiz. I tried to look online but I can't figure out how to do it from this point I have already created. Could you please give me some advice/resources on how can I solve this problem? account/forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class FormRegistrazione(UserCreationForm): email = forms.CharField(max_length=30, required=True, widget=forms.EmailInput()) class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] account/views.py from django.shortcuts import render, HttpResponseRedirect from django.contrib.auth import authenticate, login from django.contrib.auth.models import User from accounts.forms import FormRegistrazione # Create your views here. def registrazioneView(request): if request.method == "POST": form = FormRegistrazione(request.POST) if form.is_valid(): username = form.cleaned_data["username"] email = form.cleaned_data["email"] password = form.cleaned_data["password1"] User.objects.create_user(username=username, password=password, email=email) user = authenticate(username=username, password=password) login(request, user) return HttpResponseRedirect("/") else: form … -
ValueError: Cannot assign "'auth.User'": "Token.user"
i am getting error while i generating token with user id. it's showing me error ValueError: Cannot assign "'auth.User'": "Token.user" must be a "User" instance. it would be great if anyone could figure me out where should i make changes in my code. thankyou so much in advance. views.py from rest_framework.authtoken.models import Token class Product_CategoryCreateAPIView(generics.CreateAPIView): # token = Token.objects.get_or_create(user=settings.AUTH_USER_MODEL) token = Token.objects.create(user=settings.AUTH_USER_MODEL) print(token.key) model = Product_Category queryset = Product_Category.objects.all() serializer_class = Product_CategoryAdd_Serializer -
I m getting error while am using crispy forms,
CrispyError at /cpm/domestic |as_crispy_field got passed an invalid or inexistent field views.py def Travel(request): form=forms.Travelform() if request.method=='POST': form=forms.Travelform(request.POST) if form.is_valid(): print("data inserted") return render(request,'Travelform.html',{'form':form}) return render(request,'Travelform.html',{'form':form}) Travelform.html {% extends 'base1.html' %} {% load crispy_forms_tags %} {% block content %} <div class="container text-center"> <h1>Domestic Travel Requisition</h1> </div> <form method="post"> {% csrf_token %} <div class="form-row"> <div class="form-group col-md-2 mb-0"> {{ form.Mobile_No|as_crispy_field }} </div> <div class="form-group col-md-2 mb-0"> {{ form.Request_Date|as_crispy_field }} </div> </div> {{ form.Trave_Type|as_crispy_field }} {{ form.Purpose_Description|as_crispy_field }} <div class="form-row"> <div class="form-group col-md-6 mb-0"> {{ form.Travel_Date|as_crispy_field }} </div> <div class="form-group col-md-6 mb-0"> {{ form.Journey_Type|as_crispy_field }} </div> <div class="form-group col-md-2 mb-0"> {{ form.From_Place|as_crispy_field }} </div> <div class="form-group col-md-2 mb-0"> {{ form.To_Place|as_crispy_field }} </div> <div class="form-group col-md-2 mb-0"> {{ form.Class|as_crispy_field }} </div> <div class="form-group col-md-2 mb-0"> {{ form.Booking_Type|as_crispy_field }} </div> <div class="form-group col-md-2 mb-0"> {{ form.Mode|as_crispy_field }} </div> <div class="form-group col-md-2 mb-0"> {{ form.Total_Period|as_crispy_field }} </div> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> {% endblock %} can you please help me i am getting same: error in raise CrispyError("|as_crispy_field got passed an invalid or inexistent field") crispy_forms.exceptions.CrispyError: |as_crispy_field got passed an invalid or inexistent field -
Django search form autocomplete
I have a code that queries multiple database tables. def search_view(request): models = [Item, Category, SubCategory] template_name = 'home-page.html' query = request.GET.get('q') print('query: {}'.format(len(query))) if len(query): item_items = models[0].objects.filter( Q(title__icontains = query) | Q(item_code__icontains = query) | Q(description__icontains = query) ) category_items = models[1].objects.filter( Q(title__icontains = query) ) subcategory_items = models[2].objects.filter( Q(title__icontains = query) ) return render(request, template_name, context={'item_items': item_items, 'category_items': category_items, 'subcategory_items': subcategory_items, 'query': query}) return redirect('/') But I want to make autocomplete when I type in the search box. I tried to do it through djando-autocomplete-light but couldn't implement it in my code. So, maybe someone can help with this. -
How to load Keras Model in Django rest API views
api_views.py from keras.models import load_model model = load_model('saved_finger_print_model.h5') And I got this error! OSError: Unable to open file (unable to open file: name = 'saved_finger_print_model.h5', errno = 2, error message = 'No such file or directory', flags = 0, o_flags = 0)