Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework populating data in template from API endpoint
Is there some specific way to populate data in django template from api endpoint? So i have a ajax call that calls a specific endpoint i technically could populate that data with js in success response, but are there any better ways of doing it? Even if no, is the approach of populating that data with js in success response even a decent approach? -
How can I attached title, content and date on the template
I am beginner in programming world. As for now I am following a video to create a blog with django. But, I have problem attaching the title, content, author and date on the template which I had downloaded from colorlib. I used the method below in the index.html file but they do now show: ''' {% extends 'base.html' %} {% load static %} {% block content %} {% for post in object_list %} <div class="site-section"> <div class="container"> <div class="row"> <div class="col-lg-8"> <div class="row"> <div class="col-12"> <div class="section-title"> <h2>Editor's Pick</h2> </div> </div> </div> <div class="row"> <div class="col-md-6"> <div class="post-entry-1"> <a href="#"><img src="{% static 'images/img_h_1.jpg' %}" alt="Image" class="img-fluid"></a> <h2><a href="{{ obj.title }}"></a></h2> <p>{{ obj.overview }}</p> <div class="post-meta"> <span class="d-block"> <a href="#">{{ obj.author.user.username }}</a> in <a href="#">{{ cat }}</a></span> <span class="date-read">{{ obj.timestamp|timesince }} ago<span class="mx-1">&bullet;</span> 3 min read <span class="icon-star2"></span></span> </div> </div> </div> {% endfor %} ''' -
Listing answers for question(get_object_or_404) in for loop. How can I get each answer also as an object in one def?
I am sorry if my title doesn't make much sense for you. I have a problem and I have a problem with describing it. I will be very grateful if you could help me. I have small voting system for my question objects. My questions have many answers that I am listing in "question_details" in for loop. I can of course access question model and therefore get informations about votes for question but I am unable to do the same for each answer. Maybe some code to better illustrate: views.py: def questiondetails(request, question_pk): question = get_object_or_404(Question, pk=question_pk) question_form_id = question total_voteup = question.total_voteup() total_votedown = question.total_votedown() is_voteup = False is_votedown = False if question.voteup.filter(id=request.user.id).exists(): is_voteup = True if question.votedown.filter(id=request.user.id).exists(): is_votedown = True I can check about of votes, and I can check if user vote up or down. in templates of questiondetails I am doing something like that: {% for answer in question.answer_set.all %} {{ answer }}<br> <div id="answer_voting_section"> {% include 'main/partials/answer_voting_section.html' %} </div> {% endfor %} And with that. I can click on my question, it will trigger "questiondetails" and bring me to it's page with question and answers coming from this for loop. And my problem is, that … -
Not possible to connect with http://127.0.0.1:8000/
I am trying to connect with the server http://127.0.0.1:8000/ (Django) but the only result is like below...: see print screen any ideas what went wrong? -
Generate automatic records in a table in Django even if the system is not being used
Does anyone know a way to generate a record in a table without the system being used by the user? I need to generate something similar to a notification or reminder, with various data obtained from other tables, something similar to a report Thank you -
Django contact form not working. GMAIL not recieving message
*****Hi Folks, I am a new Django. please help me to solve this issue. I am trying to use a simple contact form using Gmail configuration. When users click sends message button it reloads to should reload to the home page and should send messages to hosted email. I don't get any email with this process. I don't understand where I am going wrong.***** Forms.html {% extends 'base.html' %} {% block content %} <form action="{% url 'home' %}" method="post" id="contactForm" name="sentMessage" novalidate="novalidate"> <!-- --> {% csrf_token %} <div class="row align-items-stretch mb-5"> <div class="col-md-6"> <div class="form-group"> <input class="form-control" id="name" type="text" name="message_name" placeholder="Your Name *" required="required" data-validation-required-message="Please enter your name." /> <p class="help-block text-danger"></p> </div> <div class="form-group"> <input class="form-control" id="email" type="email" name="message_email" placeholder="Your Email *" required="required" data-validation-required-message="Please enter your email address." /> <p class="help-block text-danger"></p> </div> <div class="form-group mb-md-0"> <input class="form-control" id="phone" type="tel" name="message_phone" placeholder="Your Phone *" required="required"/> <p class="help-block text-danger"></p> </div> </div> <div class="col-md-6"> <div class="form-group form-group-textarea mb-md-0"> <textarea class="form-control" id="message" name="message_text" placeholder="Your Message *" required="required" data-validation-required-message="Please enter a message."></textarea> <p class="help-block text-danger"></p> </div> </div> </div> <div class="text-center form-group"> <div id="success"></div> <button class="btn btn-primary btn-xl text-uppercase" id="sendMessageButton" type="submit">Send Message</button> </div> </form> {% endblock content %} view.py File from django.shortcuts import render … -
How to Implement Image recognition system in Website using Django?
I have made an image recognition system using python and I am trying to implement that in website. I have have a system that recognizes the fruit images built using CNN. Now, I have built a website which is of a Fruit-blog. I want a section or a page in in that website in which a user can upload an image and the website can recognize which fruit is the given image of but I have no idea how to implement my recognition system in the website. Can you please help me explaining what to do and how can I implement the AI from python to Django website? -
Reverse Accessor for "CustomPAM.groups' clashes with reverse accessor for 'CustomUser.groups
I'm working on a django project for school. We pretty much have to build a program that allows users to answer peer assessments. In my django project, I currently have two models in separate apps. One model is to save user info, and the other is to save the peer assessments. Both the Models are below. mysite/PAM/models.py from django.db import models from django.contrib.auth.models import AbstractUser from datetime import datetime # Create your models here. class CustomPAM(AbstractUser): date_created=models.DateField(auto_now_add=True) starting_date=models.DateField(default=datetime.now, editable=True) deadline_date=models.DateField(null=True, editable=True) question1=models.TextField() question2=models.TextField() question3=models.TextField() question4=models.TextField() question5=models.TextField() question6=models.TextField() question7=models.TextField() question8=models.TextField() question9=models.TextField() question10=models.TextField() answer1=models.PositiveIntegerField(max_length=1, null=True, editable=True) answer2=models.PositiveIntegerField(max_length=1,null=True, editable=True) answer3=models.PositiveIntegerField(max_length=1,null=True, editable=True) answer4=models.PositiveIntegerField(max_length=1,null=True, editable=True) answer5=models.PositiveIntegerField(max_length=1,null=True, editable=True) answer6=models.PositiveIntegerField(max_length=1,null=True, editable=True) answer7=models.PositiveIntegerField(max_length=1,null=True, editable=True) answer8=models.PositiveIntegerField(max_length=1,null=True, editable=True) answer9=models.TextField(null=True, editable=True) answer10=models.TextField(null=True, editable=True) assessmentFrom = models.EmailField(unique=False) assessmentFor=models.EmailField(unique=False) def __unicode__(self): return self.assessmentFrom and mysite/myusers/models.py from django.db import models from django.contrib.auth.models import AbstractUser from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token class CustomUser(AbstractUser): username=models.CharField(max_length=50, unique=True) name=models.CharField(max_length=150) eagle_id=models.PositiveIntegerField(unique=True, null=True) email=models.EmailField(max_length=150, unique=True) password=models.CharField(max_length=80) is_student=models.BooleanField(default=False) is_professor=models.BooleanField(default=False) is_TA=models.BooleanField(default=False) team_number=models.PositiveIntegerField(default=0,null=False, editable=True) def __str__(self): return self.name #the next four lines are for generating tokens @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.get_or_create(user=instance) the users model is one I made a few weeks ago, the Peer Assessment Model is the … -
What tools do I need to use for a web application [closed]
So I'm teaching my self how to create web applications, like a blog. I'm currently just learning and have built some pages with HTML and CSS(with bootstrap), and I'm using Django. I'm wondering where do tools like React, MongoDB, Node.js come into play. Does Django cover all these things? To sum things up, I'm confused as to what tools you need. It would be great if you guys could break it up into categories, like the front-end framework, explain what it does, and give some examples of tools. I know there are groups of tools people use like the ones in MEAN stack, but I really don't get what they do. -
How to pass the request object on to setup(request, *args, **kwargs) of a FormView through Url
The url: path('signup/', SignUp.as_view()(request), name='signup'), the class whose request attribute i want to initialze with setup : class Login(FormView): template_name = 'products_app/login.html' form_class = UserLoginForm success_url = reverse_lazy('index') -
Django Rest Framework, getting error : 'NoneType' object has no attribute
I created a blog where people can do Post,comment and likes to post. When I POST new posts I get error AttributeError at /api/posts/ 'NoneType' object has no attribute 'user' ,error occur at serializers.py in get_user_has_voted, line 20. even though I get error , I am able to POST data and all other functionalities works fine. Why does the error happens ? How can I debug it ? SERIALIZER.PY class PostSerializers(serializers.ModelSerializer): comments = serializers.HyperlinkedRelatedField(many=True,read_only=True,view_name = 'comment_details') likes_count = serializers.SerializerMethodField() user_has_voted = serializers.SerializerMethodField() class Meta: model = Post fields = '__all__' #exclude=('voters',) def get_likes_count(self, instance): return instance.voters.count() def get_user_has_voted(self, instance): request = self.context.get("request") return instance.voters.filter(pk=request.user.pk).exists() # line 20 MODELS.PY class Post(models.Model): title = models.CharField(max_length=60) body = models.CharField(max_length=60) file = models.FileField(null=True,blank=True) voters = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="votes",null=True,blank=True) There are duplicate questions in Stack overflow but with different scenarios, as a begginer I couldn't grasp the idea. -
IIS Web Page Returns "Server Error 500" When I press "Submit" button (POST request)
I am using Django framework to create simple web portal for my team. The main purpose of the web portal is to deliver the file to a server using paramiko.SSHClent(). If I run my project on the local server using "python manage.py runserver", then pressing the "Submit" button delivers the file from the user to the server. The next step was to deploy the website. So, I used Windows Internet Information Service(IIS) Manager 8.5 to deploy my website. The website deployed, but there is one problem. If I press the "Submit" button, I get this error, "Server Error (500)" Here is the views.py file: from django.shortcuts import render, redirect from .forms import DocumentForm from django.contrib import messages import paramiko import os from . import file_mapping def uploadForm(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() document = request.FILES['document'] client_name = form.cleaned_data.get('client') file_type = form.cleaned_data.get('fileType') print('Client Name: ' + client_name) print('File Type: ' + file_type) file_mapping.handle_uploaded_file(document) file_mapping.setupfilename(client_name, file_type) #file_mapping.connectCqaServer(document) messages.success(request, f'Your file has been uploaded.') else: form = DocumentForm() #messages.warning(request, f'Your file is Invalid') return render(request, 'forms/forms.html', {'form': form}) Here is the forms.html file: {% extends "blog/base.html"%} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form … -
Django Rest API with okta OAUTH token authentication
I have a problem with Okta token authentication, I know how to authenticate with drf token and jwt token auth. In my project, I have to use okta token which is a type of jwt as well, however, this token is generated by front-end and send back to me in the request so here you can see how I authenticate the okta token with okta_jwt package: def post(self, request, *args, **kwargs): access_token = request.META.get('HTTP_AUTHORIZATION') try: validate_token(access_token, config.issuer, config.aud, config.client_id) except Exception as e: return JsonResponse({"result": e.args[0]}, status=400) .......... Basically I have to take the token out from the header and check with okta_jwt to see if it's legal Obviously, I don't think it's a good solution and it's hard to do unit test Can anyone provide a better solution for this? Thanks -
Go to newly created post
Once the user has made a valid post and pressed Post, I want them to be taken to the valid post. I ran a test with return redirect('post-detail', 18). At the moment once a valid post had been made then the post with ID 18 is loaded. I am trying to get the ID of the newly created post. What I am trying to write is return redirect('post-detail', id of newly created post) As this line works form.instance.author = self.request.user, I tried form.instance.id but it didn't have the desired results. Does anyone have any suggestions? class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'content'] def form_valid(self, form): form.instance.author = self.request.user return redirect('post-detail', 18) #print (form.instance.id) return redirect('post-detail', form.instance.id) -
I am trying to send the email to the user when user click on register button
def register_view(request): # Creates a New Account & login New users if request.user.is_authenticated: return redirect("/") else: title = "Register" form = UserRegistrationForm(request.POST or None) print(form.is_valid()) if form.is_valid(): user = form.save(commit=False) password = form.cleaned_data.get("password1") user.set_password(password) user.save() # new_user = authenticate(email=user.email, password=password) login(request, user) return redirect("/books") subject = "Greetings" msg = "Congratulations Yor Account is created Successfully. Do not share your login credentials with anyone else" to = "Ak4695755@gmail.com" res = send_mail(subject, msg, settings.EMAIL_HOST_USER, [to]) context = {"title": title, "form": form} return render(request, "accounts/signup.html", context) -
django.db.utils.ProgrammingError: can't adapt type 'CharField?
I am getting this error "django.db.utils.ProgrammingError: can't adapt type 'CharField' ", why is this error raising when i am trying to migrate to database -
Sort items by price on clicking dropdown
I have a dropdown and list of property. The dropdown contains two option, Low to High and High to Low. If any user clicks on any one of the dropdown item, the properties listed should sort by its price. How can I achieve that using javascript? property.html <div class="col-sm-6"> <div class="pxp-sort-form form-inline float-right"> <div class="form-group"> <select class="type-regular custom-select" id="pxp-sort-results" name="price-sorting"> <option value="" selected="selected disabled">Default Sort</option> <option class="price-sorting" value="l2h" id="l2h">Price (Lo-Hi)</option> <option class="price-sorting" value="h2l">Price (Hi-Lo)</option> </select> </div> </div> </div> <div class="row products-grid"> {% for item in properties.all %} <div class="col-sm-12 col-md-6 col-xxxl-4 product"> <a href="{% pageurl item %}" class="pxp-results-card-1 rounded-lg" data-price="{{ item.price }}" data-prop="1"> <div id="property-{{item.id}}" class="carousel slide" data-ride="carousel" data-interval="false"> <div class="carousel-inner"> {% for j in item.prop_images.all %} {% image j.prop_img original as property_img %} <div class="carousel-item {% if forloop.first %} active {% endif %}" style="background-image: url('{{property_img.url}}')"></div> {% endfor %} </div> <span class="carousel-control-prev" data-href="#{{item.prop_name}}" data-slide="prev"> <span class="fa fa-angle-left" aria-hidden="true"></span> </span> <span class="carousel-control-next" data-href="#property-{{item.id}}" data-slide="next"> <span class="fa fa-angle-right" aria-hidden="true"></span> </span> </div> <div class="pxp-results-card-1-gradient"></div> <div class="pxp-results-card-1-details" id="prop-dtls"> <div class="pxp-results-card-1-details-title">{{item.prop_name}}</div> <div class="pxp-results-card-1-details-price price">{{item.price}}</div> </div> <div class="pxp-results-card-1-features"> <span>{{item.bedroom}} BD <span>|</span> {{item.bathroom}} BA <span>|</span> {{item.sqft}} SF</span> </div> <div class="pxp-results-card-1-save"><span class="fa fa-star-o"></span></div> </a> </div> {% endfor %} </div> The values are coming dynamically from backend. -
my django view is always throwing "unexpected keyword argument error
i am familiar with python and started to learn django and it is fun in the begining how ever a table insertion becomes nightmare to me from 2 days and always throwing the following error sample() got an unexpected keyword argument 'firstname' i have tried all the possible ways on documentation and stackoverflow but nothing works. but another view with same syntax got worked for me that's so weird. here are my files. this is my stack trace. Traceback (most recent call last): File "C:\Users\manee\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\manee\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\manee\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\manee\myapp\PE\views.py", line 77, in sample a=sample(firstname=name) Exception Type: TypeError at /sample Exception Value: sample() got an unexpected keyword argument 'firstname' this is the combination of the worked view and troubling view(problems is working fine,sample is not working). def problems(request): name=request.POST['name'] title=request.POST['title'] difficulty=request.POST['example'] description=request.POST['description'] solution=request.POST['solution'] code=request.POST['code'] question=problem(name=name,title=title,difficulty=difficulty,description=description,solution=solution,code=code) question.save() return render(request,'thanks.html') def sample(request): name=request.POST['name'] email=request.POST['email'] rno=request.POST['rno'] a=sample(firstname=name,email=email,rno=rno) a.save() return render(request,'example.html',{'name':name}) and here is my models.py from django.db import models #Create your models here. class problem(models.Model): id=models.AutoField(primary_key=True) name=models.CharField(max_length=20) title=models.CharField(max_length=30) difficulty=models.CharField(max_length=10) description=models.TextField() solution=models.TextField() code=models.TextField() def __str__(self): return self.name class sample(models.Model): … -
How to Implement OR function on my queryset
I have currently created a model as shown below class Customer(models.Model): first_name = models.CharField(max_length=200, null=True) middle_name = models.CharField(max_length=200, blank=True,default='') last_name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) In my views.py I have, customer_list = Customer.objects.all() myFilter1 = CustomerlistFilter(request.GET,queryset=customer_list) customer_list = myFilter1.qs And within my filters.py I have written what is shown below class CustomerlistFilter(django_filters.FilterSet): id = CharFilter(lookup_expr='icontains') first_name = CharFilter(lookup_expr='iexact') middle_name = CharFilter(lookup_expr='iexact') last_name = CharFilter(lookup_expr='iexact') class Meta: model = Customer fields = ['id', 'first_name', 'middle_name', 'last_name'] Is there way of implementing the OR function, so that I can have one search box instead of multiple boxes for each field? -
Fetch data to input field django API
I am currently trying to get a city based on postal code. The situation: I got two input fields, zip code and city where when 4 digits are typed in zip code, the city field should be auto filled. What I've tried so far I got following code by far: template.html {% render_field form.zip_code id="zip_code" type="text" class="form-control w-100 mt-2" placeholder="Zip Code" %} {% if city %} {% render_field form.city id="city" type="text" value="{{ city.name }}" class="form-control w-100 mt-2" placeholder="City" %} {% else %} {% render_field form.city id="city" type="text" value="" class="form-control w-100 mt-2" placeholder="City" %} {% endif %} <script type="text/javascript"> $(document).ready(function() { $('#zip_code').on('change', function(){ var zipcode = $(this).val(); if(zipcode.length % 4 === 0){ $.ajax({ type:"GET", url:"https://dawa.aws.dk/postnumre?nr="+zipcode, success: function(data) { $('#city').val(data['navn']); }, error : function(){ alert('City not found!'); }, dataType: 'jsonp', }); }; }); }); </script> I am not sure why nothing happens. I can make a div, call it text and get the data via executing $('.text').text(JSON.stringify(data['navn'])); with a hit on enter. No auto check at 4 digits. But it won't somehow appear in my input fields value attribute. How can I make it from here? Thank you! -
Django Template IF inside Listing FOR
I am tryin use an object from a listing in an IF structure inside the FOR LOOP, but when I am trying to compare the object whit a String (That is 'TRUE'), I can not go inside the True case lines of the IF structure. Example: When equipo.Department = "Equipo", i don know why the IF ({% if equipo.Department == 'Equipo' %}) is not working. Code: {% autoescape off %} {% if equipos %} {% for equipo in equipos %} <tr></tr> <td>{% if equipo.Department == 'Equipo' %} E {% else %}{{ equipo.Department }}{% endif %}-{{ equipo.Equipment_id }}</td> <td>{{ equipo.Name }}</td> <td>{{ equipo.Description }}</td> <td>{{ equipo.SerialNo }}</td> <td>{{ equipo.Vendor }}</td> <td>{{ equipo.Tag }}</td> <td>{{ equipo.OutOfService }}</td> <td>{{ equipo.Location }}</td> <td>{{ equipo.Plan }}</td> <td>{{ equipo.ManualPath }}</td> <td>{{ equipo.ImagePath }}</td> </tr> {% endfor %} {% else %} <h1>No existen registros</h1> {% endif %} {% endautoescape %} -
showing only two out of three cards in my dashboard
I am creating the dashboard view for my CRM. However while displaying the card view, only two of the three card views are visible. Can anyone help me regarding this? Is this a code formatting issue? I am adding an image of the dashboard for my CRM below as well as the code for the cards given below. example.html: {% extends 'base.html' %} {% block content %} <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" /> <!-- Begin Page Content --> <div class="container-fluid"> <!-- Page Heading --> <div class="d-sm-flex align-items-center justify-content-between mb-4 mt-4"> <h1 class="h3 mb-0 text-gray-800">Welcome to NexCRM</h1> <a href="#" class="d-none d-sm-inline-block btn btn-sm btn-primary shadow-sm"><i class="fas fa-download fa-sm text-white-50"></i> Generate Report</a> </div> <!-- Main Content Here --> <div class="row"> <!-- Company Card Example --> <div class="col-xl-3 col-md-6 mb-4"> <div class="card border-left-primary shadow h-100 py-2"> <div class="card-body"> <div class="row no-gutters align-items-center"> <div class="col mr-2"> <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">Companies</div> <div class="h5 mb-0 font-weight-bold text-gray-800">4,083</div> </div> <div class="col-auto"> <i class="fas fa-building fa-2x text-gray-300"></i> </div> </div> </div> </div> </div> <!-- Company Card Example --> <div class="col-xl-3 col-md-6 mb-4"> <div class="card border-left-primary shadow h-100 py-2"> <div class="card-body"> <div class="row no-gutters align-items-center"> <div class="col mr-2"> <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">Companies</div> <div class="h5 mb-0 font-weight-bold text-gray-800">4,083</div> </div> … -
How do I mix vocals and music with python? [closed]
I want to make a website that offers free hip hop beats to rappers and hip hop artists. On this website, they should be able to record their vocals by listening to the music, and then both the music files and vocals should be synced together which makes a song. How can I do this? -
MultiValueDictKeyError at /account/register
Error: MultiValueDictKeyError at /account/register 'first_name' Request Method: POST Request URL: http://127.0.0.1:8000/account/register Django Version: 2.2.7 Exception Type: MultiValueDictKeyError Exception Value: 'first_name' Exception Location: C:\Users\Maansi\AppData\Roaming\Python\Python37\site-packages\django\utils\datastructures.py in getitem, line 80 views.py: def login(request): if request.method=='POST': username=request.POST['username'] password=request.POST['password'] user=auth.authenticate(username=username,password=password) if user is not None: auth.login(request,user) return redirect("/") else: messages.info(request,'invalid credentials') return redirect('login') else: return render(request,"login.html") def register(request): if request.method=='POST': first_name=request.POST['first_name'] last_name=request.POST['last_name'] username=request.POST['username'] password1=request.POST['password1'] password2=request.POST['password2'] email=request.POST['email'] if password1==password2: if User.objects.filter(email=email).exists(): messages.info(request,'Email Taken') return redirect('register') elif User.objects.filter(username=username).exists(): messages.info(request,'Username Taken') return redirect('register') else: user=User.objects.create_user(username=username,password=password1,email=email,first_name=first_name,last_name=last_name) user.save() print('user created') return redirect('login') else: messages.info(request,"Password don't match!") return redirect('register') else: return render(request,"register.html") login.html <div class="col-sm-6"> <div class="form-group"> {% csrf_token %} <input class="form-control valid" name="username" id="name" type="text" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Enter your username'" placeholder="Enter your username"> </div> </div> <div class="col-sm-6"> <div class="form-group"> {% csrf_token %} <input class="form-control valid" name="password" id="password" type="password" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Enter Password'" placeholder="Enter Password"> </div> </div> register.html: <div class="col-lg-8"> {% csrf_token %} <form class="form-contact contact_form" action="register" method="post"> <div class="row"> <div class="col-sm-6"> <div class="form-group"> {% csrf_token %} <input class="form-control valid" name="first_name" id="name" type="text" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Enter your name'" placeholder="Enter your name"> </div> </div> <div class="col-sm-6"> <div class="form-group"> {% csrf_token %} <input class="form-control valid" name="last_name" id="name" type="text" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Enter … -
Django: Is it Possible to create a model like Profile Model, to create an instance at the time of registration automatically
I have a custom user model and has created a profile model from it as well. so when user sign up a profile instance is created in the profile model as well. Now I have another similar model which is the address model. I tried configuring it in the same way but the address instance isn't getting created. Is it possible to do that? This is just for an understanding, whether similar model like profile can be created. this is my model. class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) summary = models.TextField(max_length=250, blank=True, null=True) birth_date = models.DateField(null=True,blank=True, auto_now_add=False, auto_now=False) country = CountryField(blank_label='(select country)') profile_pic = models.ImageField(upload_to='pimage/', default='pimage/default.png') def __str__(self): return f'{self.user.username} Profile' class Address(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE, blank=True, null=True) address = models.CharField(max_length=200, null=True) city = models.CharField(max_length=200, null=True) state = models.CharField(max_length=200, null=True) zipcode = models.CharField(max_length=200, null=True) mobile = models.CharField(max_length=12, null=True) def __str__(self): return f'{self.user.username} Address' views @login_required def address_add(request): if request.POST: a_form = AddressForm(request.POST, instance=request.user.address) if a_form.is_valid(): a_form.save() messages.success(request, f'Address Saved') return redirect('user_address') else: a_form = AddressForm(instance=request.user.address) context = {'a_form':a_form,} return render(request, 'áccounts/user_address.html', context)