Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How to use more than 2 Class Based Generic Views in one template
I was trying to create a web app in which a user can see other posts while updating a post. So, for that, I want to use both ListView And UpdateView together in the same template. My Views.py: from django.shortcuts import render from .models import Entry from django.views.generic import ListView from django.views.generic.edit import UpdateView from django.contrib.auth.models import User from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin class index(LoginRequiredMixin, ListView): template_name = 'diary/index.html' context_object_name = 'entries' def get_queryset(self): # def get_queryset(self, request): return Entry.objects.filter(author=self.request.user) class EntryUpdate(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Entry fields = ['title', 'content'] template_name = 'diary/update.html' def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user == post.author: return True else: return False I don't know if I should create another view, or that there is an inbuilt functionality for this, so, it would be really helpful if you guys can help me out. Any Help Would Be Appreciated! -
Making HTTP GET request that target a collection of instances in DjangoRESTFUL
I started with checking if the serializer works as i expected but it didn't show any output after running the code. from datetime import datetime from django.utils import timezone from django.utils.six import BytesIO from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from toys.models import Toy from toys.serializers import ToySerializer toy_release_date = timezone.make_aware(datetime.now(), timezone.get_current_timezone()) toy1 = Toy(name='Snoopy talking action figure', description='Snoopy spearks five languages') toy1,save() toy2 = Toy(name='Hawaiian Barbie', description= 'Barbie loves Hawaii', release_date="") toy2.save() print(toy1.pk) print(toy1.name) print(toy1.created) print(toy1.was_inclded_in_home) print(toy2.pk) print(toy2.name) print(toy2.created) print(toy2.was_included_in_home) serializer_for_toy1 = ToySerializer(toy1) print(serializer_for_toy1.data) serializer_for_toy2 = ToySerializer(toy2) print(serializer_for_toy2.data) json_renderer = JSONRenderer() toy1_rendered_into_json = jason_renderer.render(serializer_for_toy1.data) toy2_rendered_into_json = json_renderer.render(serializer_for_toy2.data) print(toy1_rendered_into_json) print(toy2_rendered_into_json) json_string_for_new_toy = '{"name":"Clash Royale play set","descriptions":"6 figures from Clash Royele"}' json_bytes_for_new_toy = bytes(json_string_for_new_toy, encoding="UTF-8") stream_for_new_toy = BytesOI(json_bytes_for_new_toy) parser = JSONParser() parsed_new_toy =parser.parse(stream_for_new_toy) print(parsed_new_toy) new_toy_serializer = ToySerializer(data=parsed_new_toy) if new_toy_serializer.is_valid(): toy3 = new_toy_serializer.save() print(toy3.name) but then i had started with creating my Django views combined with serializer classes. from django.shortcuts import render from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from rest_framework import status from toys.models import Toy from toys.serializers import ToySerializer class JSONResponse(HttpResponse): def __init__(self, data, **kwargs): content = JSONRenderer().render(data) kwargs['content_type'] ='application/json' super(JSONResponse, self).__init__(content, **kwargs) @csrf_exempt def toy_list(request): if request.method == 'GET': … -
How to fix 'User has no attribute usergroup' eventhough it's added?
I have to develop a register form, I'm using crispy forms for this. (It was not my idea...), So I wrote a RegisterForm class (see code), and added some nice fields to work with, they all do work, unless usergroup = forms.ChoiceField(choices=GROUPS). Django shows me an Attribute error: User' object has no attribute 'usergroup'. Eventhough I can call all the other things such as fullname and email. I've already tried setting it to CharField and enter it manually but this gives me an error too. GROUPS = ( ('None', 'Choose...'), ('xyit', 'xy IT'), ('xyhr', 'xy HR'), ('xysales', 'xy Sales'), ('cn', 'admin'), ) class RegisterForm(UserCreationForm): fullname = forms.CharField() usergroup = forms.ChoiceField(choices=GROUPS) email = forms.EmailField() class Meta: model = User fields = ["fullname","usergroup", "username", "email", "password1", "password2"] And this is where I want to call it: def contacts(request): username = None if request.user.is_authenticated: username = request.user.username fullname = request.user.fullname email = request.user.email usergroup = request.user.usergroup print(email, fullname, usergroup) numberDevices = len(DeviceInformation.objects.all()) numberDevicesUser = len(request.user.deviceinformation.all()) return render(request, contact_req, {'username':username, "numberDevices": numberDevices, "numberDevicesUser": numberDevicesUser,}) else: return render(request, unauthorized_req, status=401) {% block register %} <form method="POST" class="form-group"> {% csrf_token %} {{ form|crispy}} <button type="submit" class="btn btn-dark">Register</button> </form> {% endblock %} Django==2.2.4 Python==3.6.8 AttributeError by Django … -
How to show specific fields only to the user profile owner in graphene-django?
I have the following schema in my graphene-django application: import graphene from django.contrib.auth import get_user_model from graphene_django import DjangoObjectType class UserType(DjangoObjectType): class Meta: model = get_user_model() fields = ("id", "username", "email") class Query(object): user = graphene.Field(UserType, user_id=graphene.Int()) def resolve_user(self, info, user_id): user = get_user_model().objects.get(pk=user_id) if info.context.user.id != user_id: # Return User object without the `email` field else: # Return User object with all fields I want to be able to query the schema in the following way: # Logged in as user 1 => no errors query { user (userId: 1) { id username email } } # Not logged in as user 1 => no errors query { user (userId: 1) { id username } } # Not logged in as user 1 => return error because accessing email query { user (userId: 1) { id username email } } How can I make it so that only a logged in user can see the email field of their own profile and no one else can see the emails of others? -
How to download content from my Django webpage?
I have a table on one of my Django webpage. I want to give the user the ability to download the content of the table in xl format. What would be an efficient and good way of doing this? I was thinking of creating an xlsx file using the xldr library. Writing the data on the file. making the file available for download and then deleting the file at the end, so that my drive stays clean. but it doesn't feel like a very efficient way. I'm new in web development, so open to all kind of ideas. Thanks -
Many-To-Many reverse field lookup with ids in Django
I try to figure out how to produce the correct queryset to retrieve url and value fields (Attr_1 and Attr_2 model) from querying the Object1 models 'reverse set' Many-to-Many Relation. Here is my Example: models.py: class Text(models.Model): string = models.TextField() #Entity class Element(models.Model): pageline = models.IntegerField() class Object1(Element): text = models.ManyToManyField(Text) class Object2(Element): another_var = models.ManyToManyField(Text) yet_another = models.CharField(max_length=1) #Entity class Attribute(models.Model): belongsTo = models.ManyToManyField(Element) class Attr_1(Attribute): url = models.URLField() class Attr_2(Attribute): value = models.CharField(max_length=255) date = models.URLField() If I use: >> models.Object1.objects.get(pk=1).attribute_set.all() <QuerySet [<Attribute: Attribute object (1)>, <Attribute: Attribute object (2)>]> >> models.Object1.objects.get(pk=1).attribute_set.values() <QuerySet [{'id': 1}, {'id': 2}]> I guess now I have to query Attr_1 for pk=1 and Attr_2 for pk=2? Does the Attribute model has a relation to know if id=1 is in Attr_1 or Attr_2 model? Any help is appreciated. Thank you! -
Not getting varaiable from django template
i am working on a function to send emails to users, from django admin area. I created a form in forms.py class SendEmailForm(forms.Form): subject = forms.CharField( widget=forms.TextInput(attrs={'placeholder': 'Subject'})) message = forms.CharField(widget=forms.Textarea) users = forms.ModelMultipleChoiceField(label="To", queryset=User.objects.all(), widget=forms.SelectMultiple()) And an admin action in admin.py: def send_emails(self, request, queryset): emails = "" for qr in queryset: emails += qr.email + ", " form = SendEmailForm(initial={'users': queryset}) context = {'form': form} return render(request, 'admin/send_email.html', context) send_emails.short_description = u"Send email" class CustomUserAdmin(UserAdmin): actions = [send_emails] And from views.py i am trying to extract the user emails, but i can only extract the message and the subject, when i extract the variable users i get the number of users. def send_emails(request): if request.method == 'POST': form = SendEmailForm(request.POST) print("STEP1") if form.is_valid(): users = request.POST['users'] print(users) and the template code is {% extends "admin/base_site.html" %} {% load i18n admin_urls static %} {% block content %} <p>{% blocktrans %}Write your message here{% endblocktrans %}</p> <form method="POST" action="{% url 'email' %}">{% csrf_token %} <div> <div> <p>{{ form.users.errors }}</p> <p>{{ form.users.label_tag }}</p> <p> {% for user in form.users.initial %} {{ user.email }}{% if not forloop.last %},&nbsp;{% endif %} {% endfor %} </p> <select name="users" multiple style="display: none"> {% for user … -
How to display list of lists in different divs in django
I have list of lists, which I'm sending to html: views.py: data = (('13:20','Dave','Stivenson'),('14:15','John','Scaletta'),('11:00','Dave','Johnston')) return render(request, 'test.html', {'rows': data}) test.html: {% for r in rows %} <div class="col-md-3"> <span style="color:white;font-size:14px">{{ r }}</span> </div> {% endfor %} It displays list in div, but how can I display not list, but list strings in div? Like: 13:20 Dave Stivenson -
Django: transfering two primary keys to new detail view
I'm trying to create a detail view where I use employee and subject name to show the evaluations created in the specific subject. I currently have this detail where, where I'm looping through the subject names and displaying all the evaluations for the subject for the employee. The view is using employee as the primary key. So when I press on the subject name from the loop below, I wish to go to a new view where I show the evaluations for the subject by the specific employee. Employee template {% for subject in subject_list %} {{ subject.subjectname }} {% for evaluation in subject.evaluation_set.all %} {{ evaluation.instructor }} {{ evaluation.ma }} {% endfor %} {% endfor %} I can't figure out what the best way to do this is. I believe using the employee primary key for the new view is correct, but how do I "transfer" the subject id from the loop to the next view? Alternatively I can use the subject id for the view but then I don't understand how to "transfer" the employee over. Employee view with subjects class EmployeeEvalDetailView(DetailView): template_name = 'evalsys/evalueringer/se_alle_evalueringer.html' model = Employee def get_context_data(self, **kwargs): context = super(EmployeeEvalDetailView, self).get_context_data(**kwargs) context['fagene'] = Subject.objects.all().prefetch_related(Prefetch('evaluation_set', … -
Responsive images wagtail django
My image is supposed to sit in a div which is 50% screen width (max width 800px for image in div) until 640px screen width where the div is 100%. I want the image to change height and width with the div. I want the whole image to always be shown basically. At the minute neither is changing and its messing up the responsiveness of the whole page. <tr class="fadeInBlock"> <td><!--div for image of architecture--> <div class="homeInfo5"> {{ page.architecturalText|richtext }} </div> </td> <td> <div class="homeIm4 responsive"> {% for item in page.gallery_images.all %} {% image item.image width-500%} <p>{{ item.caption }}</p> {% endfor %} </div> </td> </tr> .homeIm4 { height: auto; float: left; } .responsive { width: 100%; max-width: 250px; height: auto; } @media all and (max-width:640px) { table, thead, tbody, th, td, tr { display: block; } } In the image tag I have tried min max width original and fill. Nothing I've tried has worked. Without the image the responsiveness of the page is fine with just the text field. -
Prepopulate slug field from StackedInline Model Django
Here are how my models are setup: class Category(models.Model): name = models.CharField(max_length=255, unique=True) slug = models.SlugField(max_length=500, null=True, blank=False, allow_unicode=True) language = LanguageField(blank=False, choices=LANGUAGE_CHOICES, default='') class Post(models.Model): header = models.CharField(max_length=500, blank=False, default='') slug = models.SlugField(max_length=500, null=True, blank=False, allow_unicode=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="posts") content = RichTextUploadingField(blank=True, null=True) And admin.py : class PostInline(admin.StackedInline): model = Post extra = 0 class CategoryAdmin(admin.ModelAdmin): inlines = [PostInline] list_display = ('name', 'slug', 'ordering') prepopulated_fields = { 'slug': ('name',), } class PostAdmin(admin.ModelAdmin): list_display = ('get_category', 'header', 'creation_date', 'number_of_minutes') prepopulated_fields = { 'slug': ('header',), } When i am creating Post from Category StackedInline Posts in admin, slug does not prepopulate post header? -
Django-filter 2 use @property to filter?
I've got this filter: class SchoolFilter(django_filters.FilterSet): class Meta: model = School fields = { 'name': ['icontains'], 'special_id': ['icontains'], } Where special_id is a @property of the School Model: @property def special_id(self): type = self.type unique_id = self.unique_id code = self.code if unique_id < 10: unique_id = f'0{unique_id}' if int(self.code) < 10: code = f'0{self.code}' special_id = f'{code}{type}{id}' return special_id I've tried to google some answers, but couldn't find anything. Right now If I use my filter like I do I only receive this error: 'Meta.fields' contains fields that are not defined on this FilterSet: special_id How could I define the property as a field for this FilterSet? Is it even possible for me to use django-filter with a @property? Thanks for any answer! -
GraphQL mutation to create foreign key address and person
I have looked at a lot of articles about mutations with foreign keys and nothing is helping. I need to create a person with a django model Person, that has an address that is a foreign key to the Address model. A person needs an address! My models in django are: from django.db import models class Address(models.Model): class Meta: verbose_name_plural = "Addresses" number = models.CharField(max_length=4) street = models.CharField(max_length=100) city = models.CharField(max_length=100) postcode = models.CharField(max_length=7) class Person(models.Model): class Meta: verbose_name_plural = "Persons" avatar = models.ImageField(upload_to='images/avatars/') first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) address = models.ForeignKey(Address, on_delete=models.CASCADE) personal_image = models.ImageField(upload_to='images/personal_images/') def get_fullname(self): return self.first_name + ' ' + self.last_name My mutations in my schema are: class AddressInput(graphene.InputObjectType): number = graphene.String(required=True) street = graphene.String(required=True) city = graphene.String(required=True) postcode = graphene.String(required=True) class CreatePerson(graphene.Mutation): class Arguments: avtr = Upload(required=False) fname = graphene.String(required=True) lname = graphene.String(required=True) addr = graphene.Argument(AddressInput, required=False) pimage = Upload(required=False) person = graphene.Field(PersonType) def mutate(self, info, avtr, fname, lname, addr, pimage): person = Person( avatar=avtr, firstName=fname, lastName=lname, address=addr, personalImage=pimage ) return CreatePerson(person=person) class Mutations(graphene.ObjectType): create_person = CreatePerson.Field() I am testing with GraphiQL and my mutation atm looks like this: mutation createPerson { createPerson(avtr: None, fname: "Bob", lname: "Diamond", addr: {number: "10", street: "Hormond Avenue", … -
Bad pratice in ajax request appending html in a django template
In my page I have all the objects of the db displayed, with template tags I forloop the queryset to make every object displayed in a card. I want to filter these objects by category (which is a parameter) without refreshing the page so I made an ajax request which gets a JSON with the filtered objects and diplays them. The ajax function works fine but involves some bad practice as you can see in the code below. # my view class HomeView(ListView): model = Item paginate_by = 4 template_name = "home-page.html" //relevant part of my template <div class="row wow fadeIn" id="hardwarelist"> {% for item in object_list %} <div class="col-lg-3 col-md-6 mb-4"> <div class="card"> <div class="view overlay"> <img src="{{item.image}}" class="card-img-top" alt="" height="330" width="330"> <a href="{{ item.get_absolute_url }}"> <div class="mask rgba-white-slight"></div> </a> </div> <div class="card-body text-center"> <a href="" class="grey-text"> <h5>{{ item.get_category_display }}</h5> </a> <h5> <strong> <a href="{{ item.get_absolute_url }}" class="dark-grey- text">{{item.title}}<br/> <span class="badge badge-pill {{ item.get_label_display }}-color"> {{item.label}} </span> </a> </strong> </h5> // ajax function // bad pratice here, I append the card html tag by tag changing template tags // like {{item.title}} with js variables like objects.title, // basically I append all the html diplayed above and it's clearly bad … -
Patching default value of the field
I have a model with uuid field with default value as a function. from uuid import uuid4 def _new_uid(): return uuid4() class A(models.Model): name = models.CharField() uid = models.UUIDField(unique=True, default=_new_uid, editable=False) In test I want to patch _new_uid method return 11111111-1111-1111-1111-111111111111. @patch('module.foo._new_uid', Mock(return_value='11111111-1111-1111-1111-111111111111')) def test_create_A(): response = api_client.post('/api/a-list/', { 'name': 'test', }) assert response.json() == { '_uid': '11111111-1111-1111-1111-111111111111', 'name': 'test' } But it still returns some random uuid. I guess it's happening because model initialization is over before test start running. I can avoid it by changing default option to: uid = models.UUIDField(unique=True, default=lambda: _new_uid(), editable=False) Can it be done without changing default to lambda call? -
Django - Associating models with one another
As a part of a task, I created an "apartment listings" website. I managed to get that done, but now I need to make a "reservation system" for it. The basic idea is that a logged in user can select an apartment from the listed apartments, pick a "start_date" and an "end_date" (if the apartment already isn't booked ) and book the apartment. Im a total Django newbie, and need some pointers in order to start somewhere with this task. I have an Apartment model which contains all of the Apartments info that I use to print everything out with the template. I'm using the provided django user models to register / log-in. I’m using Django 2.1.8 I have created this view and model to make my reservations : view: def apartment_view(request, apartment_id): apartment = get_object_or_404(Apartment, pk=apartment_id) context = {'apartment': apartment, } context_instance = RequestContext(request) form = ReservationForm() if request.method == 'GET': form = ReservationForm() elif request.method == 'POST': form = ReservationForm(request.POST) if form.is_valid: form.save() # to go back to check that the info has changed return HttpResponseRedirect('/booking/') args = {} args['form'] = form return render(request, 'booking/index.html', args) models: class Apartment(models.Model): title = models.CharField(max_length=200) address = models.CharField(max_length=200) city = models.CharField(max_length=100) … -
How to access the last element added in Django Rest API?
I am creating my own portfolio website and created Django rest API. I want to extract or GET data of the last user. so what can I do in the following code? from django.contrib.auth.models import User from rest_framework import viewsets, filters from sample.api.serializers import UserSerializer class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer def viewname(request, user_id): user = User.objects.get(id=user_id) return ('hii :',user) viewname() -
Django - Initial form value from templates
i have one form and use it many times with a for loop in one template file. I want to set the values of the fields in my templates directly. I use Django-bootstrap4 and didn't now how to realize it. I tried the template tags "bootstrap_form" and "bootstrap_field", but I can't set the value of the fields. 1) for loop with the form without initializing the values (worked): {% for item in items %} <div class="modal fade" id="item_modal_{{item.id}}" ...> <div class="modal-content"> <div class="modal-body"> {% bootstrap_form form %} </div> </div> </div> {% endfor %} 2) Now I want to initial the form fields with the item values. I tried this: {% for item in items %} <div class="modal fade" id="item_modal_{{item.id}}" ...> <div class="modal-content"> <div class="modal-body"> {% bootstrap_field form.field1 value=item.field1 %} {% bootstrap_field form.field2 value=item.field2 %} {% bootstrap_field form.field3 value=item.field3 %} {% bootstrap_field form.field4 value=item.field4 %} </div> </div> </div> {% endfor %} Thank you! -
Django - Comma makes a newline
I have a form with multi select fields with predefined choices. And some of these strings contain commas. But when I iterate though these choices every comma create a newline/break tag. models.py KOMMUNIKATION_CHOICES = ( ('Formulerer sig kort og præcist i skrift og tale', 'Formulerer sig kort og præcist i skrift og tale'), ('Tilpasser sin skriftlige og mundtlige kommunikation til situationen og målgruppen', 'Tilpasser sin skriftlige og mundtlige kommunikation til situationen og målgruppen'), ('Søger aktivt at forstå og spørger ind til meningen i andres budskaber', 'Søger aktivt at forstå, og spørger ind til meningen i andres budskaber'), ('Giver åbent udtryk for holdninger og ideer', 'Giver åbent udtryk for holdninger og ideer'), ("Afklarer misforståelser, når de opstår", 'Afklarer misforståelser, når de opstår'), ) kommunikation = MultiSelectField( max_length=522, choices=KOMMUNIKATION_CHOICES, default="", ) example If anyone could clarify this or have any idea how to solve, please let me know. -
django-elasticsearch error : [Errno -2] Name or service not known
I'm trying to install an application developed by someone else and when running a manage.py command I'm getting this error, which I do not understand. I wonder if anyone can tell me where to look to investigate first - thank you. POST http://elasticsearch:9200/_bulk?refresh=true [status:N/A request:0.001s] Traceback (most recent call last): File "/home/henry/.virtualenvs/hjsm/lib/python3.6/site-packages/django/db/models/query.py", line 486, in get_or_create return self.get(**lookup), False File "/home/henry/.virtualenvs/hjsm/lib/python3.6/site-packages/djmoney/models/managers.py", line 209, in wrapper queryset = func(*args, **kwargs) File "/home/henry/.virtualenvs/hjsm/lib/python3.6/site-packages/django/db/models/query.py", line 399, in get self.model._meta.object_name providers.models.Organisation.DoesNotExist: Organisation matching query does not exist. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/henry/.virtualenvs/hjsm/lib/python3.6/site-packages/urllib3/connection.py", line 160, in _new_conn (self._dns_host, self.port), self.timeout, **extra_kw) File "/home/henry/.virtualenvs/hjsm/lib/python3.6/site-packages/urllib3/util/connection.py", line 57, in create_connection for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM): File "/usr/lib/python3.6/socket.py", line 745, in getaddrinfo for res in _socket.getaddrinfo(host, port, family, type, proto, flags): socket.gaierror: [Errno -2] Name or service not known During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/henry/.virtualenvs/hjsm/lib/python3.6/site-packages/elasticsearch/connection/http_urllib3.py", line 95, in perform_request response = self.pool.urlopen(method, url, body, retries=False, headers=self.headers, **kw) File "/home/henry/.virtualenvs/hjsm/lib/python3.6/site-packages/urllib3/connectionpool.py", line 641, in urlopen _stacktrace=sys.exc_info()[2]) File "/home/henry/.virtualenvs/hjsm/lib/python3.6/site-packages/urllib3/util/retry.py", line 344, in increment raise six.reraise(type(error), error, _stacktrace) File "/home/henry/.virtualenvs/hjsm/lib/python3.6/site-packages/urllib3/packages/six.py", line 686, in reraise raise value File "/home/henry/.virtualenvs/hjsm/lib/python3.6/site-packages/urllib3/connectionpool.py", line 603, … -
Connection Error : Max retries exceeded with url:/API/Admin/login.php
I am running my django application in local host and i tried with my IP address as well. I am getting the connection error. My views.py file is below def user_login(request): datas= {'log':False} if request.method == "POST": usern=request.POST.get('username') passw=request.POST.get('password') response = requests.post(url='https://www.onebookingsystem.com/API/Admin/login.php',data={"Username":usern,"password":passw},timeout=5) json_data = response.json() The error which i am getting is given below. File "C:\Users\Android V\Anaconda3\envs\djangoenv\lib\site-packages\requests\adapters.py", line 516, in send raise ConnectionError(e, request=request) requests.exceptions.ConnectionError: HTTPSConnectionPool(host='www.onebookingsystem.com', port=443): Max retries exceeded with url: /productionApi/API/Admin/login.php (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x00000000054620B8>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refusedit',)) [09/Oct/2019 18:28:21] "POST / HTTP/1.1" 500 156251 -
Unable to save data from both forms
I am trying to get Seller information, username, password, name, mobile number and address. I have used User to get the username and password, connected the username to my model through OneToOneField relationship and later save the information. I have made a model named SellerDetails which gets the user field from OneToOneField with User and rest all details are provided as follows: #models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class SellerDetails(models.Model): """docstring for SellerDetails.""" user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=128, null = True) address = models.CharField(max_length=256) mobile_number = models.IntegerField(primary_key=True) def __str__(self): return self.user.username then I have made two forms in my forms.py #forms.py from django import forms from django.contrib.auth.models import User from avkara.models import SellerDetails, VendorDetails class UserForm(forms.ModelForm): password = forms.CharField(widget = forms.PasswordInput()) class Meta: model = User fields = ('username', 'password') class SellerDetailsForm(forms.ModelForm): """docstring for SellerDetailsForm.""" class Meta: model = SellerDetails fields = ('name','address','mobile_number') #Then I tried established a relation while saving the form #views.py def Signup_seller(request): seller_registered = False if request.method == "POST": user_form = UserForm(data = request.POST) user_details = SellerDetailsForm(data = request.POST) if user_form.is_valid() and user_details.is_valid(): seller = user_form.save() seller.set_password(seller.password) seller.save() #saving user_details now other_details = user_details.save(commit= False) other_details.user … -
Is it possible to get the value from an option in the drop down list in django?
So currently I am adding new data through a model I registered to the django's admin site whereby the model consists of 3 text fields (email, country, phone number). I am also doing a phone numbers validation with PyPI's phonenumbers package to validate if the entered number is a number that exists or is in wrong format. However in order to this validation, I need to parse the text in the country text field (for e.g. US) as an argument into the validation code to know if the number is real or fake and currently I can pass the text over but users will have to type in "US" instead of selecting from a list of countries like from a drop down list. I want to improve this format by implementing a drop down list to replace the current country text field with a list of countries to select from but when a user selects the country United States, on the front end it is supposed to display "United States" in the drop down list but the value, as in html context should be "US" and I want to instead parse "US" instead to the backend to do validation but … -
Function within ModelManager can't be called
I can't seem to access a function within my model manager. models.py class ChargeManager(models.Manager): def dorefundcharge(self, charge_id): print(charge_id) class Charge(models.Model): charge_id = models.CharField(max_length=120) objects = ChargeManager() views.py charge_id = 1234 refund_of_charge = charge.dorefundcharge(charge_id) Error AttributeError at /accounts/profile/refundcharge/540/ 'Charge' object has no attribute 'dorefundcharge' -
Django - ["'on' value must be either True or False."]
I've rendered a normal form and got the inputs from the same, But while submitting the form is submitted with checkbox values as "On , Off" instead of "True, False" A little help would be appreciated. Thanks in advance Forms.py class bfs_version_filter_form(forms.Form): bfs_version_paid = forms.BooleanField(required = False, label = "Paid", initial = True ) url returned http://127.0.0.1:8000/bfslite/version_filter/?bfs_version_paid=on error ["'on' value must be either True or False."]