Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django REST User Creation/Authentication
This question is based on the one here. I am setting up a Django REST Framework for my web app and am trying to set up User accounts. Based on the REST documentation, they put all of their account code in their example in the main project directory and a separate application so did that as well. Here is what I have: urls.py from django.contrib import admin from django.urls import include, path from django.conf.urls import url from rest_framework import routers from . import views router = routers.DefaultRouter() router.register('users', views.UserViewSet) urlpatterns = [ path('admin/', admin.site.urls), url('', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), ] serializers.py from django.contrib.auth.models import User from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) def create(self, validated_data): user = User.objects.create( username=validated_data['username'] ) user.set_password(validated_data['password']) user.save() return user class Meta: model = User # Tuple of serialized model fields (see link [2]) fields = ( "id", "username", "password", ) views.py from rest_framework import viewsets, permissions from rest_framework.generics import CreateAPIView from django.contrib.auth.models import User from .serializers import UserSerializer # Create your views here. class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = [permissions.IsAuthenticated] class CreateUserView(CreateAPIView): model = User permission_classes = [ permissions.AllowAny ] serializer_class = UserSerializer I have tried using the Boomerang … -
Django Serializer showing "character": "Dictionary object (256)" as opposed to the actual character
I am using Django rest framework and I am trying to do a JOIN on a GET command. I have the following view: class CharacterView(APIView): permission_classes = (AllowAny,) def get(self, request, user_id): character_saves = Char.objects.select_related('character').filter( user_id=user_id) serializer = CharacterSerializer(character_saves, many=True) return Response({"characters": serializer.data}) And the following serializer: class CharacterSerializer(serializers.Serializer): character_id = serializers.IntegerField() user_id = serializers.IntegerField() active = serializers.BooleanField() character = serializers.CharField() def create(self, validated_data): return Char.objects.update_or_create( user_id=validated_data.pop('user_id'), character_id=validated_data.pop('character_id'), defaults=validated_data ) Yet, I am getting the following data: "characters": [ { "character_id": 256, "user_id": 1, "active": true, "character": "Dictionary object (256)" }, { "character_id": 260, "user_id": 1, "active": true, "character": "Dictionary object (260)" } ] Instead of giving me the actual item I want, it gives me a dictionary object. This is almost correct, however I am guessing I am configuring something wrong in my query or serializer, preventing me from getting the raw value. How do I get the actual value here, rather than "Dictionary object (260)"? -
Django: Manipulate Form Input
I want to be able to multiply the user's input by 2 (if the user inputs 4 on a form, save 8). I haven't been able to figure out how I might go about doing this. Any ideas? -
Django - updating a user's profile removes session
I'm successfully updating the user's profile, but for some reason it is removing the session somehow. I'm using the same form used during the initial user creation - just filling in the fields via initial. Is it some built-in Django magic that is messing with my session? Here is what the request looks like: [09/May/2020 22:40:38] "POST /user/settings HTTP/1.1" 200 9564 [09/May/2020 22:40:41] "GET /users/12/ HTTP/1.1" 302 0 views.py # @login_required(login_url='/login/') def settings(request): user = request.user if request.method == 'POST': POST = request.POST.copy() POST['user_type'] = user.user_type form = CreateUserForm(POST, instance=request.user) if form.is_valid(): user = form.save(commit=False) user.entity_type = request.user.entity_type print("Saving user.") user.save() user.session = request.session # return redirect('dashboard', pk=request.user.id) else: print(form.errors) else: email = user.email zipcode = user.zipcode user_type = user.user_type if user.entity_type == 'individual': first_name = user.first_name last_name = user.last_name form = CreateUserForm(instance=request.user, initial={ 'first_name': first_name, 'last_name': last_name, 'email': email, 'zipcode': zipcode, 'user_type': user_type }) elif user.entity_type == 'business': business_name = user.business_name print(user_type) form = CreateUserForm(instance=request.user, initial={ 'business_name': business_name, 'email': email, 'zipcode': zipcode, 'user_type': user_type }) context = {'form':form} return render(request, 'user/settings.html', context) forms.py class CreateUserForm(UserCreationForm): first_name = forms.CharField(max_length=100, help_text='First Name', required=False) last_name = forms.CharField(max_length=100, help_text='Last Name', required=False) business_name = forms.CharField(max_length=100, help_text='Business Name', required=False) email = forms.EmailField(max_length=150, help_text='Email') zipcode = … -
How can i add multiple models and custom fields to a json response in Django Rest Framework
i'm new into Python/Django programming and i got stuck with something in a personal project that i'm doing. My issue is that i want to return a custom response based on different models of my application, some of the values will come from custom queries and others are part of the models itself. So, i have the following models in my app(some fields were deleted to not make the post too long): class Parking(models.Model): google_id = models.CharField(max_length=100) short_name = models.CharField(max_length=100) long_name = models.CharField(max_length=300) price = models.DecimalField(max_digits=4, decimal_places=2, null=True, blank=True) class ParkingLot(models.Model): parking = models.ForeignKey(Parking, on_delete=models.CASCADE, null=False, related_name='parkinglots') size = models.ForeignKey(Size, on_delete=models.DO_NOTHING, null=False, related_name='size') width = models.DecimalField(max_digits=3, decimal_places=2, null=True, blank=True) height = models.DecimalField(max_digits=3, decimal_places=2, null=True, blank=True) class ParkingAvailability(models.Model): parkinglot = models.ForeignKey(ParkingLot, on_delete=models.CASCADE, null=False, related_name='availability') available = models.BooleanField(null=False, blank=False) from_hour = models.TimeField(auto_now=False, auto_now_add=False, default='09:00:00') to_hour = models.TimeField(auto_now=False, auto_now_add=False, default='21:00:00') These models are an exact representation of my database tables. All good. My problem is that now i want to make a custom json response, this needs to run queries over these tables but not show the entire objects and in some cases, custom fields based on filter or operations that i need to run over the tables (for example, numbers of parkinglots … -
Pass args and kwargs into reverse Django
I think this is a very easy question, so bare with me. I have a link that is set up as follows: page/<key> where key is a randomly generated key, that is setup here: reverse('page', args=(key,)) However, I want to also pass data into the page/<key> endpoint. However, if I add another variable into args here: reverse('page', args=(key, more_data)) then it gets messed up as it tries to open a url at: page/<key>/<more_data> Furthermore, django doesn't allow args and kwargs in one reverse call. How would I pass data in then? Thanks! -
Django custom URL missing 1 required positional argument
I have the following view (empty for test) : from .forms import Form_Step_1 def register(request, step): print(step) In my urls.py I have : urlpatterns = [ path('login/', views.LoginView.as_view(), name='login'), path('logout/', views.LogoutView.as_view(), name='logout'), path('register', register, name='register'), path('register/', register, name='register'), path('register?step=<int:step>/', register, name='register'), ] The register and register/ works well. But if I go to register?step=1 I have the following error : register() missing 1 required positional argument: 'step' Thanks for your help -
How to add an additional class to a table from context in Django
I have 2 functions one for MarketingMessage and another for Slider. I have already a function for MarketingMessage and I want to add the Slider because the below function is not working correctly I want to combine them together as they are from the same model This is the original function that I want to add to it def get_context_data(self, **kwargs): context = super(HomeView, self).get_context_data(**kwargs) try: context['marketing_message'] = MarketingMessage.objects.filter( active=True).latest('timestamp') except MarketingMessage.DoesNotExist: context['marketing_message'] = None return context this is the function that I want to get rid of and include it to the above one def get_context_data(self, **kwargs): context = super(HomeView, self).get_context_data(**kwargs) try: context['sliders'] = Sliders.objects.filter( active=True).latest('timestamp') except Sliders.DoesNotExist: context['sliders'] = None return context This is the model class MarketingMessage(models.Model): title = models.CharField(max_length=60) message = models.TextField( max_length=120) active = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) def __str__(self): return self.title class Slider(models.Model): title = models.CharField(max_length=60) image = models.ImageField(blank=False, upload_to='Marketing') header_text = models.CharField(max_length=120, null=True, blank=True) middle_text = models.CharField(max_length=120, null=True, blank=True) footer_text = models.CharField(max_length=120, null=True, blank=True) button_text = models.CharField(max_length=120, null=True, blank=True) active = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) def __str__(self): return self.title Thank you all -
502 Bad Gateway - Dockerized Django Gunicorn NGINX on AWS EBS
So I am trying to deploy over two days and I can't seem to to manage to get fix this error. I am getting a 502 bad gateway error. I am trying to deploy a two-container app to elastic beanstalk. The two containers are: Nginx reverse proxy container Django app with gunicorn I SSHed to my EC-2 instance and fetched the nginx logs 2020/05/09 21:48:25 [error] 6#6: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 84.119.15.244, server: , request: "GET / HTTP/1.1", upstream: "http://172.17.0.2:8000/", host: "http://xxx-xxx-xxx.us-east-1.elasticbeanstalk.com/" 84.119.15.244 - - [09/May/2020:21:48:25 +0000] "GET / HTTP/1.1" 502 560 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36" "-" 2020/05/09 21:48:25 [error] 6#6: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 84.119.15.244, server: , request: "GET /favicon.ico HTTP/1.1", upstream: "http://172.17.0.2:8000/favicon.ico", host: "http://xxx-xxx-xxx.us-east-1.elasticbeanstalk.com/", referrer: "http://xxx-xxx-xxx.us-east-1.elasticbeanstalk.com/" It seems like the upstream refused to connect. I also took the gunicorn logs and it looks like server started successfully [2020-05-09 21:48:07 +0000] [1] [INFO] Starting gunicorn 19.9.0 [2020-05-09 21:48:07 +0000] [1] [INFO] Listening at: http://127.0.0.1:8000 (1) [2020-05-09 21:48:07 +0000] [1] [INFO] Using worker: sync [2020-05-09 21:48:07 +0000] [9] [INFO] Booting worker with pid: 9 here is my nginx default.conf … -
jQuery: Saving a form with jQuery turns the form invalid
I'd like to save a form containing an image. Without jQuery the form saves as intended, however, adding below "js-product_image-create-form" function creates an invalid form, but, at the same time, json respond status is: <JsonResponse status_code=200, "application/json"> The form is invalid in the View (prints "invalid" below) and in "invalid" in jQuery. However, removing the class="js-product_image-create-form", visually I get json with a valid form = True as well as the function prints "valid" Why is the form valid in one case but invalid in the other case? Using Django View: def save_product_image_form(request, form, template_name): data = dict() if request.method == 'POST': if form.is_valid(): form.save() data['form_is_valid'] = True print("valid") product_image = ProductImage.objects.all() data['html_product_image_list'] = render_to_string('product_image/includes/partial_product_image_list.html', { 'product_image': product_image }) else: data['form_is_valid'] = False print("invalid") context = {'form': form} data['html_form'] = render_to_string( template_name, context, request=request) return JsonResponse(data) def product_image_create(request): if request.method == 'POST': form = ProductImageForm(request.POST, request.FILES) else: form = ProductImageForm() return save_product_image_form(request, form, 'product_image/includes/partial_product_image_create.html') $(function() { var saveForm = function() { var form = $(this); $.ajax({ url: form.attr("action"), data: form.serialize(), type: form.attr("method"), dataType: 'json', success: function(data) { if (data.form_is_valid) { alert("I am valid"); $("#product_image-table tbody").html(data.html_product_image_list); $("#modal-product_image").modal("hide"); } else { alert("I am invalid !"); $("#modal-product_image .modal-content").html(data.html_form); } } }); return false; }; … -
JWT validation in class based view django
I've implemented jwt authentication in django using Django-graphql-jwt library, now I want to allow get/post on my endpoint (/graphql) only for requests with JWT token. There are examples in django-graphql-jwt documentation like @login_required, but I don't want to put a decorator above every query and mutation. So, I've decided to restrict an access to a view. I added path('graphql/', PrivateGraphQLView.as_view()) in url.py but how can I implement request checking for a valid token in the header? from graphene_django.views import GraphQLView class PrivateGraphQLView(GraphQLView): pass -
Adding Semantic UI React value of Form.Select into variable I post into my Django API
I'm new to React and I try to understand how I can add Form.Select value into my variables that I post into my Django API. When I only use Form.Input it works ok but when I add a Form.Select value doesn't passed into the userform. I saw that using event.target.elements.inputname.value is not possible for Form.Select, but after a lot of hours trying to make this works ... it looks like I'm unable to do it. errors shown is : Uncaught TypeError: Cannot read property 'value' of undefined Your help would be much appreciated. Thanks a lot !!! Here is my code : import React from 'react' import { Button, Form } from 'semantic-ui-react' //import axios from 'axios' const options = [ { key: 'm', text: 'Male', value: 'male' }, { key: 'f', text: 'Female', value: 'female' }, ] class MyClass extends React.Component{ handleFormSubmit = (event) => { event.preventDefault() const aa = event.target.elements.aa.value const bb = event.target.elements.bb.value const cc = event.target.elements.cc.value //axios.post('http://127.0.0.1:8000/api/blabla', { // aa: aa, // bb: bb, // cc: cc, //}) // .then(res => console.log(res)) // .catch(err => console.log(err)) console.log(aa, bb, cc) } render() { return( <div> <Form onSubmit={this.handleFormSubmit}> <Form.Input name="aa" placeholder='...' /> <Form.Input name="bb" placeholder='...' /> <Form.Select name="cc" … -
foreign key and relate name
i made a comment form and i want to attach every comment with the relate body i want to make Blogpost appear in html template enter image description here models: class Comment(models.Model): blogpost = models.ForeignKey( BlogPost, on_delete=models.CASCADE, related_name='img') name = models.CharField(max_length=256) email = models.EmailField() body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) views: class CommentView(View): def get(self, *args, **kwargs): form = CommentForm() blogpost = BlogPost.objects.all() comment = Comment.objects.all() return render(self.request, 'blog/comment.html', {'form': form, 'blogpost': blogpost, 'comment': comment}) template: {% csrf_token %} <label for="name">name</label> {{ form.name }} <label for="body">body</label> {{ form.body }} <label for="email">email</label> {{ form.email }} {{ form.blogpost }} <button class="btn btn-primary" type="submit">Submit</button> {% for thing in blogpost %} {{ thing }} {% endfor %} </form> what should i do ? -
Upgrading Django 1.11 to 3.X/Python2.7 to 3.7
I have a fairly old website running Django 1.11 and Python 2.7. I am not sure why it doesn't seem to be updating. I upgraded Python3.5 to Python3.7 just now. Deleted the old virtualenv (by deleting app/bin and creating a new virtualenv with virtualenv --python=/usr/bin/python3 . ) When in the virtualenv, if I do a python -V I get Python 3.7.7. If I run django-admin --version I see 3.0.6. But when I try to run the server, my Traceback says: File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) So it's still pointing at apparently an old global install? How can I point it to the new version in the virtualenv I've created? -
Beginner Looking for Advice on How to Progress with Current Project
To combat a personal convenience issue and learn more about APIs, I made a python program that prompts a user for a YouTube playlist and transfers the songs from that playlist into a new or existing Spotify playlist (destination also prompted). I finally was able to get all the functionality working, but now I'd like to continue building the project, but I'm not really sure what to do next. Some things I'm interested in learning are building my own REST API and front and backend development, and wanted to incorporate that in this project by making a website where a user could log into their Youtube and Spotify accounts and complete the transfers in a more aesthetically pleasing interface as opposed to just running a python file. If anyone has advice on what would be best for a beginner to build next, and what technologies would be most relevant for front/back end, it would be greatly appreciated. Thanks! -
Creating a function to open a new folder each time an image is uploaded
I want to create a function where everytime a user uploads an image a new folder is created with their username (designer_name) and associate each title to each uploaded Image is that possible? If it is what is the best way to do it? The model class Post(models.Model): designer_name = models.ForeignKey(User, on_delete=models.CASCADE) design = models.ImageField( blank=False, null=True, upload_to='new designs') title = models.CharField(max_length=100) date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return self.title def get_absolute_url(self): return reverse("score:post-detail", kwargs={"pk": self.pk}) -
How to use annotated (alias) field on the left of values as part of group by (i.e. values) clause in django using ORM?
Having challenge to get a summarized result by using django ORM utilizing an annotated field then apply values with that alias into the values (group by) and followed by other annotations to complete the aggregated field Sample data: >>> >>> models.Sale.objects.values().first() {'id': 93, 'sales_order': 'SON4000006', 'transaction_date': '2020-05-04 00:00:00', 'customer_name': 'Customer No2', 'delivery_note': 'DN200006', 'vehicle_number': 'T101AAA', 'tax_invoice': 'TI900006', 'product_name': 'Pro Cememnt', 'quantity': '100', 'total_value': '50000', 'quantity2': None, 'total_value2': None, 'destination': 'Zambia', 'agent_id': None, 'created_at': datetime.datetime(2020, 5, 9, 6, 48, 26, 59719, tzinfo=<UTC>), 'updated_at': datetime.datetime(2020, 5, 9, 6, 48, 26, 59719, tzinfo=<UTC>)} >>> >>> >>> models.Document.objects.values().first() {'id': 27, 'ref_number': '2019 MATARE75/251', 'description': None, 'doc_type': 'Exit', 'file': 'docs/SKM_Sales20042214362_Msp5YxV.pdf', 'sale_id': 85, 'created_at': datetime.datetime(2020, 4, 25, 16, 11, 24, 847574, tzinfo=<UTC>), 'updated_at': datetime.datetime(2020, 4, 25, 16, 11, 24, 847574, tzinfo=<UTC>)} >>> >>> >>> >>> >>> qs1=models.Sale.objects.annotate(docs_count=Count('docs'), complete=Case(When(docs_count=3, then=True), default=False, output_field=BooleanField())).values('destination', 'complete').annotate(count=Count('id'), qty=Sum('quantity'), value=Sum('total_value')).order_by('destination','complete') >>> >>> >>> >>> print(qs1.query) SELECT "sales_sale"."destination", CASE WHEN COUNT("sales_document"."id") = 3 THEN True ELSE False END AS "complete", COUNT("sales_sale"."id") AS "count", SUM("sales_sale"."quantity") AS "qty", SUM("sales_sale"."total_value") AS "value" FROM "sales_sale" LEFT OUTER JOIN "sales_document" ON ("sales_sale"."id" = "sales_document"."sale_id") GROUP BY "sales_sale"."destination" ORDER BY "sales_sale"."destination" ASC, "complete" ASC Expected output is: SELECT "sales_sale"."destination", CASE WHEN COUNT("sales_document"."id") = 3 THEN True ELSE False END … -
Django Blog - Comment function shows dropdown menu for authors in form
I created a Django Blog and want to add a comment section. So far I created the Comment-models and it is possible to make comments. But for every user it shows a dropdown menu where they can chose the user which will displayed with the comment-posting, which should not be. I tried to modifiy the Comments model and take out the 'author' in forms.py, but nothing works. Does anyone have an idea what I could do here? I assume it must have something to do with the author, I also tried 'author = models.ForeignKey(User, on_delete = models.CASCADE)' but same result. This is how my code looks like: # in forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('text',) #fields = ('author', 'text',) # in models.py class Comment(models.Model): post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE ) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) approved_comment = models.BooleanField(default=False) def approve(self): self.approved_comment = True self.save() def __str__(self): return self.text #here a part from views.py class UserPostListView(ListView): model = Post template_name = 'blog/user_posts.html' #<app>/<model>_<viewtype>.html context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') class PostDetailView(DetailView): model = Post def add_comment_to_post(request, pk): post = … -
Django - How to post all those checkbox ID's which are unchecked as well to views
I have a table ( 7X4 ). First column of a table is checkbox. With the below code, I can get all the checked items in the UI to views, but I wanted to get unchecked ID's as well. Below is my templates file: <table id="tableForm" name="table-data" class="table table-striped table-bordered zero-configuration"> <thead> <tr> <th>Select</th> <th>Week Day</th> <th>Timing</th> <th>Action</th> </tr> </thead> <tbody> {% for row in days_data %} <tr> <td id="{{row.id}}"><input value="{{row.set_name}}" name="checks" type="checkbox"></td> <td> {{row.day}} </td> <td>{{row.set_name}}</td> <td> </tbody> </table> views.py file def weekDays_set(request): if request.method == 'POST': year = request.POST.get('form_year') batch = request.POST.get('form_batch') days = request.POST.getlist('table-data') days1 = request.POST.getlist('checks') print(days1) # I am getting only checked rows ID's I can get only checked row ID's in dictionary, Can someone help me on getting unchecked rows data as well please ? -
How to write this Django HTML template more efficiently?
I have a Django app where users can create their lists and add to-dos. I want to add a new page which will show to-dos that had due dates. Like, in the page, there will be a section called "Earlier" which was feature tasks with missed due dates. Other sections would be "Today", "Tomorrow" and "Later on". Let me show my view class and HTML code now and explain my problem. Class based view to handle this page: class ToDoNextUpView(LoginRequiredMixin, ListView): model = ToDo template_name = "ToDo/next_up.html" ordering = ["-due_date"] context_object_name = "todos" def get_queryset(self): query_set = [] for todo in ToDo.objects.filter(creator=self.request.user, is_checked=False): if todo.due_date is not None: query_set.append(todo) return query_set def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) today = datetime.datetime.now(datetime.timezone.utc) tomorrow = today + datetime.timedelta(days=1) todos_earlier = [] todos_today = [] todos_tomorrow = [] todos_later = [] for todo in ToDo.objects.filter(creator=self.request.user, is_checked=False): if todo.due_date is not None: if todo.due_date.day == today.day and todo.due_date.month == today.month and todo.due_date.year == today.year: todos_today.append(todo) elif todo.due_date.day == tomorrow.day and todo.due_date.month == tomorrow.month and todo.due_date.year == tomorrow.year: todos_tomorrow.append(todo) elif todo.due_date < today: todos_earlier.append(todo) elif todo.due_date > tomorrow: todos_later.append(todo) context["todos_earlier"] = todos_earlier context["todos_today"] = todos_today context["todos_tomorrow"] = todos_tomorrow context["todos_later"] = todos_later return context And this is … -
ValueError at /user_settings/ ModelForm has no model class specified
I'm creating a user setting page , where user can update his/her profile but after creating a ModelForm is gives this error. ModelForm has no model class specified. code in forms from django import forms from django.forms import ModelForm from blog.models import * from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class UserForm(ModelForm): class Mata: model=customer fields= '__all__' exclude=['user'] Code in views @login_required(login_url='login') @allowed_users(allowed_roles=['customer']) def user_settings(request): users=request.user.customer form=UserForm(instance=users) if request.method == 'POST': form=UserForm(request.POST, request.FILES, instance=users) if form.is_valid(): form.save() context = {'form':form} return render(request, 'blog/account_settings.html', context) Kindly help anyone -
Pointing Django storage to BunnyCDN
So I'm trying to serve /media/ files in a website through BunnyCDN, but I'm not exactly sure if I'm doing it right. From other remote storage implementations that I've seen, like AWS S3, I'm supposed to override the storage file that Django uses in my settings.py and do weird things to my urls file to point it to the server, but I'm kind of confused since the BunnyCDN documentation is very limited, and Django's own docs on writing custom storage systems are not very clear on this. I can't find anything since everyone seems to use AWS for this. -
Initializing manually rendered choice field on validation error
I've got a choice field that I'm manually rendering in my template. template.html <select name="pricing" id="id_pricing"> <option value> Make a selection </option> {% for value, object in form.pricing.field.choices %} <option value="{{value}}" {% if form.pricing.initial == value %} selected {% endif %} > {{object}} </option> {% endfor %} </select> This works 100% with one exception. If there is a validation error that gets thrown on another field due to checks that I have in def clean(), on the reload of the page, the value that populates the choice field isn't the one that the user just selected prior to submitting the form. It's 'Make a selection'. Do you know how I can ensure that the value that populates the choice field on reload of page due to validation error is the one that the user selected? Thanks for your help! -
Django 3.0: Unable to get value in view of selected option in template
I am at beginner level in django. And, I am unable to get the value of user selected option in view. I have to apply some logic there. views.py def shop(request): if request.GET.get('featured'): featured_filter = request.GET.get('featured') print(featured_filter) #debugging purpose else: print("\n\nnone\n\n") #debugging purpose bookz = Book.objects.order_by('title') var = {'books': bookz, 'range': 10} return render(request, 'bookrepo/shop.html', context=var) shop.html <form action="{% url 'bookrepo:shop' %}" method="GET"> <select name="featured" class="custom-select-lg custom-select"> <option selected><h1>Filter</h1></option> <option value="pricelow">Low price</option> <option value="pricehigh">High price</option> <input type="submit" name="featured" value="Filter" /> </select> </form> These option things have nothing to do with models. So right now, I am getting this when I select low price and press button: (in django console) [10/May/2020 00:18:20] "GET /shop/?featured=pricehigh&featured=Filter HTTP/1.1" 200 47486 [10/May/2020 00:18:20] "GET /static/js/js.dom.changer.js HTTP/1.1" 304 0 Filter [10/May/2020 00:18:24] "GET /shop/?featured=pricelow&featured=Filter HTTP/1.1" 200 47486 As u can see "Filter" is getting printed. But i want is featured's value like pricelow or pricehigh. -
How do I add security requirements to the password of my Django custom user model?
I'd like to start saying that I'm a beginner to Django, and I've been following a pretty great tutorial so far from Corey Schafer. In the project Corey uses the default Django User model, but I didn't want the users to log in with their username so I decided to override this as the Django docs say at https://docs.djangoproject.com/en/3.0/topics/auth/customizing/. I updated my registration forms with the new models and everything works fine. I can log in, log out and register properly, but I noticed that the password requirements for registration are gone. Previously Django would check if my password was too similar to the rest of my data, and had a minimum length requirement. I would like to know if there is a way to restore this feature. Here is my code for users/models.py: from django.db import models from django.contrib.auth.models import BaseUserManager, AbstractBaseUser from PIL import Image class UserManager(BaseUserManager): def create_user(self, email, name, password=None): """ Creates and saves a User with the given email, date of birth and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), name=name, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, name, password=None): """ Creates and saves a …