Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting error while communicating django channel with Redis
enter image description here I am trying to crate a chatapp.I referred to django tutorial provided in documentation.How to get rid of this error?? -
Can't show new added attr in template from object in Queryset in UpdateView (Django)
I'm trying to output a list of objects that are affected by this object. The main model doesn't affect the additional one, so I'm trying to add the list to the new object attribute. When I output .__dict__ of an object after adding a new attribute, everything is OK, but the template outputs a blank. How do I fix this? My code in UpdateView: def get_queryset(self): print('ID: ', self.kwargs['adapter_account_id']) deals = Deal.objects.filter(adapter_account=self.kwargs['adapter_account_id']) adapter_acc = AdapterAccount.objects.filter(id=self.kwargs['adapter_account_id']) for obj in adapter_acc: obj.deals = deals print(adapter_acc[0].__dict__) return adapter_acc Output for .__dict__: {'_state': <django.db.models.base.ModelState object at 0x7fa0590547c0>, 'id': 13, 'adapter_id': 9, 'params': {'secret': 'secret', 'pay_gate': 'VV', 'product_id': '10731', 'merchant_id': '1998'}, 'deals':<QuerySet [<Deal:#28>, <Deal: #30>]>} My try to render value in template: {{ adapteraccount.deals}} For example, {{ adapteraccount.params}} works fine. -
wagtailmenus - iterating submenu items
I'm getting started with wagtail, (and Django), and using wagtailmenus. I'm having trouble getting the submenu object that I (presumably) iterate to build submenus where required. main_menu.html {% for item in menu_items %} <li class="dropdown nav-item"> <a class="nav-link href="{{ item.href }}">{{ item.text }}</a> {% if item.has_children_in_menu %} {% sub_menu item %} {% endif %} </li> {% endfor %} This code renders the top level items fine, and recognises when the submenu is required, and references the correct template. sub_menu.html <div class="dropdown-menu"> <a href="{{ item.href }}" class="dropdown-item"> {{ item }} </a> </div> However, item is the previous item - so I just get the top level item repeated, once. As far as I can figure out, I need to get a iterable object of the sub menu, and build it in the same way as the top level menu. Something like, pseudo_sub_menu.html {% for sub_item in item %} <a href="{{ sub_item.href }}" class="dropdown-item"> {{ sub_item.text }} </a> {% endfor %} But that returns 'MainMenuItem' object is not iterable How can I go about this? -
How to get the desired column name?
In my app/views.py, I have got all the column names: columns = MyModel._meta.get_fields() How to get the desired column names here? Eg. How to cut the above columns to get the last 10x column names? How to get the 1st + 3nd + 6th + 10th column names together? Thanks for the help! -
Ajax & Django to calculate a price before submitting to database
I have this so far. But I want to take the input fields and add first with the calculate button. I have successfully implemented a Submit button, but the problem I run into is I'm trying to first calculate and display before submitting to my database. This is what I have so far, but I'm not sure how to create the html function to add them all up.. Book Price: $10 (input field) Delivery charge: $3 (input field) Delivery type: $5 (input field) Final Result: $18 (result of adding the fields above when user clicks the calculate button) [calculate] [submit] submit button will finalize the results and send the values to the database. This is my model for the table class book(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) book_price = models.IntegerField() delivery_charge = models.IntegerField() delivery_type = models.IntegerField() final_result = models.IntegerField() def save(self, *args, **kwargs): self.final_result = self.book_price + self.delivery_charge + self.delivery_type print(self.final_result) super(book, self).save(*args, **kwargs) views.py for the form def final_price(request): response_data = {} if request.method == 'POST': form = RequestForm(request.POST) book_price = request.POST.get('book_price') delivery_charge = request.POST.get('delivery_charge') delivery_type = request.POST.get('delivery_type') response_data['book_price'] = book_price response_data['delivery_charge'] = delivery_charge response_data['delivery_type'] = delivery_type book.objects.create(book_price=book_price, delivery_charge=delivery_charge,delivery_type=delivery_type) return JsonResponse(response_data) if form.is_valid(): instance = form.save(commit=False) instance.user = … -
Django use old database backup
I have 2 servers: production (master branch) and test (dev branch). On my local machine I work on dev branch, it has all the latest features and the newest DB schema. Now I need to inspect some problems that occurred on the production server. For that I want to download DB backup from production server onto my local machine and do some manipulations with it. On my local machine I have a postgres running and that is where my local DB is stored. What I usually do is drop local DB, apply the backup instead of what I've deleted and that works fine. I am able to work with the database. However, if the production database is several migrations behind the local database (which happens often) than I get Django migration errors when I try to apply all the latest migrations. The errors are usually like some_relation / some_column already exists. Probably, that happens because Django tries to apply all migrations starting at the very first one. To work this around I usually run all migrations with --fake option, than make small changes in models (like blank=True), just enough to create new migration which I apply then. After that I … -
Can I convert html in dict?
How can I paste/convert code html. I get code from file .txt and function like {for} etc. it's paste as text. respone = { "Pic" : str(File_read_to_div.readline()), "h1" : str(File_read_to_div.readline()), "WpisChild" : File_read_to_div.readline(), "Messags" : list(Messages) } return JsonResponse(respone, safe=False) And now in site I see {for} as text in div. Objects are not displayed. -
Django template data update using ajax
I am trying to update my data periodically (10 seconds) on a Django template using ajax scripts. I am relatively new in developing the front end. Using other articles, I am able to do so. But everytime page refreshes, multiple threads for page refreshing are created and update requests are doubled every 10 secods. Following is my django template snippet: <body id="page-top"> <div class="table-responsive"> <table class="table table-striped"> <thead> <tr class="table-info"> <th style="text-align:center">Parameter</th> <th style="text-align:center">A</th> <th style="text-align:center">B</th> </tr> </thead> <tbody> {% for para, details in manualData.items %} <tr> <th style="text-align:center" scope="row">{{ details.1.name }}</th> {% for key, entity in details.items %} <td style="text-align:center"> <font color="white" size="4px">{{ entity.value }}</font> </td> {% endfor %} </tr> {% endfor %} </tbody> </table> </div> </body> I am using ajax script as follows: <script type="text/javascript"> function refresh() { var_ref = $.ajax({ success: function (data) { $('#page-top').html(data); } }); } $(function () { setInterval('refresh()', 10000); }); </script> Conclusively, all I need is to once the refreshing process is defined, new process should not be created or else past process to be aborted if new process is to be defined. Kindly help me to attain the same. Thanks in advance Nakul -
Django: How to load dynamic data to chartjs
I want to load my models' data into a chart, using chartjs. Curiously, only the 'dummy-data' is working, that looks as follow: data: { labels: ['red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'], datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 2, 7], My raw data looks like this: labels = ['/truck-alerts-analysis/fleet-history', '/truck-alerts-analysis/map-view', '/truck-alerts-analysis/fleet-status', '/truck-alerts-analy sis/truck-history', '/truck-alerts-analysis/truck-history', '/truck-alerts- analysis/fleet-status', '/truck-alerts-analysis/truck-histor y', '/setup/QCFcKp', '/reset-password', '/login'] data = [251, 243, 238, 220, 174, 158, 151, 88, 87, 86] Using django, I defined these values in views.py as follow: def pages(request): showData = start_date pageV = PageView.objects.all() FPage = FinalPage.objects.all() typeUser = list(FinalPage.objects.values_list('page', flat=True)) count = list(FinalPage.objects.values_list('sessionCount', flat=True)) # manipulation in order to get the right labels that I want t=[] for i in typeUser: new = i.split("?", 1)[0] t.append(new) k = t[-10:] c = count[-10:] # Where the labels and data is being returned return render(request, 'gaapp/pages.html', {"showData": showData, "labels": k, "data": c}) The curious behaviour is that, when calling for {{labels}} and {{data}} in the HTML file (where the chart is being processed), only the {{data}} is being excepted? In other words, the {{labels}} aren't valid. I don't understand why? Please help My HTML: <div class="PageMines"> <canvas id="myChart1" width="40" height="30"></canvas> … -
Why my modal in django not show me autocomplete values?
I have a data table in which in the last column there is the button"edit" that give me the possibility to modify the value of each row data with a ajax query. All works fine, but I want that when I click on the button "edit" the modal pop-up is autofilled with row value, that after I can manually modify. I attached below the part of the code that I think does not work: <tr id="element-{{element.id}}"> <td class="elementcodice userData" name="codice">{{element.codice}}</td> <td class="elementtipologia userData" name="tipologia">{{element.tipologia}}</td> <td class="elementsottocategoria userData" name="sottocategoria">{{element.sottocategoria}}</td> <td align="center"> <button class="btn btn-success form-control" onClick="editUser({{element.id}})" data-toggle="modal" data-target="#myModal"> Modifica</button> </td> </tr> and jquery code: function editUser(id) { if (id) { tr_id = "#element-" + id; codice = $(tr_id).find(".elementcodice").text(); tipologia = $(tr_id).find(".elementtipologia").text(); sottocategoria = $(tr_id).find(".elementsottocategoria").text(); $('#form-id').val(id); $('#form-codice').val(codice); $('#form-tipologia').val(tipologia); $('#form-sottocateogira').val(sottocategoria); } } Where is the problem? -
Can I use django conditionals inside css?
I have a static css file in my django app static directory. I have multiple views running of the same css file, since otherwise there would be A LOT of copy and pasting, but I need just a few things to be different depending on the page I'm currently on. Is it possible to use the django conditional statements like {% if request.path == ... so on inside the static css file? Or if not what would be a sensible alternative that would achieve the same result? Because the class header.masthead is used about 10 times in the CSS file and if I had to write a new, let's say, header.mastheadcookiepage and assign the same functionality, and do this for multiple new pages, that would be really annoying. Perhaps this is a stupid question and I'm approaching this problem the wrong way, but I'm quite new to web developement, so any help is appreciated! -
Unable to receive mail but submit successfully: Contact Form Django
I was trying to make contact form for my website, its loading, working and submitting successfully but i'm not receiving any mail from my website. I also created a form like that for reset password its working but not this why? my html <div class="blog_list"> <form method="POST"> {% csrf_token %} <h2 class="blog_heading">Contact Us</h2> <fieldset class="form-group"> {{ form|crispy}} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Submit</button> </div> </form> my views.py def contact(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] messages.success(request,f'Message sent successfully!') return redirect('Love Travel-home') try: send_mail(subject, message, from_email, ['admin@example.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return render(request, "shop/contact.html", {'form': form}) my forms.py class ContactForm(forms.Form): from_email = forms.EmailField(required=True) subject = forms.CharField(required=True) message = forms.CharField(widget=forms.Textarea, required=True) settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS =True EMAIL_HOST_USER = os.environ.get('django_user') EMAIL_HOST_PASSWORD = os.environ.get('django_pass') I made contact form it submits it successfully but i didn't receive mail, can anyone please help me? -
Pagination issue in Django
I have a database in my Django project on which I am making queries. I would like to display the responses in different pages. If the request is "none", the pagination works flawlessly. But whenever I pass a query, first page displays the responses I am looking for but next pages are behaving like request were "none". Here is my views.py def search(request): query = request.GET.get('query') if not query: products_list= Product.objects.all() else: products_list = Product.objects.filter(name__icontains=query) if not products_list.exists(): products_list = Product.objects.filter(brand__icontains=query) title = "Results: %s" % query paginator = Paginator(products_list, 9) page = request.GET.get('page',1) try: products = paginator.page(page) except PageNotAnInteger: products = paginator.page(1) except EmptyPage: products = paginator.page(paginator.num_pages) context = { 'products': products, 'title': title, 'paginate': True, } return render(request, 'finder/search.html', context) And the html: <nav aria-label=""> <ul class="pager"> {% if products.has_previous %} <li><a href="?page={{ products.previous_page_number }}">Previous</a></li> {% endif %} {% if products.has_next %} <li><a href="?page={{ products.next_page_number }}">Next</a></li> {% endif %} </ul> </nav> -
Python About using regular expression in pandas for integer search
I used django for a search feature improvement,Enter the character you want to search in the screen that the user enters, convert it to an integer to match the specified field, file and convert it to dataframe, so it has been done so far new_fmt = int(new_fmt) some1 = df[(df[19].str[:8] == new_fmt )] user input is new_fmt, but user need to input the exact corresponding input, so what I want to ask is like, when user input 26660000, The code separates The first four inputs and assigns The last four to [0-9] [0-9] [0-9] [0-9], after using regular expression input to four matches, such as user input: 26660000, The matches of 26660000-26669999 are displayed in dataframe,Instead of just matching the output 26660000 . When I looked up other materials, I learned that re can only be used for str, while the table I imported in pd is int, so this bothers me a lot. I hope to get a solution, thank you -
Django - Vue.js cascading dropdown
I’m trying to make a cascading dropdown. I’m using Vuejs, Django and django Rest Framework. I tried with this example : https://jsfiddle.net/mani04/Lgxrcc5p/ but I don’t understand how to implements the « places » (in example attached) with my own objects from API. To understand you can fin below : Model.py class Affaires(models.Model): id = models.PositiveSmallIntegerField(primary_key=True) nom = models.CharField(max_length=50) class Meta: managed = True db_table = 'affaires' def __str__(self): return '{} - {}'.format(self.id, self.nom) class AffairesOfs(models.Model): idaffaire = models.ForeignKey(Affaires, models.DO_NOTHING, db_column='idAffaire') # Field name made lowercase. nom = models.CharField(max_length=50) class Meta: managed = False db_table = 'affaires_ofs' def __str__(self): return '{}'.format(self.id) This is my HTML & scripts : <div id="starting"> <div class="container"> <div class="row"> <form class="form-group"> <label>N° d'affaire</label> <select class="col"> <option value="choisir">Choisir :</option> <option v-for="affaire in affaires" value="${affaire.id}">${affaire.id} - ${affaire.nom}</option> </select> <label>N° d'OF</label> <select class="col"> <option value="choisir">Choisir :</option> <option v-for="of in ofs" value="${of.id}">${of.id} - ${of.nom}</option> </select> <input type="submit" value="Valider" class="btn btn-success" /> </form> </div> </div> <div class="loading" v-if="loading===true">Loading&#8230;/div> </div> <script type="text/javascript"> new Vue({ el: '#starting', delimiters: ['${','}'], data: { ncs: [], affaires: [], ofs: [], loading: false, currentNc: {}, message:null, newNc: {'idof': null, 'idrepere': null }, }, mounted: function() { this.getNcs(); this.getAffaires(); this.getOfs(); }, methods: { getNcs: function() { this.loading = … -
Make django handle subdomain suffix
We're hosting several dockerized web-apps on our webserver, let's call it group.example.com. Our subdomains are handled via nginx as suffixes though, which translates to something like group.example.com/app1/ group.example.com/app2/ as root urls. When using Django, we run into problems though, as all its urls generated by url in the templates such as <a href="{% url 'index' %}">home</a> will be relative links, so rendered to <a href="/">home</a>. This relative link will not be interpreted correctly, leading to the main, non-app page group.example.com. So the goal is to have an app based prefix such as /app1/ for all links. I can hardcode these for static links, but there has to be a more elegant way. Also this leads to problem for the used forms submitting to the wrong page - redirecting again back to the main, non-app page group.example.com. I tried adding /app1/ to all registered urls as prefix, but that doesn't seem to work either - that way the app is running but user would need to visit group.example.com/app1/app1/ to get to the index, and the relative links still don't work correctly. In the app docker-container we're running the web-app with nginx and uwsgi. It works fine when using correct subdomains such … -
Trying to understand django url namespacing
I was going through the Django docs, here they're talking about removing hardcoding in urls so that its easier to modify urls in the future. This is how a hardcoded url looks like <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li> After removal of hardcoded string <li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li> This is all well and done. What's confusing me is the namespacing part from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('', views.index, name='index'), path('<int:question_id>/', views.detail, name='detail'), path('<int:question_id>/results/', views.results, name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ] Here the app_name variable is introduced to store the app name, polls in this case. But in the view they have gone and specified <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li> Isn't this the same as before? I mean the hardcoded URL issue is right there... What is the design pattern behind this. Why can't they just look at the app folder and get the app name from there? -
How do I access separate Django-entangled JSONField items in a form with jinja?
does someone have an idea how I get individual entangled_field items into my form? Here's my code, I'll explain further down (in form.html) where I'm having issues. models.py class Project(Model): """Project Data""" eeg = JSONField() meg = JSONField() forms.py class ProjectForm(EntangledModelForm): """HTML form for Project objects https://github.com/jrief/django-entangled""" nosessions = IntegerField(required=False) sessionduration = IntegerField(required=False) hoursrequired = IntegerField(required=False) esthourspermonth = IntegerField(required=False) class Meta: model = Project entangled_fields = { "eeg": [ "nosessions", "sessionduration", "hoursrequired", "esthourspermonth", ], "meg": [ "nosessions", "sessionduration", "hoursrequired", "esthourspermonth", ], } untangled_fields = [..working fields..] Django object proj112 = Project.objects.get(name='112_test') for k,v in proj112.eeg.items(): print(k,v) nosessions 5 hoursrequired 10 sessionduration 2 esthourspermonth 10 for k,v in proj112.meg.items(): print(k,v) nosessions 10 hoursrequired 20 sessionduration 2 esthourspermonth 20 detail.html - I can successfully access/list the keys and values for both 'eeg' and 'meg' once they are created (manually via the api or database). <table> <b>EEG</b> {% for key,value in project.eeg.items %} <tr> <td>{{key}}</td><td>{{value}}</td> </tr> {% endfor %} </table> <table> <b>MEG</b> {% for key,value in project.meg.items %} <tr> <td>{{key}}</td><td>{{value}}</td> </tr> {% endfor %} </table> form.html - This displays the field correctly but inserts data to both 'eeg' and 'meg'. {{ form.nosessions|as_crispy_field }} I want to reference them separately as I have a … -
I am facing a problem while trying to deploy python django app to heroku
-----> Python app detected cp: cannot stat '/tmp/build_f87e66a969d68e5390ddccb6b44523c7/requirements.txt': No such file or directory it constantly gives me this error and the app wont run its getting frustrated now can anyone help?? -
Django taggit with Count: the example from book
I am trying to understand the example from book "Django by Example". There is a blog application with tags. models.py class Post(models.Model): # ... tags = TaggableManager() views.py def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) # List of similar posts post_tags_ids = post.tags.values_list('id', flat=True) similar_posts = Post.published.filter(tags__in=post_tags_ids)\ .exclude(id=post.id) similar_posts = similar_posts.annotate(same_tags=Count('tags'))\ .order_by('-same_tags','-publish')[:4] return render(request, 'blog/post_detail.html', {'post': post, 'similar_posts': similar_posts}) From my point of view, annotate(same_tags=Count('tags')) will count all tags in each post in similar_post Queryset. Why does it pick and sum only the same tags as in my post? Thanks in advance -
How to groupby nested object elements In Django Rest FrameWork
How to use group-by for nested objects class RequirementInfo(models.Model): name = models.ForeignKey(PostJobRequirement, on_delete=models.CASCADE) class CandidataInfo(models.Model): name = models.ForeignKey(CandidateList, on_delete=models.CASCADE) rate = models.FloatField(null=True, blank=True) class SubmittedCandidateInfo(models.Model): requirement = models.ArrayField(model_container=RequirementInfo) candidate = models.ArrayField(model_container=CandidataInfo) def __str__(self): return str(self.requirement[0]) class SubmittedCandidate(CreateModificationDateMixin): submitted_candidate_id = models.IntegerField(default=sub_id, editable=False, primary_key=True) submit_candidate = models.ArrayField(model_container=SubmittedCandidateInfo) def __str__(self): return str(self.submitted_candidate_id) class Meta: verbose_name_plural = "submitted_candidates" db_table = "submitted_candidate" Serializer: class RequirementInfoSerializer(DjongoModelSerializer): class Meta: model = RequirementInfo exclude = ('id', ) depth = 1 class CandidataInfoSerializer(DjongoModelSerializer): class Meta: model = CandidataInfo exclude = ('id', ) depth = 1 class SubmittedCandidateInfoSerializer(DjongoModelSerializer): requirement = RequirementInfoSerializer(many=True, required=False) candidate = CandidataInfoSerializer(many=True, required=False) class Meta: model = SubmittedCandidateInfo fields = ('requirement','candidate') For Submitting candidates Here am generating number of records based on requirment*candidate computation class SubmittedCandidateSerializer(DjongoModelSerializer): class Meta: model = SubmittedCandidate fields = ('submitted_candidate_id','submit_candidate') def create(self, validated_data): submit_candidate = validated_data['submit_candidate'][0] submit_candidate_copy = submit_candidate['candidate'].copy() for _item in submit_candidate['requirement']: for index, _val in enumerate(submit_candidate_copy): validated_data['submit_candidate'][0]['requirement'] = [dict(_item)] validated_data['submit_candidate'][0]['candidate'] = [dict(_val)] message_obj = super().create(validated_data) return message_obj For viewing submitted candidates class ViewSubmittedCandidateSerializer(DjongoModelSerializer): submit_candidate = SubmittedCandidateInfoSerializer(many=True, required=False) class Meta: model = SubmittedCandidate fields = ('submitted_candidate_id','submit_candidate', 'interview_status', 'modification') Views: class SubmittedCandidateViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) queryset = SubmittedCandidate.objects.all() serializer_class = SubmittedCandidateSerializer class ViewSubmittedCandidateViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) queryset = SubmittedCandidate.objects.all() serializer_class = ViewSubmittedCandidateSerializer My … -
How to fix Page not found (404) error django2.0 for profile pages
How to fix Page not found (404) error django2.0 for profile pages this code views code ''' def profile(request, slug): profile = Profile.objects.get(slug=slug) context = { 'profile':profile, } return render(request, 'registration/profile.html' ,context) ''' and this urls.py ''' from django.urls import path,re_path from . import views from django.contrib.auth.views import LoginView,logout #login app_name='accounts' urlpatterns = [ path(r'', views.home, name ='home'), # path(r'^login/$', login, {'template_name':'registration/login.html'}), path('login/', LoginView.as_view(), name="login"), path(r'^logout/$', logout, name='logout'), # path(r'^signup/$', views.register, name='register'), path('signup/', views.register, name='signup'), path(r'^(?P<slug>[-\w]+)/$', views.profile, name='profile'), # path(r'^(?P<slug>[-\w]+)/edit$', views.edit_profile, name='edit_profile'), ] ''' profile.html page in templates /registration folder -
I do exactly as the tutorial says and my code has no syntax errors - but things still don't work
I do exactly as the tutorial says and my code has no syntax errors - but things still don't work. I need to verify a few things, can someone help with me in a chat please? It shouldn't take more than 5 minutes I'm sure. Would highly appreciate it, thanks! -
(1048, "Column 'cnic' cannot be null" , duplicate entry error, etc value cannot be saved in database through add_ser_save function
here is add_user_save function in managerviews.py def add_user_save(request): if request.method!="POST": return HttpResponse("Method Not Allowed") else: first_name=request.POST.get("first_name") last_name=request.POST.get("last_name") username=request.POST.get("username") email=request.POST.get("email") password=request.POST.get("password") cnic=request.POST.get("cnic") contact_number=request.POST.get("contact_number") gender=request.POST.get("gender") #try: user=CustomUser.objects.create_user(username=username,password=password,email=email,last_name=last_name,first_name=first_name, user_type=3) user.passenger.cnic=cnic user.passenger.first_name=first_name user.passenger.last_name=last_name user.passenger.email=email user.passenger.contact_number=contact_number user.passenger.gender=gender user.passenger.save() user.save() #messages.success(request,"Successfully Added User") #return HttpResponseRedirect(reverse("add_user")) #except: #messages.error(request,"Failed to Add User") #return HttpResponseRedirect(reverse("add_user")) here is my models.py passsenger table class Passenger(models.Model): cnic=models.BigIntegerField(primary_key=True) admin=models.OneToOneField(CustomUser,on_delete=models.CASCADE, blank=False, null=True) manager_id=models.ForeignKey(Manager,on_delete=models.CASCADE, blank=True, null=True) staff_id=models.ForeignKey(Staff,on_delete=models.CASCADE, blank=True, null=True) fisrt_name=models.CharField(max_length=255, default='non') last_name=models.CharField(max_length=255, default='non') email=models.CharField(max_length=255, default='non') contact_number=models.IntegerField( null=True) gender=models.CharField(max_length=255, default='non') created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now_add=True) def __str__(self): return self.cnic do i have to change in the below function? I dont know what to add here (usertype =3 is passenger user) @receiver(post_save,sender=CustomUser) def create_user_profile(sender,instance,created,**kwargs): if created: if instance.user_type==1: Manager.objects.create(admin=instance) if instance.user_type==2: Staff.objects.create(admin=instance) if instance.user_type==3: Passenger.objects.create(admin=instance) Problem is value is not added in database i trued a lot by adding blank=true, null=true but error changes every time. Sometimes comes on duplicate key on admin and sometimes like cnic cannot be null all that. Is there any issue in models.py? Help kindly so that i can save data from front end template to passenger table. -
Django is-instance is not working properly For UUID [closed]
I have UUID4 value= "2626df07-1854-4ff1-9296-fa43bc896950" for this value am trying import uuid print((isinstance(value, uuid.UUID))) Result is:- False can anyone please explain me the reason behind this. Note:-value is a proper UUId4