Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to fix "invalid keyword argument for this function" in ModelSerializer
I'm working on ModelSerializers their is a non-model field that is uploaded_files = serializers.FileField(required=True, source='files') in BlogSerializer. The uploaded_files does not belong to BlogModel. When is try to upload it gives me 'files' is an invalid keyword argument for this function i know files is not a field in BlogModel but i tried to add a property method files(self): in BlogModel which did not work either. models.py class BlogModel(models.Model): BLOG_STATUS = ( ('PUBLISH', 'Publish'), ('DRAFT', 'Draft'), ) blog_id = models.AutoField(primary_key=True) user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='blogs') title = models.CharField(max_length=255) content = models.TextField(blank=True, null=True) status = models.CharField(max_length=7, choices=BLOG_STATUS) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta(): db_table = 'blogs' verbose_name = 'Blog' verbose_name_plural = 'Blogs' def __str__(self): return self.title @property def files(self): #here is the property i added return 'do something' serializers.py class BlogFilesSerializer(ModelSerializer): created_at = serializers.SerializerMethodField() updated_at = serializers.SerializerMethodField() class Meta: model = BlogFilesModel fields = ('blog_files_id', 'blog', 'path', 'created_at', 'updated_at') extra_kwargs = { 'path': { 'error_messages': { 'blank': 'File is required' }, } } class BlogSerializer(ModelSerializer): blog_files = serializers.SerializerMethodField() uploaded_files = serializers.FileField(required=True, source='files') blog_created_at = serializers.SerializerMethodField(read_only=False) class Meta: model = BlogModel fields = ('blog_id', 'user', 'title', 'content', 'status','blog_files', 'blog_created_at', 'uploaded_files', ) Hope is have explained my problem well. Thank … -
Django Cart - multiple configuration options for a product
I want to create a Django web-application where users can add items to a cart. Without the models Colour and Size this works so far. My Problem is, that i can not figure out how to implement the configuration-options (for example) Colour and Size the right way. I added both "Options" with a Many-to-One relationship. I now can add multiple colours and sizes for a Product, but do not know how to save the choosen "Option" in an CartEntry This is what i got so far: from django.db import models from django.contrib.auth.models import User class Product(models.Model): name = models.CharField(max_length=256) price = models.DecimalField(max_digits=6, decimal_places=2) def __str__(self): return str(self.name) class Colour(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="rel_colour") option = models.CharField(max_length=24) price = models.DecimalField(max_digits=6, decimal_places=2) def __str__(self): return str(self.colcour) class Size(models.Model): product =models.ForeignKey(Product, on_delete=models.CASCADE, related_name="rel_size") option = models.CharField(max_length=24) price = models.DecimalField(max_digits=6, decimal_places=2) def __str__(self): return str(self.size) class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) products = models.ManyToManyField(Product, blank=True) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.id) + ' - ' + str(self.user) class CartEntry(models.Model): product = models.ForeignKey(Product, null=True, on_delete=models.CASCADE) cart = models.ForeignKey(Cart, null=True, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() def __str__(self): return str(self.quantity) + ', ' + str(self.product.name) -
How Can I implement custom authentication in django for user login
I want to implement custom login authentication in Django. I do not want to use Django's inbuilt authentication system because it is not working. I have a model named Doctor and I want to fetch the data from the Doctor model for login authentication. I have set my default database as MySQl database. I have tried some code but it didn't work for me. views.py def login(request): if request.POST: username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user is not None: login(request,user) return render(request,'welcome1.html') #success else: #Invalid login return render(request, 'login.html',{ 'error_message':'Invalid Credential' }) return render(request, 'login.html') models.py class Doctor(models.Model): initial_name = models.CharField(max_length=8) first_name = models.CharField(max_length=20, unique=True) last_name = models.CharField(max_length=20, unique=True) hospital_name = models.CharField(max_length=20) username = models.EmailField(max_length=50) password = models.CharField(max_length=50) address = models.CharField(max_length=1024) zip_code = models.CharField(max_length=12) dob = models.DateField(max_length=8) gender = models.CharField(max_length=10) phone_number = models.TextField(max_length=10) def __str__(self): return self.initial_name My expected output should be "when I will put wrong Email & password, it will show an error" But it is automatically redirecting to my home page, if i put wrong eail or password. -
Django: Search using SearchVector returns no results
I'm trying to get search results by searching multiple fields. If I use django.db.models.Q - it works fine. But if I use django.contrib.postgres.search.SearchVector I get wrong results. My requirements.txt file: django==2.2.0 psycopg2==2.8 Relevant parts of my models.py file: class Post(models.Model): title = models.CharField(max_length=250) body = models.TextField() My code: >>> from blog.models import Post >>> from django.db.models import Q >>> from django.contrib.postgres.search import SearchVector >>> Post.objects.filter(Q(title__icontains='is') | Q(body__icontains='is')).count() 10 >>> Post.objects.annotate(search=SearchVector('title','body')).filter(search='is').count() 0 I don't understand why am I getting no results with SearchVector. -
ValueError at /cart/add/3 "<Cart: None>" needs to have a value for field "id" before this many-to-many relationship can be used
I am trying to make acart component for my ecommerce site this error appears:ValueError at /cart/delete/2 "" needs to have a value for field "id" before this many-to-many relationship can be used. views.py from django.shortcuts import render, redirect, reverse from django.urls import reverse_lazy from .models import Cart from products.models import Product from django.shortcuts import get_object_or_404 def cart_home(request): cart_obj, new_obj=Cart.objects.new_or_get(request) return render(request, "carts/home.html", {"cart":cart_obj}) def addproduct(request, id): productobj= get_object_or_404(Product, id=id) shoppingcart=Cart() shoppingcart.products.add(productobj) shoppingcart.save() return redirect("carts:home") def removeproduct(request, id): productobj= get_object_or_404(Product, id=id) shoppingcart=Cart() shoppingcart.products.remove(productobj) shoppingcart.save() return redirect("carts:home") '''' models.py '''' from django.db import models from django.conf import settings from products.models import Product from django.db.models.signals import pre_save, post_save, m2m_changed User = settings.AUTH_USER_MODEL class CartManager(models.Manager): def new_or_get(self, request): cart_id = request.session.get("cart_id", None) qs = self.get_queryset().filter(id=cart_id) if qs.count() == 1: new_obj = False print('cart id exists') cart_obj = qs.first() if request.user.is_authenticated and cart_obj.user is None: cart_obj.user = request.user cart_obj.save() else: print("new cart created") new_obj = True cart_obj= Cart.objects.new(user=request.user) request.session['cart_id'] = cart_obj.id return cart_obj, new_obj def new(self, user=None): user_obj = None if user is not None: if user.is_authenticated: user_obj = user_obj return self.model.objects.create(user=user_obj) class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True, on_delete="Cascade") products = models.ManyToManyField(Product, blank=True, null=True) total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) updated = models.DateTimeField(auto_now=True) timestamp = … -
Django URl routing for email
Hi I am relatively new to Django, I am making a web based todo list. Upon following some online tutorials I was able to make the list. One of the tasks that im trying to achieve is the ability to send the list as an email with the status. I created a from in the form.py, created a sendMail view in views.py, linked these to the URL and added sendmail.html in the templates. But when I am clicking on the send mail anchor tag in index.html it redirects and says "Page Not Found". I am pretty confident that it has something to do with incorrect URL routing as the list works perfectly but the email functionality doesnt. I am also trying to figure out how to add the elements from the Todo list and send it using send_mail(). Here's the HTML file {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>ToDo App</title> <link href="https://fonts.googleapis.com/css?family=Oswald" rel="stylesheet"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="{% static 'todo/bs/css/flatly.min.css' %}" /> <link rel="stylesheet" href="{% static 'todo/styles.css' %}" /> </head> <body> <div class="container-fluid" id="wrapper"> <div class="row"> <div class="col-lg-4 col-lg-offset-4" id="content"> <h2> {{ mydate|date:"D, d M Y"}}</h2> … -
ArrayField doesn't get updated?
I'm trying to check if a lesson has been done (by checking if the page has been visited once on a logged account). I've been trying to check if the page has been visited. If not, the ID should be added in the array of visited pages. I'm checking all the possible situations (or at least the one I could think of) and when I have to, I add another lection.id to the array of accessed lessons. After priniting this array everytime, I saw that the lesson id gets added, but not in the database. (if I check the DB or if I change the page the lesson id disappears) views.py from django.shortcuts import render from django.shortcuts import get_object_or_404 from .models import Lectie def lectii(req): lectii = Lectie.objects.all().order_by("id") if req.user.is_authenticated: if req.user.profile.lectiiRezolvate == None: lectiiRezolvate=[] else: lectiiRezolvate = req.user.profile.lectiiRezolvate else: lectiiRezolvate=[] context = { 'lectii': lectii, 'lectiiRezolvate': lectiiRezolvate } print(lectiiRezolvate) return render(req, '../templates/pagini/lectii-selector.html', context) def lectie(req, lectie_id): if req.user.is_authenticated: if req.user.profile.lectiiRezolvate == None: req.user.profile.lectiiRezolvate.append(lectie_id) user.profile.save() print(req.user.profile.lectiiRezolvate) else: if lectie_id in req.user.profile.lectiiRezolvate: pass else: req.user.profile.lectiiRezolvate.append(lectie_id) print(req.user.profile.lectiiRezolvate) else: pass lectie2 = get_object_or_404(Lectie, pk=lectie_id) lectiePDF = 'lectii/lectia-{}.pdf'.format(lectie2) context = { 'lectiePDF': lectiePDF, 'lectie2': lectie2, } return render(req, '../templates/pagini/lectii.html', context) urls.py from django.urls import … -
How to built Django Referral System?
I am currently working on web application and want to add "Referral System". I found "Pinax-Referral". But not found any Example to understand. Can you please help me into these? -
Access to media files only for authenticated users
I have project in django 1.0.4 - yes I know it is old. I want to use the lack of access to media (audio) files for users who are not logged in. After making changes to nginx, logged in users also have no access. I tried with view and url function - no result my nginx settings: location /media/content/audio/ { deny all; } my function and url @login_required def protected_serve(request, path, document_root=None, show_indexes=False): if not request.user.is_authenticated: raise Http404() else: return serve(request, path, document_root, show_indexes) urlpatterns += patterns('', (r'^media/content/audio/(?P<path>.*)$', protected_serve), ) -
How should i show a HTML field in one template and another field in another template in django?
I have two templates one is base.html in which i am having a Report Issue button which i want to show to remaining templates. On clicking the Report Issue button Bootstrap modal is displayed. There i have a dropdown from which i will choice course for which i want to report an issue. I can get the courses in dropdown, but when i am on to some other template i don't want to display dropdown, instead the course name is automatically filled in the input below dropdown. My Question is how should i hide dropdown in another template and display input tag inplace of it? Is this possible in django? {% if not user.profile.is_moderator and user.is_authenticated %} <button type="button" class="feedback-button" data-toggle="modal" data-target="#myModal"><i class="fa fa-question-circle" aria-hidden="true"></i> Report Issue</button> {% endif %} <!-- Modal --> <div id="myModal" class="modal fade" role="dialog"> <div class="modal-dialog"> <!-- Modal content --> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Leave us a message</h4> <button type="button" class="close" data-dismiss="modal">×</button> </div> <div class="modal-body"> <form role="form" method="POST" action=""> {% csrf_token %} <p>Send your message in the form below and we will get back to you as early as possible.</p> <div class="form-group"> <label for="user_name">User:</label> <input type="text" name="user_name" class="form-control" id="user_name" value="{{user.username}}" disabled> <label for="user_email">Email:</label> <input type="text" … -
POST QueryDict not formed correctly with data from multiple forms
I have multiple forms with the same fields: a hidden id input (some forms may not have it), a name field, an email field and a select field. I am performing a request: $.post(url, data, successFunction) and this is how I build data: const data = []; let i = 0; $('.myforms').each(function () { data['entry-' + i++] = $(this).serializeArray(); }); This is how data looks like: { "entry-0": [ { "name": "id", "value": "3" }, { "name": "name", "value": "name1" }, { "name": "email", "value": "" } ], "entry-1": [ { "name": "id", "value": "4" }, { "name": "name", "value": "name2" }, { "name": "email", "value": "" } ], "entry-2": [ { "name": "id", "value": "7" }, { "name": "name", "value": "name3" }, { "name": "email", "value": "name3@email.com" }, { "name": "options", "value": "1" } ], "entry-3": [ { "name": "name", "value": "new" }, { "name": "email", "value": "" }, { "name": "options", "value": "1" }, { "name": "options", "value": "2" } ] } But the QueryDict is not being formed correctly, it's not interpreting the data as I expect: Out[10]: <QueryDict: {u'entry-2': [u'[object Object]', u'[object Object]', u'[object Object]', u'[object Object]'], u'entry-3': [u'[object Object]', u'[object Object]', u'[object Object]', u'[object Object]'], … -
Change the way Django discovers translations
Django discover translation based on order of Installed app and override translation of same phrases in different apps based on translation file which appear sooner of others. This scenario is described here So, is there any way to change this scenario to something else, like using specific translation for same phrases in different apps from translation which provided by app which in use? -
How to pass audio Blob to Django Backend and Server?
I am building a Django WebApp that records multiple speakers, manipulates the files and pushes the result to an IBM Speech Processing tool. I've been stuck at the recording part for two days and would appreciate some help. My goal is to be able to store .wav files in my database, that I can manipulate and send to the IBM tool. In JS, this is how I found how to record the audio. function handlerFunction(stream) { rec = new MediaRecorder(stream); rec.ondataavailable = e => { audioChunks.push(e.data); if (rec.state == "inactive"){ let blob = new Blob(audioChunks,{type:'audio/wav'}); recordedAudio.src = URL.createObjectURL(blob); recordedAudio.controls=true; recordedAudio.autoplay=true; sendData(blob) } } } function sendData(data) { $('.passAudio').val(data); } I can replay it in the audio tag and I'm attempting to pass it as a hidden input. So far, it's telling me it passes an Blob object, but I don't know what to do with that. <audio id=recordedAudio></audio> <input type="hidden" accept="audio/*" id="0" name="audio" class="passAudio"> I'm trying to get it to somehow store in my default storage, but I have no idea if this is even in the correct direction. I'm also unsure how to check if it's been correctly saved. # views.py if request.method == 'POST': blob = request.POST.getlist('audio') path … -
Django authenticate() returns none except one case
So i am stuck at a point in my project. I am trying to create users and I have extended User model using the OneToOnefield method as recommended in Documentation to create a user profile. There is no problem in creation of the user as all the details are correctly stored in both the auth_user and appname_userprofile table. The problem I get is when I try to login with any user stored in the auth_user table. Except one case( which i created before creating the userProfile model). So in my auth_user Table the pass for this one case is encoded but for the remaining cases it's plain text. Here is my function handling the view - def login_view(request): if request.method == 'POST': print(request.body) username = request.POST.get('id_username') password = request.POST.get('id_password') print(username, password) try: import pdb; pdb.set_trace() user = authenticate(username=username, password=password) print('This is ',user) if user is not None: login(request,user) else: return redirect('fileupload') print('This is ',user).... some more code Now when i pass the credentials for this one case and try to authenticate. the login works(except my code gets stuck at some later point because this user doesn't have any profile). When i pass the credentials for user created after creating the … -
I am not able to understand code for index function as well as add_to_cart function in views.py file while designing an ecomm website
This is all the code that I want to understand deeply that what's going on underneath the hood. This code lies in views.py file and I am designing an ecommerce website in django using python 2.7 version. I have Cart, Product and Item Model on models.py file. Also my project name is ShoppingCart and app name is shopping. from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login required from django.contrib.auth.models import User from django.shortcuts import render, redirect from django.views.generic import View from shopping.models import Cart, Product, Item import string import random # Create your views here. def index(request): user = request.user items = '' if user.is_anonymous(): user = '' else: items = Item.ojects.filter(cart__user=user, cart__checked_out=False) items = items.count() if items else 0 products = Product.objects.filter(total_items__get=0) return render(request, 'index.html', {'products':products, 'user':user, 'items':items, 'page':'home'}) def add_to_cart(request): user = request.user if user.is_anonymous(): chars = string.ascii_uppercase + string.digits user_name = ''.join(random.choice(chars) for _ in range(9)) password = '1234567a' user = User.objects.create(username=user_name, first_name='guest', last_name='guest', email='guest@gmail.com', is_active=True is_staff=True) user.set_password(password) user.save() user = authenticate(username=user_name, password=password) if user: login(request.user) product_id = request.GET.get('product_id') cart = Cart.objects.filter(checked_out=False, user=user) cart = cart[0] if cart else '' if not cart: cart = Cart.objects.create(user=user) Item.objects.create(cart=cart, product_id=product_id, quantity=1) return redirect('index') -
Using exclude on annotated FilteredRelation doesn't work?
It looks like using exclude on queryset with annotated FilteredRelation give a FieldError on the annotation name. For exemple, in Django tests (django/tests/filtered_relation/tests.py) if we change this : def test_with_join(self): self.assertSequenceEqual( Author.objects.annotate( book_alice=FilteredRelation('book', condition=Q(book__title__iexact='poem by alice')), ).filter(book_alice__isnull=False), [self.author1] ) to this def test_with_join(self): self.assertSequenceEqual( Author.objects.annotate( book_alice=FilteredRelation('book', condition=Q(book__title__iexact='poem by alice')), ).exclude(book_alice__isnull=False), [] ) We get the error Traceback (most recent call last): File "/usr/lib/python3.6/unittest/case.py", line 59, in testPartExecutor yield File "/usr/lib/python3.6/unittest/case.py", line 605, in run testMethod() File "/home/lucas/dev/test/django/tests/filtered_relation/tests.py", line 99, in test_with_join_exclude ).filter(~Q(book_alice__isnull=False)), File "/home/lucas/dev/overmind/venvs/release/lib/python3.6/site-packages/django/db/models/query.py", line 844, in filter return self._filter_or_exclude(False, *args, **kwargs) File "/home/lucas/dev/overmind/venvs/release/lib/python3.6/site-packages/django/db/models/query.py", line 862, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "/home/lucas/dev/overmind/venvs/release/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1263, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/home/lucas/dev/overmind/venvs/release/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1281, in _add_q current_negated, allow_joins, split_subq) File "/home/lucas/dev/overmind/venvs/release/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1287, in _add_q split_subq=split_subq, File "/home/lucas/dev/overmind/venvs/release/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1204, in build_filter return self.split_exclude(filter_expr, can_reuse, e.names_with_path) File "/home/lucas/dev/overmind/venvs/release/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1604, in split_exclude query.add_filter(filter_expr) File "/home/lucas/dev/overmind/venvs/release/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1249, in add_filter self.add_q(Q(**{filter_clause[0]: filter_clause[1]})) File "/home/lucas/dev/overmind/venvs/release/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1263, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/home/lucas/dev/overmind/venvs/release/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1287, in _add_q split_subq=split_subq, File "/home/lucas/dev/overmind/venvs/release/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1164, in build_filter lookups, parts, reffed_expression = self.solve_lookup_type(arg) File "/home/lucas/dev/overmind/venvs/release/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1028, in solve_lookup_type _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta()) File "/home/lucas/dev/overmind/venvs/release/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1389, in names_to_path … -
Django doesn't show selected choices in a Multiselect
Django multiselect doesn't return/render the selected choices that are saved in the database form.py class testform(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) temp = User.objects.values_list('username', flat=True).filter(groups__name = "Artist") OPTIONS1 = zip(temp, temp) self.fields['column'].choices = [OPTIONS for OPTIONS in OPTIONS1] column = forms.MultipleChoiceField(required = True, choices= []) Selecting the options goes fine like views.py def index(request): if request.method == "POST": form = testform(request.POST) if form.is_valid(): form.save() return redirect('index') else: form = testform() return render(request, 'dummy/index.html', { 'edit_form' : form}) Data is being saved as once selected ['artist1', 'artist2', 'artist3'] But when revisiting the same page, it doesn't show the selected choices of that instance, instead the select multiple box has no selection of the above 3 choices A little help is strongly appreciated, Thanks in advance -
django if condition not working when using variable, but when using number it's working
why this code not working, i get variable "data" from views.py when i change data.numrooms with number like '1', it's working well, but is use data.numrooms that's not working <select class="form-control" name="numadults"> <option value=''>No. of Adult</option> {% for i in range %} {% if data.numadults == i %} <option value="{{ i }}" selected>{{ i }}</option> {% else %} <option value="{{ i }}">{{ i }}</option> {% endif %} {% endfor %} </select> -
Object of type User is not JSON serializable
I am creating a an auto complete search for my web page and where I am trying to fetch name of users from database using ajax calls. My AJAX call is running fine and going to designated URL. I have tried using JSON encoder but that also did not work. I am a bit new to DJANGO.Please help My views.py def autocomplete(request): if request.is_ajax(): q = request.GET.get('search', '').capitalize() search_qs = Profile.objects.filter(user__username__startswith=q) results = [] print (q) for r in search_qs: results.append(r.user) data= json.dumps(list(results), cls=DjangoJSONEncoder) else: data = 'fail' mimetype = 'application/json' return HttpResponse(data, mimetype) My models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' Error I am getting TypeError: Object of type User is not JSON serializable [] "GET /ajax_calls/search/?**term=he** HTTP/1.1" 500 15860 -
ValueError: ModelForm has no model class specified
I am new to Django and trying to create a web page with two submit buttons one for login and one for registration. After adding model classes for a database this error occurred. (pre model code commented with sign #). Cannot find any answers online or in Django documentation for this issue. authentication.html <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom-mb-4">Login User</legend> {{Lform|crispy}} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit" name="login">Login</button> </div> </form> </div> </div> <div class="col-md-6"> <div class="content-selection"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom-mb-4">Register User</legend> {{Rform|crispy}} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit" name="register">Register</button> </div> </form> Below is views.py views.py from django.shortcuts import render, redirect from django.contrib import messages from .forms import login, register def home(request): return render(request,"authentication/home.html",{}) def authentication(request): if request.method=='POST': Lform=login(request.POST) Rform=register(request.POST) if Lform.is_valid(): email = Lform.cleaned_data.get('Email') password = Lform.cleaned_data.get('Password') messages.success(request,email+' loged in') return redirect('home') elif Rform.is_valid(): name=Rform.cleaned_data.get('name') email = Rform.cleaned_data.get('email') password = hash(Rform.cleaned_data.get('password')) confirm_password = hash(Rform.cleaned_data.get('confirm_password')) if password == confirm_password: messages.success(request,name+' registered') return redirect('home') else: messages.error(request,'password dont match') return redirect('authentication') else: print('page') Lform=login() Rform=register() return render(request,"authentication/authentication.html", {'Lform':Lform,'Rform':Rform}) forms.py from django import forms from .models import Authentication class login(forms.Form): Email = forms.EmailField(widget=forms.TextInput(attrs={'placeholder':'Email'}))###Capital E in email for login Password = forms.CharField(widget=forms.PasswordInput())###Capital P in Password … -
Create a django url with ajax results
I am using AJAX to refresh a table in my template by using dataTable. When I get the results from the AJAX call (json) I'm using 'columns' to set every row. In one of the rows, I want to create a Django URL to another view. What I have tried so far doesn't seem to work function refreshData(event_ref) { var table = $('#datatable').dataTable({ 'processing': true, 'serverSide': false, 'responsive': true, 'destroy': true, 'ajax': { 'type': "GET", 'url': "{% url 'events:index' %}", 'dataSrc': "" }, 'columns': [ { "data": "pk", render: function (pk) { return '<input type="checkbox" id="check_' + pk + '" name="check_all">'} }, { "data": "fields.date_time" }, { "data": "pk", render: function (pk) { return "<a href='{% url 'events:event' " + pk + "%}'>Click me</a>" }} ], 'order': [[ 2, "desc" ]], 'columnDefs': [ { 'targets': [0, 8], // column index (start from 0) 'orderable': false, // set orderable false for selected columns }], 'scroller': { loadingIndicator: true } }); } The problem is in the line { "data": "pk", render: function (pk) { return "<a href='{% url 'events:event' " + pk + "%}'>Click me</a>" }} and what I get is this, Reverse for 'event' with arguments '(' + pk + … -
How to fix NoReverseMatch error in Django [duplicate]
This question already has an answer here: What is a NoReverseMatch error, and how do I fix it? 3 answers I'm making a web app to manage students. When creating/ updating students a "NoReverseMatch" error is thrown. I'm new to django but I cannot figure out why it's throwing the error when the exact same pattern name is present in the urls files. The delete redirect does not work either. urls.py: path('Student/', views.StudentListView.as_view(), name='Students'), path('Student/<int:pk>', views.StudentDetailView.as_view(), name='Student-detail'), path('Student/create/', views.StudentCreate.as_view(), name='Student_create'), path('Student/<int:pk>/update/', views.StudentUpdate.as_view(), name='Student_update'), path('Student/<int:pk>/delete/', views.StudentDelete.as_view(), name='Student_delete'), views.py: class StudentDetailView(generic.DetailView): model = Student class StudentListView(generic.ListView): model = Student template_name = 'main/student_list.html' class StudentCreate(CreateView): model = Student fields = '__all__' class StudentUpdate(UpdateView): model = Student fields = ['student_name'] class StudentDelete(DeleteView): model = Student success_url = reverse_lazy('Students') student_form.html: {%block content%} <body> Add new student: <form action="" method="post"> {% csrf_token %} <table> {{ form.as_table }} </table> <input type="submit" value="Submit"> </form> </body> {%endblock%} Instead of redirecting back to the student detail page I get the following error: NoReverseMatch at /Student/1/update/ Reverse for 'Student-detail' not found. 'Student-detail' is not a valid view function or pattern name. Thank you. -
form.as_hidden doesn't pass values to POST
My form has initial values in it. I use form.as_hidden to hide the values and pass those values through a POST request. However, the hidden values are not passing through. Is there a way through this? views.py def car_detail_view(request, id): if request.method == "POST": form = CarForm(request.POST) print(form.is_valid()) if form.is_valid(): car_save = form.instance get_car = Car.objects.get(number_plate=car_save.number_plate) get_car.available = False get_car.save() return redirect('/') else: print(form.errors) else: car = Car.objects.get(id=id) form = CarForm(initial={'brand':car.brand, 'number_plate':car.number_plate, 'price':car.price, 'available':car.available}) args = { 'car':car, 'form':form } return render(request, 'map/confirmation.html', args) confirmation.html <h1>Confirmation of Booking</h1> {% block content %} <p>Brand: {{ car.brand }}</p> <p>Number Plate: {{ car.number_plate }}</p> <p>Price: {{ car.price }}</p> <p> Are you sure you want to book? <p> <form class="" method="post"> {% csrf_token %} {{ form.as_hidden }} <input type="submit" value="Book {{ car.brand }}"> </form> {% endblock %} -
Django: implementing websockets to work with my existing MVT-based app (Channels seems to need me to throw out my entire existing code)
I have an existing Django project in the sports domain with apps that are built on the Model-View-Template structure. Many of the models and views are fairly sophisticated and work well currently. Data from the database (scores etc) is combined with some incoming user inputs through forms (HTTP POST requests) to be displayed on a web page via templates. However, I now need live data to be displayed to users and be automatically refreshed to all the users continuously, either because one of the users entered something new (in the front-end), or because the scores changed during the game (directly enters the back-end). I've done some research on Stack Overflow as well as tutorials on Youtube/ rest of the web and it appears that for me to use Django Channels, I'd have to start from scratch and build everything ground-up, which I'd like to avoid. How do I use the websocket protocol for my Django app easily without having to completely rework everything that I've done so far? -
Messages for users with (user.is_active =False) flag during the login process
I am trying to add message during the log-in process , to a user when he has an account, but deactivated, that he should activate it if he wants to get it. I use LoginView controller, that uses built-in standard form called AuthenticationForm AuthenticationForm has a following method: def confirm_login_allowed(self, user): """ Controls whether the given User may log in. This is a policy setting, independent of end-user authentication. This default behavior is to allow login by active users, and reject login by inactive users. If the given user cannot log in, this method should raise a ``forms.ValidationError``. If the given user may log in, this method should return None. """ if not user.is_active: raise forms.ValidationError( self.error_messages['inactive'], code='inactive', # and list of error messages within this class error_messages = { 'invalid_login': _( "Please enter a correct %(username)s and password. Note that both " "fields may be case-sensitive." ), 'inactive': _("This account is inactive."), } So that technically if not user.is_active – it should show message 'inactive' but in my case for inactivated users with is_active = False DB table it shows the message 'invalid_login' instead. I am trying 100% correct login and password and user is not active but it …