Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Authenticate username and password in my own login form in django
i have a class 'user' in my models.py...user has several attributes like userid,username,password,etc. this is a part of my login page login.html <form action="" method="post" enctype="multipart/form-data"> <h1>Login Form</h1> <div> <label><b>Username</b></label> <input type="text" id="username" placeholder="Enter username" required=""> </div> <div class="password"> <label id="labelp"><b>Password</b></label> <input type="text" required="" placeholder="Enter password" id="password"> </div> <div class="submitb"> <input type="submit" value="Log In"> </div> </div> i want to retrieve this username and password from here and want to authenticate it against the values i have in my user table(username and password) and then login the user. how do i do that? -
Issue with Django dbbackup and restore command
I have 2 Databases in my app : DATABASES = { MAIL_ACCOUNTS_DB_CONFIG: { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'rango', 'USER': 'rangoadmin', 'PASSWORD': 'rango@2017', 'HOST': 'localhost', # Or an IP Address that your DB is hosted on 'PORT': '3306', 'OPTIONS': {'charset': 'utf8mb4'}, }, DEFAULT_DB_CONFIG: { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'rango', 'USER': 'rangoadmin', 'PASSWORD': 'rango@2017', 'HOST': 'localhost', 'PORT': '5432', 'CONN_MAX_AGE': 0, } } In setting.py, DBBACKUP_STORAGE = 'django.core.files.storage.FileSystemStorage' DBBACKUP_STORAGE_OPTIONS = {'location': '/home/shan/project_bkp'} DBBACKUP_GPG_RECIPIENT = 'XXXXXXXXXXXXXXX' When I run python manage.py dbbackup --encrypt --compress I can only see default-shan-desktop-2017-09-12-213553.psql.gz.gpg . Where is the backup of mysql DB` ? Question: How to know which database backup has been made ? When I fire python manage.py dbbackup --encrypt --compress --database MAIL_ACCOUNTS_DB_CONFIG I get `django.db.utils.ConnectionDoesNotExist: The connection MAIL_ACCOUNTS_DB_CONFIG doesn't exist How to backup each DB seperately ? How to restore it ? When restoring using python manage.py dbrestore --decrypt I get : CommandError: Because this project contains more than one database, you must specify the --database option. When I run : python manage.py dbrestore --decrypt --database MAIL_ACCOUNTS_DB_CONFIG I get: CommandError: Database MAIL_ACCOUNTS_DB_CONFIG does not exist. -
How to validate django-summernote
As I install django-summernote by pip install django-summernote I used it by adding it in forms.py class faq_Form(forms.ModelForm): faq_answer = forms.CharField(widget=SummernoteWidget(attrs={'height': '300px','placeholder':'Enter Answer Here',}),required=True) class Meta(): model = faq fields = ['faq_answer'] widgets = { #'body': SummernoteInplaceWidget(), 'faq_answer': SummernoteWidget(), } And in html file i include it inside form by below: {{ form | safe }} Now i want to get text from this summernote in javascript from validation.....I am unable to do that. So please provide some solution. -
Django - Database querying - Checking if a list of values is a subset of another list
I'm programming a website aimed at teaching a language. The idea is that by validating lessons, the students are unlocking other contents (exercices, songs...). Formally, at each lesson are attached tags. Whenever a student validates a lesson, he validates the associated tags. Each content is flagged with prerequisites corresponding to those tags. On a page, I want to display all the songs a user can get access to based on the tags he unlocked. If he unlocked all the tags associated to the song, he can view it otherwise he can't. Here is the model of a lesson (called cours) : class Cours(models.Model): niveau=models.ForeignKey(Niveau,on_delete=models.CASCADE) titre=models.CharField(max_length=255, unique=True) tags=models.ManyToManyField(Tag) Here is the model of a song : class Chanson(models.Model): titre=models.CharField(max_length=255, unique=True) prerequis=models.ManyToManyField(Tag,blank=True,related_name="+") Here is the model of the profile of a user and the solution I found out to answer my problem using Python built-in sets. class Profil(models.Model): user=models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) cours_valides=models.ManyToManyField(Cours) chanson_valides=models.ManyToManyField(Chanson) def songs_to_do(self): songlist=Chanson.objects.exclude(id__in=self.chanson_valides.values_list('id',flat=True)) outputsonglist=list() for song in songlist: if set(song.prerequis.values_list('id',flat=True))<=set(self.cours_valides.values_list('tags',flat=True)): outputsonglist.append(song) return outputsonglist The songs to do method basically returns the list of songs the user has not covered yet but can access based on the lessons he validated so far. Indeed, the cours valides field lists all the … -
Django POST - unable to retrieve form data, POST check fails
I'm very new to Django. I am trying to desing my login module and trying to print the values i submit. login.html (please excuse indentation mistakes) {% load staticfiles %} <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Login Form</title> <link rel="stylesheet" href="{% static 'css/lstyle.css' %}"> </head> <body> {% block content %} {% if form.errors %} <script> alert("Your username and password didn't match. Please try again."); </script> {% endif %} {% if next %} {% if user.is_authenticated %} <script> alert("Your account doesn't have access to this page. To proceed,please login with an account that has access."); </script> {% else %} <script> alert('Please login'); </script> {% endif %} {% endif %} <div class="login"> <div class="login-screen"> <div class="app-title"> <h1>Login</h1> </div> <div class="login-form"> <form method="POST" action="{% url 'login' %}"> {% csrf_token %} <p class="bs-component"> <table> <tr> <td>{{ form.username }}</td> </tr> <tr> <td>{{ form.password }}</td> </tr> <tr> <td>{{ form.schoolID }}</td> </tr> </table> </p> <p class="bs-component"> <center> <input class="btn btn-success btn-sm" type="submit" value="login" /> </center> </p> <input type="hidden" name="next" value="{{ next }}" /> </form> </div> </div> </div> </body> {% endblock %} </html> Forms.py from django.contrib.auth.forms import AuthenticationForm from django import forms # If you don't do this you cannot use Bootstrap CSS class LoginForm(AuthenticationForm): username = forms.CharField(max_length=30, … -
raw_id_fields with pages field does not work
There are several issues if we add "pages" field to raw_id_fields. When I click on search button, pages dialog opens, and if I select any page, nothing happens (I think that context variable "is_popup" from render_page_row method in cms/utils/admin.py should additionally check if IS_POPUP_VAR is present in request.META['HTTP_REFERER']) If problem 1. is fixed, click on page adds page id but also all parent ids all the way to the tree root (I think that propagation of onclick event should be stopped) It is not possible to open child nodes without selecting parent. When parent node arrow is clicked in order to see and add child node, parent is selected and dialog is closed. Result of adding onclick event handler on cms-tree-node. Is it possible to add onclick event only for page link and not on the whole element with class cms-tree-node, so we can open node children without selecting page? -
Django wizard handles datetimes what serializer does it use?
I was using django wizard (in django formtools) with the session backend, and changed to using seperate views due to having a more complex signup. However using the standard session JSONSerialzer fails to store eg datetimes as JSON doesn't support this. However this is possible in django wizard. What Serializer does it use? -
confused about why django el(endless) pagination not working when "with" template tag is used to render filtered objects
i have the following template for user profile view.where i want to show the post uploaded by the respective profile user using django el(endless) pagination. but the ajax call is not working when i include the page_template inside the "with"tag. class Post(models.Model): title = models.CharField(max_length=250) slug =models.SlugField(max_length=250,unique=True,default=None) created = models.DateField(auto_now_add = True) author = models.ForeignKey(User, related_name='uploaded_by') published = models.BooleanField(default=True) ajax not working <div id="entries" class="endless_page_template"> {% with post=user.uploaded_by.all %} {% include page_template %} {% endwith %} </div> @login_required def user_detail(request,username, template='accounts/user/detail.html', page_template='usersubmit/post_ajax.html'): context = { 'user' :get_object_or_404(User, username=username, is_active=True), 'page_template': page_template, } if request.is_ajax(): template = page_template return render(request, template, context) But when i remove the "with" template tag it just works fine. code as follows: <div id="entries" class="endless_page_template"> {% include page_template %} </div> #views,py @login_required def user_detail(request,username, template='accounts/user/detail.html', page_template='usersubmit/post_ajax.html'): context = { 'user' :get_object_or_404(User, username=username, is_active=True), 'post':Post.objects.all(), 'page_template': page_template, } if request.is_ajax(): template = page_template return render(request, templ is there any way to query the post related to a particular user for viewing on their profile page.Can anyone suggest me?I am new to django -
Django FloatField with amount of decimals as stored in database
Consider the following example model: class Product(models.Model): weight = FloatField(db_index=True, null=True, blank=True) The FloatField will be a field of type double in MySQL. Now I want to be able to use a variable amount of decimals for this field. So when I save a Product with weight 50, it must be stored as 50 in the database. When the weight is 50.0, it must be stored as 50.0. This seems default behaviour, so the weights are stored in the database like how they were originally saved. However, when retrieving a product from the database, an original weight of 50 is converted to 50.0, so a decimal is added. That is probably because of the fact that the retrieved value will be converted to a float in Django, which automatically adds the decimal. To overcome that problem, I tried to extend the from_db_value method of the FloatField, hoping the be able to fetch the original value (50 instead of 50.0). But at that point the value is already converted to 50.0: class Product(models.Model): weight = DynamicDecimalFloatField(db_index=True, null=True, blank=True) class DynamicDecimalFloatField(models.FloatField): def from_db_value(self, value, expression, connection, context): print(value) # prints 50.0 return value What would be the best way to access the … -
Django channels - only send on newly created
I am trying to only send group messages on newluy created models. This does not seem to work. HOw should one do this? class ImageValueBinding(WebsocketBinding): model = Image stream = "intval" fields = ["device", "image", "detect", "detect_type", "confidence", "description", "timestamp"] @classmethod def group_names(cls, instance): if instance.pk == None: client = VirtualClient.objects.get(unique_identifier=instance.device.unique_identifier) groups = [] for group in client.group_set.all(): groups.append("push-%s" % group.slug) return groups -
getting error while relating a foreign key to save form in django
models.py class OtherData(models.Model): title = models.CharField(max_length=120) user = models.ForeignKey(settings.AUTH_USER_MODEL) class ProductImage(models.Model): otherdata = models.ForeignKey(OtherData) user = models.ForeignKey(settings.AUTH_USER_MODEL) image = models.FileField(blank=True, null=True, upload_to='images/') I am looking for saving an image on an instance of otherdata, getting integrity error 'NOT NULL constraint failed'. I am using a model form to save data. I tried to use form valid method as follows in views.py but still the same error. def form_valid(self, form): instance = form.save(commit=False) instance.user = self.request.user instance.otherdata_id = self.kwargs.get('pk') return super(ImageCreateView, self).form_valid(form) Looking forward for a help, thank you. -
Getting JWT from OAuth2 redirect_url
I have a Django REST app with JWT auth. Login happens by frontend getting a token from backend, that's it. It then sends token in headers for every request. Now I'm trying to implement a connect to Linkedin functionality through OAuth2. Frontend gets from backend a LinkedIn link to redirect to. User lets us use their data on LinkedIn page. Linkedin redirects user to backend url (set up in Linkedin app settings) so that backend could collect token from query params. Backend redirects back to frontend. Problem is, there is no JWT in headers on stage 3, i.e there is no auth, no current user, no session. -
Unable to delete record in DB when using DestroyAPIView
I'm trying to write a Django Rest Framework based backend for learning purpose. I've created a simple school model, which has only name and description field (Please note that primary key is auto populated). App's models.py data is as below, from django.db import models class School(models.Model): name = models.CharField(max_length=255) description = models.TextField() class Meta: ordering = ('id',) def __str__(self): return self.name App's views.py data is as below, from .models import School from .serializers import SchoolSerializer from rest_framework import status from rest_framework import generics from rest_framework.decorators import permission_classes from rest_framework.permissions import IsAdminUser from rest_framework.response import Response class SchoolList(generics.ListCreateAPIView): queryset = School.objects.all() serializer_class = SchoolSerializer permission_classes(IsAdminUser,) def list(self, request, *args, **kwargs): queryset = self.get_queryset() serializer = SchoolSerializer(queryset, many=True) return Response(serializer.data) @permission_classes((IsAdminUser, )) def post(self, request, format=None): user = request.user serializer = SchoolSerializer(data=request.data, context={'user':user}) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class SchoolDetail(generics.RetrieveAPIView): queryset = School.objects.all() serializer_class = SchoolSerializer class SchoolDelete(generics.DestroyAPIView): queryset = School.objects.all() serializer_class = SchoolSerializer def delete(self, request, *args, **kwargs): return self.destroy(request, *args, **kwargs) App's urls.py data is as below, from django.conf.urls import url from rest_framework.urlpatterns import format_suffix_patterns from . import views urlpatterns = ( url(r'^schools/$', views.SchoolList.as_view()), url(r'^schools/(?P<pk>[0-9]+)/$', views.SchoolDetail.as_view()), url(r'^schools/delete/(?P<pk>[0-9]+)/$', views.SchoolDelete.as_view()), ) urlpatterns = format_suffix_patterns(urlpatterns) I'm trying to delete … -
django join to model with same User
i want to connect the post model with the userprofile so the i can jointly represent post and corresponding to it the related user image must be displayed. please tell me how to generate the query enter code here view instance = postmodel.objects.order_by('-updated') model user profile image: class userprofile(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) profileimage = models.ImageField(upload_to="userprofile/") model that contain post detail: class postmodel(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(User,default=None) body=models.TextField() slug = models.SlugField(unique=True) subject=models.TextField() timestamp = models.DateTimeField(auto_now_add=True,auto_now=False) updated = models.DateTimeField(auto_now=True,auto_now_add=False) -
Django - UnicodeEncodeError at / 'ascii' codec can't encode characters in position 22-29
I write this code and it worked perfectly with Python 2.7 in Linux terminal. But in Django 1.11.4 I receive following error. # -*- coding: utf-8 -*- import urllib url = 'http://test.com?title=%D8%AE%D8%B1%DB%8C%D8%AF%20%D9%85%D9%86%D8%B2%D9%84&shopping_list=%D9%BE%DB%8C%D8%A7%D8%B2%20%D9%88%20%D8%B3%DB%8C%D8%A8%20%D8%B2%D9%85%DB%8C%D9%86%DB%8C&recurring=not_recurring&description=%D8%A7%D8%B2%20%D8%B9%D8%A8%D8%A7%D8%B3%20%D8%A2%D9%82%D8%A7%20%D8%A8%D8%AE%D8%B1' url = urllib.unquote(url).decode('utf8') Django error: UnicodeEncodeError at / 'ascii' codec can't encode characters in position 22-29: ordinal not in range(128) Please guide to fix the problem. Thank you. -
Display a graph of a certain variable as a function of time
I am working in a Django project. That project consists of offering different products related to bank loans to our customers. We want to get different statistics for our application. An example could simply be the number of new loans each week / month / year. What would be the best plugin offered by Django or Python to plot graphics? with possibilities to insert in the app? This could be the number of loans depending on the time (days, weeks or years). -
Accessing model attributes in the template in django
this is a snippet of the views.py of my django app.i have used modelform to create a form. the models.py has a class user which has an attibute username. i want to redirect the registration page to a view 'redirect' but also i want to pass the name of the user which is obtained after we hit the submit button on the form and the data gets stored in the instance 'new_form'. def registration(request): if request.method=='POST': form=userForm(request.POST) if form.is_valid(): name=form.cleaned_data['username'] new_form=form.save() return HttpResponseRedirect(reverse('redirect')) else: form=userForm() return render(request,'student/registration.html',{'form':form}) my redirect.html looks something like this. <h1>You have signed up.</h1> <p>hello {{field.name}}</p> but the problem is that name is not being displayed after hello which is obvious because i haven't passed anything with reverse('redirect'). So how do i do that? And is there any problem with my redirect.html also? -
onclick js function after django relative url
I have the following links in my template: <li><a id="toggleHome" href= "{% url 'index' %}" class="active" onclick="toggleHome();" ><span>Home</span></a></li> <li><a id="toggleLogin" href= "{% url 'login_app:user_login' %}" onclick="toggleLogin();" ><span>Login</span></a></li> <!-- login app --> the onclick works for the first link but not the second one. The difference being the relative url of the application 'login_app'. The urls are both working fine though. Any suggestion? -
dynamically specifying variable name in a function
I am making a custom django template tag. The rudimentary version: import models @register.filter def intensity1(value): return models.CHOICES_FOO[value] It just returns the value'th element of model.FOO list But I actually have a few different lists, models.CHOICES_BAR, models.CHOICES_BAZ So I thought to make a more generalized function, pass it the value and an arg which specifies which variable list to refer to. @register.filter def intensity2(value, arg): return models.arg[value] arg = "INTENSITY_CHOICES" print (intensity2(value, arg)) But of course this doesn't work. Failing with module 'models' has no attribute 'arg' Is there a way to state something like that? or would I be better off keeping all these choices in a dict and then retrieve them by referring to the key? -
django haystack: how to iterate over all indexed elements
I am trying to iterate over a Search Queryset with haystack, but it throws me this error: Result window is too large, from + size must be less than or equal to: [10000] but was [11010]. See the scroll api for a more efficient way to request large data sets. This limit can be set by changing the [index.max_result_window] index level parameter. Is there a way to iterate over all indexed elements? (let's say I have several million records). -
Django can't send mail
I've made a contact form in django. In the first template it's sending the email without any problem. In the second one, the one i'm trying to use, it won't send anything, it's not redirecting, not giving me any errors. The settings I've made for it are good since in the first template i can send. If i try to send it like this, it will send the email. views.py def contact_test(request): """ Contact form """ data = dict() if request.method == "POST": form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] email = form.cleaned_data['email'] message = form.cleaned_data['message'] try: send_mail(subject, message, email, ['test1234@yahoo.com']) except BadHeaderError: return HttpResponse('Invalid header found.') except ConnectionRefusedError: return HttpResponse('Sorry, no connection available.') return HttpResponse('Thank you for your message') else: form = ContactForm() data['form'] = form return render(request, 'frontend/contact_test.html', data) contact_test.html (first template) {% if form.errors %} <p style="color:red;"> Please correct the error{{ form.errors|pluralize }} below. </p> {% endif %} <form action="" method="POST"> <table> {{ form.as_table }} </table> {% csrf_token %} <input type="submit" value="Submit"> </form> But, if I'm trying to send it in the template i want to use, it's not going to send. views.py def contact(request): """ Contact form """ data = dict() if request.method == "POST": … -
Set user attribute after project creation
In my app A User can create a project by giving it a name. That is my model : class Project(models.Model): name = models.CharField(max_length=250) team_id = models.ForeignKey(Team, blank=True, null=True) project_hr_admin = models.ForeignKey(MyUser, blank=True, null=True) def get_absolute_url(self): return reverse('website:ProjectDetails', kwargs = {'pk' : self.pk}) def __str__(self): return self.name that is my views: class ProjectCreate(CreateView): model = Project fields = ['name'] template_name = 'project_form.html' How can I set when a user create a project project_hr_admin = models.ForeignKey(MyUser, blank=True, null=True) with his ID and save it in the DB ?? Thx you -
Regarding displaying titles on blog sites using django and bootstrap
Currently, I am building blog site by using django and bootstrap. In this work, the HTML of the bootstrap theme that I plan to use is a slightly complicated structure, so I am in trouble because I can not display the blog title by the loop in HTML. Regarding solution to this problem, title data stored in an array is retrieved one by one, and embedding tags or variables in HTML, I thought that I could display the title of each article. however, I do not know how to realize it. I think the following code the minimum elements that make up the display of titles in django. What elements should be added besides the below? base.html <body> <div id="content"> {% block content %} {% endblock %} </div> </body> list.html {% block content %} {% for post in posts %} <p>{{ post.title }}</p> {% endfor %} {% endblock %} view.py class PostListView(ListView): queryset = Post.published.all() context_object_name = 'posts' paginate_by = 10 template_name = 't_env/post/list.html' model.py class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) After removing {% for post in posts%} in list.html, I tried that add filters, arguments, etc. for {{post.title}} would work, but it … -
Django - Custom save method in model
(Using Django 1.11.5) Traditionally, I've always created a model like so: class Animal(models.Model): is_hungry = models.BooleanField(default=True) Then make changes like so: animal = Animal() animal.save() animal.is_hungry = True animal.save() Recently, I saw a friend define a model with a custom save method: class Animal(models.Model): is_hungry = models.BooleanField(default=True) def feed_animal(self): self.is_hungry = False self.save() And calling this method appears to work as expected: >>> from testapp.models import Animal >>> a = Animal() >>> a.save() >>> a.is_hungry True >>> >>> a.feed_animal() >>> a.is_hungry False Are there any benefits/drawbacks in defining such a custom save method in the model definition? Is there any reason to prefer calling .save() on the object directly? -
create_product() missing 1 required positional argument: 'category_id'
I m trying to use related object but i keep getting this error create_product() missing 1 required positional argument: 'category_id' I have been trying to figure out how to fix the error Here is my views def create_product(request, category_id): form = ProductForm(request.POST or None, request.FILES or None) category = get_object_or_404(Category, pk=category_id) if form.is_valid(): category_product = category.song_set.all() for s in category_product: if s.name == form.cleaned_data.get("song_title"): context = { 'category': category, 'form': form, 'error_message': 'You already added that song', } return render(request, 'shop/product/product_create.html', context) product = form.save(commit=False) product.category = category product.save() return render(request, 'music/detail.html', {'category': category}) context = { 'category': category, 'form': form, } return render(request, 'shop/product/product_create.html', context) I m trying to use related object but i keep getting this error create_product() missing 1 required positional argument: 'category_id' I have been trying to figure out how to fix the error Here is my views class Category(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='category_created') name = models.CharField(max_length=500, db_index=True) slug = models.CharField(max_length=500, blank=True) images = models.ImageField(upload_to='users/%Y/%m/%d', blank=True) def __str__(self): return self.name def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.name) super(Category, self).save(*args, **kwargs) class Product(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='product') category = models.ForeignKey(Category, related_name='products') name = models.CharField(max_length=500, db_index=True) slug = models.CharField(max_length=500, blank=True) images = models.ImageField(upload_to='users/%Y/%m/%d', blank=True) description …