Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Object of type AccessToken is not JSON serializable
So I am trying to send an email through my Django REST api, I am using Django_Rest_simplejwt for authentication, I am getting the following error when POSTing: TypeError at /auth/register/ Object of type AccessToken is not JSON serializable Request Method: POST Django Version: 3.1 Exception Type: TypeError Exception Value: Object of type AccessToken is not JSON serializable Exception Location: C:\ProgramData\Miniconda3\lib\json\encoder.py, line 179, in default Python Executable: C:\ProgramData\Miniconda3\python.exe Python Version: 3.7.6 Here is my code for sending an email for the user to confirm registration class CreateUserView(CreateAPIView): queryset = get_user_model() permission_classes = [AllowAny, ] serializer_class = UserSignUpSerializer def post(self, request): serializer = UserSignUpSerializer(data= request.data) data = {} if(serializer.is_valid()): account = serializer.save() data['response'] = "Successfully Registered A New User!" data['response'] = serializer.data user = MyUser.objects.get(email= serializer.data['email']) token = RefreshToken.for_user(user).access_token data['token'] = token #send email to the user upon registering #Note: that we used the function right away, because it is a staticmethod current_site = get_current_site(request).domain relativeLink = reverse("email-verify") #reverse gives us the path, when we give it the name attribute of the url absolute_url = "http://" + current_site + relativeLink + "?token = " + str(token) email_body = "Hi" + user.first_name + "\n" + "Please verify your email: \n" + absolute_url email_data … -
Best way to do complicated sitemaps in Django?
I have pretty complicated URLs for a Django website which are location-specific (by city and country) and based on detail pages (both static and dynamic). Is there a good package do collect all these pages? I probably have 1 million plus pages. How should I create this sitemap? Willing to spend some money too if there is product to do this. -
How to order a filtered django query set by a decimal field
I am trying to sort my query set by a "ranking value" which I have as a decimal field in my django model, however it seems the "order_by" function doesn't seem to work? my query set is always the same, with no ordering. I have tried the google but come up short, am i missing something here? Thanks in advance. -
Django - suing font awersome in unicode form
I want to use font awersome in my project in the way, that user can choose which icon he wants. I found django-fontawesome-5 but there is one problem - there is no access to icon's unicode and I need it for one javascript component (html doesn't work there, and unicode does). I was looking all over the internet, but I coundn't find anything that would allow me to add font-awersome icons, with their unicodes somhow stored. My question is do you know how to get this feature? -
Django upload fils - how to compress before saving to S3 Bucket?
Completely lost on how to compress my images before uploading them to an S3 bucket. I tried adding something like this to my save() method: def save(self, *args, **kwargs): # Opening the uploaded image (if it was uploaded) if self.receipt: im = Image.open(self.receipt) output = BytesIO() # Resize/modify the image im = im.convert('RGB') # after modifications, save it to the output im.save(output, format='JPEG', quality=80) output.seek(0) # change the imagefield value to be the newley modifed image value self.receipt = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" % self.receipt.name.split('.')[0], 'image/jpeg', os.sys.getsizeof(output), None) super(Expense, self). Not a big fan of this approach as the save method is run whenever an Expense instance is updated/created. So if a receipt (the image file) is attached, and I update any other field on the instance, another image file will be added to my S3 bucket. I tried adding if self.receipt and self.pk is None so the save() method only runs on new instances - however, I also want to compress files if they are added to an existing Expense instance. I hear a lot of talk about lambda functions to do the compression on the fly, but can't find any decent guides on how to set it up. I'm … -
How to remove plus sign in Django Admin many to many field?
many to many field How to remove add and edit button on Django Admin in many-to-many fields? -
Saving custom Signup form in django-allauth
I have problems with saving my custom signup form using django-allauth. The form displays correctly on the page. When I click the "register" button, a POST request is sent which does not save anything to the database. The save() method is not called on the form. models.py: import uuid from django.contrib.auth import password_validation from django.contrib.auth.base_user import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.core.exceptions import ValidationError from django.core.mail import send_mail from django.db import models from django.utils.translation import ugettext_lazy as _ from .managers import UserManager from edu.models import Course, Group class User(AbstractBaseUser, PermissionsMixin): MODERATION_STATUS_SIGNUP = 'signup' MODERATION_STATUS_ON_REVIEW = 'on_review' MODERATION_STATUS_REJECTED = 'rejected' MODERATION_STATUS_APPROVED = 'approved' MODERATION_STATUSES = [ (MODERATION_STATUS_SIGNUP, 'В процессе регистрации'), (MODERATION_STATUS_ON_REVIEW, 'На рассмотрении'), (MODERATION_STATUS_REJECTED, 'Отклонен'), (MODERATION_STATUS_APPROVED, 'Подтвержден'), ] id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) secret_hash = models.UUIDField('хэш', default=uuid.uuid4, blank=True, editable=False) email = models.EmailField('email', unique=True) first_name = models.CharField('имя', max_length=150, blank=False) middle_name = models.CharField('отчество', max_length=150, blank=False) last_name = models.CharField('фамилия', max_length=150, blank=False) is_student = models.BooleanField('курсант', default=False) is_elder = models.BooleanField('старшина', default=False) is_ct = models.BooleanField('классный руководитель', default=False) is_hc = models.BooleanField('воспитатель', default=False) is_watch = models.BooleanField('работник вахты', default=False) is_staff = models.BooleanField('работник института', default=False) is_admin = models.BooleanField('администратор', default=False) is_active = models.BooleanField('активный пользователь', default=False) moderation_status = models.CharField( 'статус аккаунта', max_length=32, choices=MODERATION_STATUSES, default=MODERATION_STATUS_SIGNUP, ) date_joined = models.DateTimeField(_('date joined'), auto_now_add=True) last_login = … -
Looping issue in Django Template
enter image description here As you can see in the above picture {{forloop.counter}} is working just below the loop but not at Quiz{{forloop.counter}} Is there any specific reason? How can i solve it? -
How can I make a single query in Django and get only those users who have an entry in the table with one product and not with another?
I have two tables: one with users(where only the name and ID), the other with the purchases of these users. I want to get for one request users who have 'car' and no 'bike' among the purchased products. How do I do this? My Models: class Client(models.Model): name = models.CharField(max_length=200) class Purchases(models.Model): client = models.ForeignKey(Client, on_delete=models.PROTECT) product = models.CharField(max_length=200) -
JSON array out of order
I have a React/Django application where users can answer multiple choice questions. I have the "choices" array rendered onto the UI in this exact order. { "id": 2, "question_text": "Is Lebron James the GOAT?", "choices": [ { "id": 5, "choice_text": "No", "votes": 0, "percent": 0 }, { "id": 4, "choice_text": "Yes", "votes": 1, "percent": 100 } ], } When I select a choice in development mode, I send a request to Django to increment the votes counter for that choice and it will send back a response with updated votes in the same order. When I try to select a choice in production mode using npm run build, the order becomes switched. { "id": 2, "question_text": "Is Lebron James the GOAT?", "choices": [ { "id": 4, "choice_text": "Yes", "votes": 1, "percent": 50 }, { "id": 5, "choice_text": "No", "votes": 1, "percent": 50 } ] } I thought the order of JSON array must be preserved. Can anyone explain why this is happening? I'm almost positive that this issue is originating from Django. Here is the function view on Django. @api_view(['POST']) def vote_poll(request, poll_id): if request.method == 'POST': poll = Poll.objects.get(pk=poll_id) selected_choice = Choice.objects.get(pk=request.data['selected_choice_id']) selected_choice.votes += 1 selected_choice.save() poll_serializer = PollAndChoicesSerializer(poll) … -
Django - How to dynamically choose base template
I want to choose which base template to use in my Django project from a possible three options. I sourced online and, from this link, I saw: Use a variable. {% extends base_template %} and in your view, set it to "base.html" in your view, or a new "ajax.html" file which just provides the block and nothing else. But a comment to that answer reads: This breaks django-compressor offline compression. I do not know what that means Another answer said: {% extends request.is_ajax|yesno:"app/base_ajax.html,app/base.html" %} But I am not making AJAX request. From this answer, I discovered the yesno Django provides. This works just for True or False; more like if-else statement. How can I achieve if, else and else-if statements ? Because that seems to be one way I could achieve what I am trying to achieve. But if you have better options, please pour it out. Here is what I tried {% if user_type == 1 %} {% extends 'hod_template/base.html' %} {% load static %} {% elif user_type == 2 %} {% extends 'staff_template/base.html' %} {% load static %} {% else %} {% extends 'student_template/base.html' %} {% load static %} {% endif %} But I got Invalid block tag … -
Cannot pull the value from the key of a session dictionary in django
I have a session variable for the name of a company saved in my django view from a user input form. When I try and use this in a later view, no matter what I try it pulls the {key: value} pair rather than just the value Views: def start(request): if request.method == 'POST': # create a form instance and populate it with data from the request: form = QuizTakerForm(request.POST ) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required post = form.save(commit=False) post.user = request.user post.save() request.session['obj_id'] = post.id request.session['company_name'] = form.cleaned_data # redirect to a new URL: return HttpResponseRedirect('industry/') .... def Gov_q1(request): company_name = request.session.get('company_name') print(company_name) question = Question.objects.get(pk=24) context = {'question': question, 'company_name': company_name} return render(request, 'ImpactCheck/detail.html', context) html: <h1> Hi my name is {{ company_name }} </h1> <h1>{{ question.text }}</h1> <form action="." method="post"> {% for answer in question.answer_set.all %} <input type="radio" name="answer" id="answer" value="{{ answer.id }}"> <label for="answer">{{ answer.answer_text }}</label><br> {% endfor %} <input type="submit" value="Submit"> </form> Ive also tried company_name=request.session['company_name'], but both then render as {'company_name': 'test_company'} rather than test_company. -
How to use a list in Django query for addition of fields
I like to perform a Django query like the one below: query = Dbmodel.objects.all().annotate(result=F('fieldname1') + F('fieldname2') + F('fieldname4')) But instead of using the fieldnames directly, I would like to use a list with the field names: fields = ['fieldname1', 'fieldname2', 'fieldname4'] Depending on user interaction the number of fieldnames in the list can variate. Is there a way to do it? As this is my first question on StackOverflow, please let me know, if my question is unclear or I could improve my question. -
Rails or Django when you know Python well and Rails well but not Ruby nor Django
I know Rails well enough to build apps quickly (and have code I can reuse). But I don't know Ruby well (I realize the oddity). At the same time I do know Python well, having used it for data science. But I don't know much about Django. I want to build an app that is well beyond Django official tutorial difficulty (the polls app), and at the same time use cutting-edge algorithms in ML and NLP (might use tensorflow). So if Rails, I'd need to use micro service or call python script. If you were in my shoes, which framework would you use? -
argparse.ArgumentError: argument --skip-checks: conflicting option string: --skip-checks
I am working with django-tenant-schemas and when I try to use "migrate_schemas" command I encounter an error. I've seen similar questions here but they didn't help at all. I've tried this on two different apps but the result is the same. Does anybody know how to fix this? Traceback (most recent call last): File "C:\DjangoNew\tenancy\manage.py", line 22, in <module> main() File "C:\DjangoNew\tenancy\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 322, in run_from_argv parser = self.create_parser(argv[0], argv[1]) File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 296, in create_parser self.add_arguments(parser) File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\site-packages\tenant_schemas\management\commands\migrate_schemas.py", line 20, in add_arguments command.add_arguments(parser) File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\commands\migrate.py", line 28, in add_arguments help='Skip system checks.', File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\argparse.py", line 1373, in add_argument return self._add_action(action) File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\argparse.py", line 1736, in _add_action self._optionals._add_action(action) File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\argparse.py", line 1577, in _add_action action = super(_ArgumentGroup, self)._add_action(action) File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\argparse.py", line 1387, in _add_action self._check_conflict(action) File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\argparse.py", line 1526, in _check_conflict conflict_handler(action, confl_optionals) File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\argparse.py", line 1535, in _handle_conflict_error raise ArgumentError(action, message % conflict_string) argparse.ArgumentError: argument --skip-checks: conflicting option string: --skip-checks -
Is there any way to use social auth in Django for multiple user types?
As the title says, is there any way to use social auth in Django for multiple user types? With user types I mean that there will be Students, Doctors and Patients in my platform. from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): is_doctor = models.BooleanField(default=False) is_student = models.BooleanField(default=False) is_patient = models.BooleanField(default=False) class Doctor(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) #TO DO - More attributes class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) #TO DO - More attributes class Patient(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) #TO DO - More attributes I want to let all of them to register and login with their Google Account. I have been looking at internet and allauth-django documentation, but I could´nt find any relevant info for my issue. Thanks in advance! -
Django - 500 error after launch on elastic-beanstalk
Hello I am still pretty green with the whole web deployment thing so bear with me this is only my second deployment. I've run into an issue called "500 Internal Server Error" I checked the aws documentation and all it can give me is error is unknown. The code all ran before I launched using runserver and the server was running before I put the code in so I don't know where the issue could be. I used eb logs to get the following data: ============= i-030b809a2708731e5 ============== /var/log/httpd/error_log [Tue Oct 06 19:47:09.942986 2020] [:error] [pid 4761] [remote 172.31.36.89:152] apps.populate(settings.INSTALLED_APPS) [Tue Oct 06 19:47:09.942991 2020] [:error] [pid 4761] [remote 172.31.36.89:152] File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/apps/registry.py", line 81, in populate [Tue Oct 06 19:47:09.942994 2020] [:error] [pid 4761] [remote 172.31.36.89:152] raise RuntimeError("populate() isn't reentrant") [Tue Oct 06 19:47:09.943009 2020] [:error] [pid 4761] [remote 172.31.36.89:152] RuntimeError: populate() isn't reentrant[Tue Oct 06 19:47:22.721931 2020] [:error] [pid 4761] [remote 172.31.36.89:152] mod_wsgi (pid=4761): Target WSGI script '/opt/python/current/app/SpaceNerdsLaunch/wsgi.py' cannot be loaded as Python module. [Tue Oct 06 19:47:22.721979 2020] [:error] [pid 4761] [remote 172.31.36.89:152] mod_wsgi (pid=4761): Exception occurred processing WSGI script '/opt/python/current/app/SpaceNerdsLaunch/wsgi.py'. [Tue Oct 06 19:47:22.722087 2020] [:error] [pid 4761] [remote 172.31.36.89:152] Traceback (most recent call last): [Tue Oct … -
CSRF Token error when attempting to post from CURL to an API endpoint I control. How do I write the request?
I have not utilized this part of Django before, but I have an endpoint which is giving me a 403 error and is telling me that my request needs a csrf token. I was trying to figure out how best to get this since I was attempting to set up a bunch of curl requests to handle some simple queries to the endpoint. Likewise, I was thinking to also use POSTman, but I was not sure where documentation is to handle these request. I have seen the cookie csrftoken, but when I was attempting to curl with it, it was still giving me a 403. thought it would looking something like this: curl -d @profilepicturev2.png -b "csrftoken=Ebfn2OlfhSwFjAEQdoQon7wUjbynFoJqrtHMNPla3cy7ZfCMT9cxZ3OQHsbaedam" http://127.0.0.1:8000/api/files/uploader Maybe I am mistaken? -
Rest API schema to retrieve value from database and return
I need to make a Rest API which will take 3 inputs: input_list (list of srings sentences), from_lang (string), to_lang (string) and return list of string after fetching values from databse table. Example: input - {input_list: ['how are you', 'see you later', 'where are you'], from_lang: 'english', to_lang: 'spanish' } output - {['cómo estás', 'nos vemos más tarde', 'Dónde estás']} A service will call this API with list of sentences in any supported language, and in return they will get list of same length with translated sentence if it exist in database or null value if it doesn't exist. How should I proceed? What I have done is, I have created a serializer to handle/validate incoming request in serializers.py: def supported_lang(value): if value not in SUPPORTED_LANGUAGES: print(value) print(SUPPORTED_LANGUAGES) raise serializers.ValidationError('Language not supported') class TranslateSerializer(serializers.Serializer): input_list = serializers.ListField( child=serializers.CharField(allow_blank=False), allow_empty=False ) from_language = serializers.CharField(validators=[supported_lang]) to_language = serializers.CharField(validators=[supported_lang]) And I have defined a simple model for storing translations in model.py: class TranslationModel(models.Model): english = models.CharField(blank=False, max_length=MAX_LENGTH, unique=True) spanish = models.CharField(blank=True, max_length=MAX_LENGTH) italian = models.CharField(blank=True, max_length=MAX_LENGTH) is_active = models.BooleanField(default=True) Then in my views.py I have handled post requests like below class TranslateView(views.APIView): def post(self, request): serializer = TranslateSerializer(data=request.data) serializer.is_valid(raise_exception=True) serialized_data = serializer.validated_data result … -
In Django FileField, how to set file.name that contains also random url?
I am trying to modify the name of an uploaded file to include also some url in it. In my case it's the custom "file_url" variable. However the current result is: , but the expected result should be: http://www.google.com/ Here is my View.py: class CreateImage(CreateAPIView): permission_classes = (IsAuthenticated,) model = models.Image serializer_class = serializers.ImageSerializer def get_serializer(self, container, *args, **kwargs): serializer_class = self.get_serializer_class() kwargs["context"] = self.get_serializer_context() old_filename = self.request.FILES['image'].name if self.request.FILES: if container == 'products': data = self.request.data.copy() product_name = data["product_name"] file_url = f"{settings.MEDIA_DOMAIN}{container}/" new_filename = get_product_new_filename(old_filename, product_name) data['image'].name = file_url + new_filename kwargs["data"] = data return serializer_class(*args, **kwargs) And simple model for reference: class Image(models.Model): image = models.FileField() def __str__(self): return self.image.name Do you have any idea, how to include given url in the filename? The workaround, would be to create additional field, say image_url as CharField, and save it there, but maybe there is a way to not duplicate table inputs. Thanks in advance! -
use django default PasswordResetView and my own view in one template
i want to use django's default password reset view "PasswordResetView" in a template that already has a view that i built on my own, after looking at the tutorials and the questions i found how to use it only on a different template that is made only for the password reset, but i don't want the user to go to a different page just to change his password when he forgets it, i want to make it in a bootstrap modal in the home page here is my home view in my views.py def home(request): user = request.user signin_form = SigninForm() signup_form = SignupForm() if request.method == "POST": if 'signin_form' in request.POST: signin_form = SigninForm(request.POST) if signin_form.is_valid(): email = request.POST['email'] password = request.POST['password'] user = authenticate(email=email, password=password) if user: login(request, user) elif user is None: messages.error(request, 'ُEmail or password is incorrect') if 'signup_form' in request.POST: signup_form = SignupForm(request.POST) if signup_form.is_valid(): signup_form.save() full_name = signup_form.cleaned_data.get('full_name') email = signup_form.cleaned_data.get('email') raw_password = signup_form.cleaned_data.get('password1') account = authenticate(email=email, password=raw_password) login(request, account) context = {'signin_form': signin_form,'signup_form': signup_form} return render(request, 'main/home.html', context) NB: i tried copy pasting the source code of that view (PasswordResetView) from django's source code in my view but i found some errors because … -
Django / Drf "The 'image' attribute has no file associated with it."
I use sorl-thumbnail in my models. While querying the videolessons objects list, some of them tells me an error "The 'image' attribute has no file associated with it." . In the admin field I can see the image field and image. My model is: from sorl.thumbnail import ImageField class Videolesson(models.Model): def upload_location(instance, filename): VideolessonModel = instance.__class__ try: new_id = VideolessonModel.objects.order_by("id").last().id + 1 except: new_id = 1 return "{} {}".format(new_id, filename) # Relations # Attributes - Mandatory user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_( "user"), on_delete=models.CASCADE,) title = models.CharField(max_length=200, verbose_name=_( "title"), help_text=_("Enter the Videolesson title")) slug = models.SlugField(unique=True) image = models.ImageField(null=True,blank=True,upload_to=upload_location,) and my serializer class VideolessonSerializer(serializers.HyperlinkedModelSerializer): user = serializers.StringRelatedField(read_only=True) user_image = serializers.StringRelatedField(source='user.image.url', read_only=True) user_thumbnail = HyperlinkedSorlImageField( '60x60', options={"crop": "center"}, source='user.image', read_only=True ) thumbnail = HyperlinkedSorlImageField( '400x400', options={"crop": "center"}, source='image', read_only=True ) # A larger version of the image, allows writing image = HyperlinkedSorlImageField('1024') class Meta: model = Videolesson fields = [ "slug", "user_thumbnail", "user", "user_image", "thumbnail", "image",] I have tried to create a new videolesson now I have error in that one too. How can I fix this error ? Thanks -
Django Bootstrap modal carousel
Hello I am trying to create simple gallery and one of the feature I would like to add is modal window with carousel in it. For a backend I am using Django framework. And its current state it is partially working. If I click on image, the modal window opens but it show the 1st image on the site even though I click on any other image, it still shows the first image. Second issue is that the controls of the carousel do not work on any side and it keeps showing only 1st image and I am not able to see on any other. Here is the code of the template: <!--Loading images from Django.--> <div class="gallery" id="gallery" data-toggle="modal" data-target="#exampleModal"> <!-- Grid column --> {% for picture in images %} <div class="mb-3 pics animation all 1 filter {{ picture.gallery_cat.category }}" id="galleryImage"> <img class="img-fluid" src="{{ picture.image.url }}" data-target="#carouselExample" data-slide-to="{{ forloop.counter }}"> </div> {% endfor %} </div> <!-- Modal window --> <div class="modal fade " id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> </div> <div class="modal-body"> <!-- Indicators --> <div class="carousel slide" id="MyCarousel"> <!-- Wrapper for slides --> <div class="carousel-inner"> {% for picture … -
Set a Model default value relative to another field
I'm building an auctions site and I want the highest_bid on a listing to be >= start_price and in turn set the bid_input to raise a ValidationError if a user tries to enter a bid_input < highest_bid. I don't want the user to have to enter a highest_bid when creating the form so I've set it to hidden input but want to figure out how to capture this value. I think I may have worked out how to validate bid_input using clean(self) but I am unsure how to set the highest_bid default value to greater or equal to the start_price. Should this be done on the model or on the form on saving? I'm quite confused on how to go about this really. models.py class Listing(models.Model): class NewManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(status='active') options = ( ('active', 'Active'), ('closed', 'Closed'), ) title = models.CharField(max_length=64) description = models.TextField(max_length=64) start_price = models.DecimalField(max_digits=9, decimal_places=2, validators=[MinValueValidator(0.99)]) image = models.URLField(max_length=200, blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="listings") lister = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=None, null=True, blank=True) date_added = models.DateTimeField(default=timezone.now) highest_bid = models.DecimalField(max_digits=9, decimal_places=2, default=None) status = models.CharField(max_length=10, choices=options, default="active") favourites = models.ManyToManyField(User, related_name="favourite", default=None, blank=True) objects = models.Manager() listingmanager = NewManager() def __str__(self): return f"{self.title} ({self.pk}, £{self.start_price}, {self.lister})" class … -
How does the "action" attribute work in a Django form?
I have learned about forms in Django(from scratch and using ModelForm). ModelForm is super helpful! I can code the whole thing, but one thing that got me confused is the "action=" attribute in a form tag on a template. This is what I have, for example: models.py : from django.db import models class Drinks(models.Model): size = models.IntegerField() color = models.CharField(max_length=10) brand = models.CharField(max_length=100) suggestion = models.CharField(max_length=100) forms.py : from django import forms from django.forms import ModelForm from django.forms import Textarea from .models import Drinks class DrinkForm(ModelForm): class Meta: model = Drinks fields = '__all__' widgets = {'suggestion': Textarea(attrs={'cols': 80, 'rows': 30})} views.py : from django.http import HttpResponseRedirect from django.shortcuts import render from .models import Drinks from .forms import DrinkForm def thanks_3(request): return render(request, 'robots/drink_thanks.html') def get_drink_info(request): if request.method == 'POST': form = DrinkForm(request.POST) if form.is_valid(): s = form.cleaned_data['size'] c = form.cleaned_data['color'] br = form.cleaned_data['brand'] sgg = form.cleaned_data['suggestion'] new_instance = Drinks(size=s, color=c, brand=br, suggestion=sgg) new_instance.save() return HttpResponseRedirect('/drink-thanks-message/') else: form = DrinkForm() context = {'form': form} return render(request, 'robots/drinks_form.html', context) urls.py : from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('drinks/', views.get_drink_info, name='drinks-007'), path('drink-thanks-message/', views.thanks_3, name='tnx3'), ] base.html : <!DOCTYPE html> {% load static %} <html …