Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I'm trying to use a img with a block and a static method on django, but when i run it return an error
my name is Antonio, im from brazil, i'm trying to learn django, and now i want to put an img with a static method inside a block, like the code bellow, but when i run the code, it returns a error: 'Invalid block tag on line 26: 'static', expected 'endblock'. Did you forget to register or load this tag?', how can i fix it? Here is how i create the block: <figure class="foto-legenda"> {% block imagem %} <img src="{% static 'img/h40-principal.jpg' %}" > {% endblock %} </figure> And here is where i want to put the block: {% block imagem %} <img src="{% static 'img/Dia1.jpg' %}"> {% endblock %} -
In Django, how to include 3rd party apps only in local development?
I am using django-extensions for developing. But its not necessary for deployment (in Heroku). How to add it in INSTALLED_APPS so that its only included in dev stage, and not in deployment? NOTE: I use pipenv for virtualenv, I installed it in [dev-packages]. I tried to find a solution using environs["django"], but I couldn't find one -
Test cases failing for production database
I had written some testcases for my api endpoints which connects with elasticsearch data for querying. The testcases are not performing the same way for production database. How can I make my testcases such that it will not depend on elasticsearch database. Or how can my testcases work fine for production database too? -
Http Erorr 405 in Django
I build comments system in which the users can submit comments, When I try to submit the comment form I got error 405 I think my problem in the logic of the views my view class VideoDetailView(LoginRequiredMixin, View): def get(self, request, pk, *args, **kwargs): video = Video.objects.get(pk=pk) fav = bool if video.favourites.filter(pk=request.user.id).exists(): fav = True like = bool if video.likes.filter(id=request.user.id).exists(): like = True # the comments logic comments = Comment.objects.filter(video=video) user_comment = None comment_form = NewCommentForm(request.POST) if request.method == 'POST': if comment_form.is_valid(): user_comment = comment_form.save(commit=False) user_comment.author = request.user user_comment.video = video user_comment.save() return HttpResponseRedirect('/' + video.slug) else: comment_form = NewCommentForm() context = { 'comment_form': comment_form, 'video': video, 'fav': fav, 'like': like, 'comments': comments, 'user_comment': user_comment, } return render(request, 'video/the_video.html', context) -
'Workout' object has no attribute 'exercises'
I just started to play with Django trying to make an API REST, for some reason that i don't understand i'm getting this error 'Workout' object has no attribute 'exercises' when i do GET - /workouts. I'm using Django REST framework to make this thing. This is part of my code that I think you need to help me: serializers.py class WorkoutSerializer(serializers.ModelSerializer): exercises = serializers.StringRelatedField(many=True) class Meta: model = Workout fields = ['id', 'name', 'creation_date', 'exercises'] class ExerciseSerializer(serializers.ModelSerializer): class Meta: model = Exercise fields = ['url', 'video_url', 'workout'] models.py class Workout(models.Model): name = models.CharField(max_length=30) creation_date = models.DateField(auto_now_add=True) def __str__(self): return self.name class Exercise(models.Model): video_url = models.URLField(max_length=200) workout = models.ForeignKey(Workout, related_name='workout', on_delete=models.CASCADE) def __str__(self): return str(self.video_url) views.py class WorkoutViewSet(viewsets.ModelViewSet): queryset = Workout.objects.all() serializer_class = WorkoutSerializer class ExerciseViewSet(viewsets.ModelViewSet): """ API endpoint that allows exercises to be viewed or edited. """ queryset = Exercise.objects.all() serializer_class = ExerciseSerializer -
Optimise calculs with table fields and deal with possible None values
I have 3 differents tables : Price, Recipe and Item class Item(models.Model): def __str__(self): return self.name name = models.CharField(max_length=200, unique=True) image = models.URLField() class Recette(models.Model): item = models.OneToOneField(Item, on_delete=models.CASCADE) qte_ressource_1 = models.IntegerField(null=True) ressource_1 = models.ForeignKey(Item, on_delete=models.SET_NULL, blank=True, null=True, related_name='ressource_1') qte_ressource_2 = models.IntegerField(null=True) ressource_2 = models.ForeignKey(Item, on_delete=models.SET_NULL, blank=True, null=True, related_name='ressource_2') qte_ressource_3 = models.IntegerField(null=True) ressource_3 = models.ForeignKey(Item, on_delete=models.SET_NULL, blank=True, null=True, related_name='ressource_3') qte_ressource_4 = models.IntegerField(null=True) ressource_4 = models.ForeignKey(Item, on_delete=models.SET_NULL, blank=True, null=True, related_name='ressource_4') qte_ressource_5 = models.IntegerField(null=True) ressource_5 = models.ForeignKey(Item, on_delete=models.SET_NULL, blank=True, null=True, related_name='ressource_5') qte_ressource_6 = models.IntegerField(null=True) ressource_6 = models.ForeignKey(Item, on_delete=models.SET_NULL, blank=True, null=True, related_name='ressource_6') qte_ressource_7 = models.IntegerField(null=True) ressource_7 = models.ForeignKey(Item, on_delete=models.SET_NULL, blank=True, null=True, related_name='ressource_7') qte_ressource_8 = models.IntegerField(null=True) ressource_8 = models.ForeignKey(Item, on_delete=models.SET_NULL, blank=True, null=True, related_name='ressource_8') class Prix_x1(models.Model): def __str__(self): return self.item.name prix = models.IntegerField(null=True) saved_at = models.DateTimeField() item = models.ForeignKey(Item, on_delete=models.CASCADE) Each Item can have a Recipe and a recipe is composed of 1 to 8 items with a quantity associated to each ingredient. And all of the items have a price. Here is what i want : For all item that have a recipe, i want to calcul the total price of this recipe, that mean to get the price of all the ingredients. The problem is that i defined my recipe model to have … -
Django vs Nginx in serving Unity WebGL files with FacebookSDK
This is a follow-up to my previous question, which may have been too broad. To summarise, I am deploying WebGL static files from Unity, which uses FacebookSDK. I've tried using both Django and Nginx to serve the files, but I've only gotten Nginx to work without CORS/CORB errors. This is the relevant information: The error with Django The request/response bodies for Django The request/response bodies for Nginx Django settings DEBUG = True CORS_ORIGIN_ALLOW_ALL = True ALLOWED_HOSTS = [ "localhost", "0.0.0.0" ] # ... INSTALLED_APPS = [ 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Third-Party Apps 'rest_framework', 'rest_framework.authtoken', # Local Apps 'api.apps.ApiConfig', ] # ... MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] # ... STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, STATIC_URL) ] How i am running Django: gunicorn --certfile=localhost.crt --keyfile=localhost.key --bind 0.0.0.0:443 backend.wsgi As far as I understand, the CORS error arises because the Allow-Control-Origin-Resource header is not set on the response given by the server that I have made a request to (Facebook's servers). However, since both Nginx and Django are visited on https://localhost, I'm not sure why Nginx works but not Django. Appreciate any help I can get! -
How do I properly define the Entry Model for Django admin site?
from django.db import models class Topic(models.Model): """A topic the user is learning about.""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Return a string representation of the model.""" return self.text class Entry(models.Model): """Something specific learned about a topic.""" topic = models.ForeignKey(Topic, on_delete=models.CASCADE) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'entries' def __str__(self): """Return a string representation of the model.""" return self.text[:50] + "..." When I updated models.py, the makemigrations command returned a traceback. I also updated the admin.py file adding admin.site.register(Entry). The same traceback showed and I have been stuck on this problem. Please help to find a solution. -
How to pre populate charfield values, as a dropdown list from one model to another in django admin panel
Is it possible to pre populate charfield values, as a dropdown list from one model to another in admin panel? In other words having the below two models: class A(models.Model): name = models.CharField(max_length=50, null=True, blank=True) class B(models.Model): name = models.CharField(max_length=50, null=True, blank=True) If I have let's say ten instances stored of model A with name field having null = False , I want these values to show up as a dropdown list when I am trying to add a new instance of model B in admin panel at the name text field area. Is it possible? -
how to solve Heroku cllect static --noiput error
when I was deploying my web app on Heroku it gives me an error below is my log file I have created this app for learning purpose and now I want to deploy this Django app but I am facing some errors while deploying i followed tutorials on youtube but I am unable to solve this. -----> Building on the Heroku-20 stack -----> Python app detected ! Python has released a security update! Please consider upgrading to python-3.9.2 Learn More: https://devcenter.heroku.com/articles/python-runtimes -----> Installing python-3.9.1 -----> Installing pip 20.1.1, setuptools 47.1.1 and wheel 0.34.2 -----> Installing SQLite3 -----> Installing requirements with pip Collecting asgiref==3.3.1 Downloading asgiref-3.3.1-py3-none-any.whl (19 kB) Collecting certifi==2020.12.5 Downloading certifi-2020.12.5-py2.py3-none-any.whl (147 kB) Collecting chardet==4.0.0 Downloading chardet-4.0.0-py2.py3-none-any.whl (178 kB) Collecting Django==3.1.4 Downloading Django-3.1.4-py3-none-any.whl (7.8 MB) Collecting gunicorn==20.0.4 Downloading gunicorn-20.0.4-py2.py3-none-any.whl (77 kB) Collecting idna==2.10 Downloading idna-2.10-py2.py3-none-any.whl (58 kB) Collecting pycryptodome==3.9.9 Downloading pycryptodome-3.9.9-cp39-cp39-manylinux1_x86_64.whl (13.7 MB) Collecting pytz==2020.5 Downloading pytz-2020.5-py2.py3-none-any.whl (510 kB) Collecting razorpay==1.2.0 Downloading razorpay-1.2.0-py3-none-any.whl (162 kB) Collecting requests==2.25.1 Downloading requests-2.25.1-py2.py3-none-any.whl (61 kB) Collecting sqlparse==0.4.1 Downloading sqlparse-0.4.1-py3-none-any.whl (42 kB) Collecting urllib3==1.26.2 Downloading urllib3-1.26.2-py2.py3-none-any.whl (136 kB) Collecting whitenoise==5.2.0 Downloading whitenoise-5.2.0-py2.py3-none-any.whl (19 kB) Installing collected packages: asgiref, certifi, chardet, sqlparse, pytz, Django, gunicorn, idna, pycryptodome, urllib3, requests, razorpay, whitenoise Successfully installed Django-3.1.4 asgiref-3.3.1 certifi-2020.12.5 … -
How to get values of a django query from attributes of a many to many relation?
I have these two models: class Company(models.Model): name = models.CharField(max_length=100) class User(models.Model): ACCES_TYPE_CHOICES = ( ('ADMIN', 'Admin'), ('GUEST', 'Guest') ) company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='users') access_type = models.CharField(max_length=5, choices=ACCES_TYPE_CHOICES) I want a query that would return the values of the number of users with access_type == GUEST and the number of users with access_type == ADMIN for each company, like this: <QuerySet [{'id': 1, 'name': 'Company name', 'admin_users': 3, 'guest_users': 1}]> I tried some approaches with annotate but couldn't find a solution. Thanks for your help! -
Django how to display third level comments in a nested comment system
I'm building a nested Django comment system.The idea is very simple that all the sub comments that belongs to the same root comment will be nested under the root comment, no matter which level or layer the sub comments belong to. Root comment A reply to Root B reply to A C reply to B D reply to C E reply to A model.py: class Comment(models.Model): """ 评论表 """ nid = models.AutoField(primary_key=True) news = models.ForeignKey(verbose_name='评论文章', to='News',to_field='id',on_delete=models.CASCADE) user = models.ForeignKey(verbose_name='评论者', to='User',to_field='id',on_delete=models.CASCADE) content = models.CharField(verbose_name='评论内容', max_length=255) create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True) parent_comment = models.ForeignKey('self', null=True, on_delete=models.CASCADE) def __str__(self): return self.content view.py: def newsDetailView(request, news_pk): ......other code...... comments_list = Comment.objects.filter(news_id=news_pk).order_by('-nid') return render(request, "news/pages/index-inner.html", { 'comments_list': comments_list, }) template: {% for comment in comments_list %} {% if comment.comment_set.all %} {% if not comment.parent_comment %} <div class='root-sub-group'> <div class="root-comment" > {{comment.content}} </div> {% for reply in comment.comment_set.all %} <div class="sub-comment"> {{reply.content}} <div/> {% endfor %} </div> {% endif %} <!--now if the comments doesn't has both sub comments and parent comment then it should be a single root comment--> {% elif not comment.comment_set.all and not comment.parent_comment %} <div class="single-root" > {{comment.content}} </div> {% endif %} {% endfor %} My issue is it only display the comment … -
Djnago + Scrapy gives ValueError: signal only works in main thread
My model can only be changed from the admin panel. Some fields must be taken from websites. I have written to Spider who can do this. I run it with help CrawlerProcces.start(), rried running with CrawlerRunner + reactor. In both cases, I get ValueError: signal only works in main thread. My AdminModel method: def save_model(self, request, obj, form, change): celery_task(obj) super(ItemAdmin, self).save_model(request, obj, form, change) And Celery task method: @shared_task def celery_task(obj): crawler = CrawlerProcess(settings=get_project_settings()) crawler.crawl(<SpiderClass>, <some_args>) crawler.start() Without Celery I get this error too. -
405 on POST request despite csrf_token
I want to do a POST request with the second search bar of my website: {% extends "todo/base.html" %} {% block content %} <div class="recommendations"> <!-- <div class="login-page"> --> <div class="form"> <form action="{% url 'search_results' %}" method="get"> <input name="q" type="text" placeholder="Perfume name..."> <input id="perfumename" type ="submit" value="Find Similar Perfumes" autocomplete="nope"/> </form> <form class="login-form" action = "similar_results/" method="POST"> <input type="text" placeholder="perfume name"/> <!-- https://www.youtube.com/watch?v=TRODv6UTXpM&ab_channel=ProgrammingKnowledge --> {% csrf_token %} <input id="perfumename2" type ="submit" value="Find Similar Perfumes" autocomplete="nope"/> </form> </div> <script> $(document).ready(function() { $("#perfumename").autocomplete({ source: async function(request, response){ let data=await fetch(`http://localhost:8000/search_similar?q={request.term}`) .then(results => results.json()) .then(results => results.map(result => { return { label: result.name, value: result.name, id:result._id }; } response(data); }, minLength=2, select: function(event, ui){ console.log(ui.item); } }) }), $(document).ready(function() { $("#perfumename2").autocomplete({ source: async function(request, response){ let data=await fetch(`http://localhost:8000/search_similar?q={request.term}`) .then(results => results.json()) .then(results => results.map(result => { return { label: result.name, value: result.name, id:result._id }; } response(data); }, minLength=2, select: function(event, ui){ console.log(ui.item); } }) }) </script> </div> {% endblock %} But when I launch it it seems I have issues with csrf as I get a 405 triggered: Yet I included a {% csrf_token %}... -
Django model ordering within Meta does not to work
I am trying to build a Twitter-like social network where users are able to publish posts and they are able to see them in reverse chronological order (the latest posts first). I am building it using Django 3.1.7. I have defined my model as follows: class Post(models.Model): date_published = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.CASCADE) content = models.CharField(max_length=240, blank=False, default=None) user_like = models.ManyToManyField(User, blank=True, related_name='likes') def __str__(self): return f'{self.user.username} posted \"{self.content}\" on {self.date_published}' class Meta: ordering = ('-date_published',) And then I query my database from the views.py file as follows: @login_required def following(request): authors_followed = Follow.objects.filter( follower=request.user).values('author') posts = Post.objects.filter(user__in=authors_followed).annotate( likes=Count('user_like')) return render(request, "network/following.html", { 'posts': posts }) But the posts are not coming in the reversed order I expect. Surprisingly, if I do de query specifying .order_by('-date_published') it works as expected. Why the ordering attribute defined in the class Meta is not working? What is going on? I have done all my migrations and migrated the database. I am using sqlite if that is relevant. Thanks. -
How do I get image by object id? (Django)
I'm trying to get images for an object filtered by the object's id, but for now, I don't even see any request to it in my MySQL database. The snippets of my code are below. models.py: class Media(models.Model): word = models.ForeignKey(Word, on_delete=models.CASCADE) title = models.TextField(max_length=100, null=True) image = models.ImageField(upload_to='images/') views.py: class MediaListView(generic.ListView): model = Media template_name = 'dictionaty_web/index.html' context_object_name = 'images' def get_queryset(self): return Media.objects.filter(word=self.request.resolver_match.kwargs['pk']) index.html: {% for word in words %} <div class="col-sm text-center"> <div class="card" style="width: 18rem;"> <img scr="{{ MEDIA_URL }}{{ image.image.url }}"> <div class="card-body"> <h5 class="card-title">{{ word.value }}</h5> <a href="{% url 'dictionaty_web:detail' word.language.id word.word.id %}" class="stretched-link"></a> </div> </div> </div> {% endfor %} -
How to render wagtail orderable to homepage template?
I want to render them for my home templates. How can I solve the issue to get the output on templates? I created snippets and orderable and now can't get the output in my homepage. @register_snippet class Question(models.Model): text = models.CharField(max_length=255) slug = models.CharField(max_length=255) panels = [ FieldPanel('text'), FieldPanel('slug') ] def __str__(self): return self.text class Answer(Orderable, models.Model): page = ParentalKey(HomePage, on_delete=models.CASCADE, related_name="question_answer") question = models.ForeignKey(Question, null = True, blank = True, on_delete = models.CASCADE, related_name = '+') answer = models.CharField(max_length=300) url = models.URLField(max_length=200) panels = [ MultiFieldPanel([ SnippetChooserPanel('question'), ], heading="Questions"), MultiFieldPanel([ FieldPanel('answer'), FieldPanel('url'), ], heading="Answers & Urls") ] def __str__(self): return self.page.title + " -> " + self.question.text ``` -
correct approach to sum within a template in Django
I'm looping through an object in my template file so that I can access the value of votes associated with each choice of a specific question. I've looked into different ways of creating a variable that I can initiate at 0 and increment at every loop by the number of votes in said choice but when I try to use it to increment it breaks my code. Currently, the loops is outputting the value of choice.votes on the page but I want to find a way to get the total instead. I also tried #View that informs said template: class ResultsView(generic.DetailView): model = Question template_name = 'polls/results.html' class PollDelete(DeleteView): template_name = 'polls/delete.html' success_url = "/polls" def get_object(self): question = get_object_or_404(Question, pk=self.kwargs['pk']) return question #template : <form method="post">{% csrf_token %} <p>Are you sure you want to delete the poll "{{ get_object }}"?</p> {% with var1=0 %} {{ var1 }} {% for choice in question.choice_set.all %} {{ choice.votes }} {% endfor %} {% endwith %} <input type="submit" value="Confirm"> </form> -
django admin data does not register in database
I am building an ecommerce website with Django and having some difficulties to transfer data from the admin page to the database and then html. I am new to Django and I would love your help. I added 7 "products" (class Product) via Django admin page. models.py from django.db import models from django.contrib.auth.models import User class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=200) price = models.FloatField() def __str__(self): return self.name class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False) transaction_id = models.CharField(max_length=100, null=True) def __str__(self): return str(self.id) class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) class ShippingAddress(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) address = models.CharField(max_length=200, null=False) city = models.CharField(max_length=100, null=False) country = models.CharField(max_length=100, null=False) postcode = models.CharField(max_length=100, null=False) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.address views.py from django.shortcuts import render from .models import * def products(request): products = Product.objects.all() context = {'products':products} return render(request, 'store/products.html') def cart(request): context = {} return render(request, 'store/cart.html') def checkout(request): context = {} return render(request, 'store/checkout.html') … -
ValueError at /new Cannot assign "'Home'": "Listing.category" must be a "Category" instance
I'm trying to create a new listing but I get this error: (ValueError at /new Cannot assign "'Work'": "Listing.category" must be a "Category" instance.) Models.py class Category(models.Model): category = models.CharField(max_length=64) def __str__(self): return self.category class Listing(models.Model): title = models.CharField(max_length=64, default="") starting_bid = models.CharField(max_length=64, default="$") description = models.TextField(default="") image_url = models.CharField(max_length=200, default="") date = models.DateTimeField(default=timezone.now) category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.title views.py def new_listing(request): if request.method == "POST": title = request.POST["title"] starting_bid = request.POST["starting_bid"] image_url = request.POST["image_url"] category = request.POST["category"] description = request.POST["description"] ins = Listing(title=title, starting_bid=starting_bid, image_url=image_url, category=category, description=description) ins.save() categories = Category.objects.filter() return render(request, "auctions/new_listing.html", { "categories": categories }) -
Dango: How to get the sum with filters
I have a model: class SalesOrder(models.Model): area_coordinator = models.CharField(max_length=200, null=True, blank=True) order_number = models.IntegerField(null=True, blank=True) quantity = models.IntegerField(null=True, blank=True) I need to get the sum of the quantity based in area_coordinator. Thank in advance. -
Django login script constantly returning invalid request
Hi I hope someone can help. I'm new to Django and have been following tutorials to make a login script. I'm created a script that allows a user to login with a users table in postgres from a HTML form. The login script always returns "Invalid User" though the users credentials are not correct. I've followed many troubleshooting guides and I'm now at the end of my tether, it's really frustrating. Please see my code below for the different sections. Any help would be appreciated Account\Views.py def login_view(request, *args, **kwargs): context = {} user = request.user if user.is_authenticated: return redirect("home") destination = get_redirect_if_exists(request) print("destination: " + str(destination)) if request.POST: form = AccountAuthenticationForm(request.POST) if form.is_valid(): email = request.POST['email'] password = request.POST['password'] user = authenticate(email=email, password=password) if user: login(request, user) if destination: return redirect(destination) return redirect("home") else: form = AccountAuthenticationForm() context['login_form'] = form return render(request, "account/login.html", context) def get_redirect_if_exists(request): redirect = None if request.GET: if request.GET.get("next"): redirect = str(request.GET.get("next")) return redirect Account\forms.py class AccountAuthenticationForm(forms.ModelForm): password = forms.CharField(label='Password', widget=forms.PasswordInput) class Meta: model = Account fields = ('email', 'password') def clean(self): if self.is_valid(): email = self.cleaned_data['email'] password = self.cleaned_data['password'] if not authenticate(email=email, password=password): raise forms.ValidationError("Invalid login") urls.py from account.views import( register_view, login_view, logout_view, ) … -
Confirm_password validation error not working
I am relatively new to Django, so this may have a simple solution but I am very confused at this point. I tried to validate if my password and confirm-password are same but the error message does not appear even when I type different passwords in confirm_password and password. I guess the is_valid is returning False but I cannot figure out why. Any help would be appreciated. my forms.py from django import forms from django.contrib.auth import get_user_model USER = get_user_model() class SignUpForm(forms.Form): username = forms.CharField(max_length=150) email = forms.EmailField() password = forms.CharField(max_length=200, widget=forms.PasswordInput()) confirm_password = forms.CharField(max_length=200, widget=forms.PasswordInput()) def clean_username(self): if USER.objects.filter(username=self.cleaned_data['username']).exists(): raise forms.ValidationError("This username is taken") return self.cleaned_data['username'] def clean(self): try: password = self.cleaned_data['password'] confirm_password = self.cleaned_data['confirm_password'] if password != confirm_password: raise forms.ValidationError("You passwords do not match") except KeyError: pass my views.py from django.contrib.auth import authenticate, login from accounts.forms import SignInForm, SignUpForm from django.shortcuts import redirect, render from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required def signup_view(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): print(form.cleaned_data) user = User( username = form.cleaned_data['username'], email = form.cleaned_data['email'], password = form.cleaned_data['password'] ) user.save() user.set_password(form.cleaned_data['password']) user.save() return redirect('/accounts/signin/') else: print("Invalid") elif request.method == 'GET': form = SignUpForm() return render(request, 'accounts/signup.html', {'form': form}) my template … -
Django + Azure: How to implement a 301 redirect from naked to www domain
I am running Django app on Microsoft Azure and need to 301 redirect all traffic to a single secure www domain i.e. From: http://example.com https://example.com http://www.example.com To: https://www.example.com I assume I need to set up a redirect with a server configuration file but I'm new to Azure and not sure how to go about it. In addition, I have set up https only so http requests are currently directed to https. Thanks for your help! -
Django web-push "Reverse for 'save_webpush_info'"
I've installed django-webpush in my project and put {% webpush_header %} in the <head> part of my HTML template as instructed, however I am getting an error: NoReverseMatch at / Reverse for 'save_webpush_info' not found. 'save_webpush_info' is not a valid view function or pattern name. I use {% load webpush_notifications %} above that and have added webpush as part of the INSTALLED_APPS, along with the following in urls.py: url(r'^webpush/', include('webpush.urls')), https://github.com/safwanrahman/django-webpush