Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Signal to add ManyToMany Field objects onto a signal-created model instance
CONCEPT: I am trying to create a goals-type app that will work as follows: The user creates a goal week (prompted to multi-select from list of pre-established goals) and hits 'Create goal week'. When the goal week is created by the user, a django signal auto-generates model instances for the following models: GoalDayOne, GoalDayTwo, GoalDayThree, GoalDayFour, GoalDayFive and each of these instances have a OneToOne association with the GoalWeek, like your typical User/Profile signal relationship. I have this part working. Now here is the tricky part: When the user establishes a GoalWeek instance --and the signal creates the GoalDayOne, GoalDayTwo...etc-- instances with it, I want to pass those pre-chosen goals to each day as well. I know handling items from the M2M field in a signal is not easy but there has to be a way to do it, correct? I have tried switching from a signals.py file to handling it all on models.py with no luck. I also fiddled around with the m2m_changed signal instead with no luck. I am assuming I can prob do this on the traditional post_save signal but I have to establish the GoalItems as an independent list first and then add them to the … -
Trigger action from button in odoo qweb
I'm trying to run a view from stock.picking view and it's ok when I call it using menuitem, but when i'm trying to replace menuitem by button, it's not triggered. In my .xml <menuitem name="My Element" id="menu_elem" action="my_action_name"/> this was working well. But that one is wrong. For example,I don't want to call the myMethod from my model,but it's required to have name="". So when I click on my button, it calls the method and I hadn't my action triggered like in menuitem <record id="myId1" model="ir.ui.view"> <field name="name">stock.picking.form.inherit</field> <field name="model">stock.picking</field> <field name="inherit_id" ref="stock.view_picking_form"/> <field name="arch" type="xml"> <field name="state" position="before"> <button name="myMethod" string="My Element" action="my_action_name" type="object" class="oe_highlight"/> </field> </field> </record> So is there a way to have only triggered action without the use of model method, like in menuitem? -
How to specify timeout for a query using Django
We have a session timeout for all queries using this: 'default': { 'ENGINE': 'django.db.backends.postgresql', ... 'OPTIONS': { 'options': '-c statement_timeout=5000', ... } } } However there is a query that takes much longer to run. I want to override the 5 second constraint for this specific query. How would I do this? We have a Postgres DB. Thanks! -
ModuleNotFoundError in django when including urls.py
I am trying to implement a simple chat API using django/drf, but when I tried adding my chat_app.urls to src.urls its throwing an error stating chat_app.serilizers.py module not found. here is my serializers.py file - from rest_framework import serializer from chat_app.models import ChatGroup class ChatGroupSerializer(serializers.ModelSerializer): class Meta: model = ChatGroup fields = '__all__' here is my view - from django.shortcuts import render from rest_framework import permissions from rest_framework.generics import (ListCreateAPIView, RetrieveUpdateDestroyAPIView) from chat_app.models import ChatGroup from chat_app.serializers.py import ChatGroupSerializer class ChatGroupListCreateView(ListCreateAPIView): permission_classes = [permissions.IsAuthenticated] serilizer_class = ChatGroupSerilizer queryset = ChatGroup.objects.all() class ChatGroupRetriveUpdateDestroyView(RetrieveUpdateDestroyAPIView): permission_classes = [permissions.IsAuthenticated] serilizer_class = ChatGroupSerilizer queryset = ChatGroup.objects.all() here is my chat_app.urls.py from django.urls import path from chat_app.views import ChatGroupListCreateView urlpatterns = [ path("", ChatGroupListCreateView.as_view(), name='chat-list-create-api') ] here is src.urls.py - urlpatterns = [ path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls')), path('chat/', include('chat_app.urls')) ] this is the error Django is throwing -> traceback -
Django - Class based view - Meta tags from model don't get passed to template
I am having an issue with my meta tags not being passed to my category.html template. Here is my models.py class Category(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(max_length=255) image = models.ImageField(null=True, blank=True, upload_to='images/') meta_title = models.CharField(max_length=255) meta_keywords = models.CharField(max_length=255) meta_description = models.CharField(max_length=255) def __str__(self): return self.name Here is my views.py class CategoryView(ListView): model = Post template_name = 'category.html' def get_queryset(self): self.category = get_object_or_404(Category, slug=self.kwargs['slug']) return Post.objects.filter(category=self.category) # def get_context_data(self, **kwargs): # context = super(CategoryView, self).get_context_data(**kwargs) # context['category'] = self.category # return context def get_context_data(self, *args, **kwargs): category_menu = Category.objects.values_list('slug', flat=True) context = super(CategoryView, self).get_context_data(*args, **kwargs) context['category_menu'] = category_menu return context The commented-out code works, however, I need the second one so that I can also display categories (name from Category model) on that page. Here is my url.py urlpatterns = [ path('', HomeView.as_view(), name="home"), path('article/<slug:slug>', ArticleDetailView.as_view(), name="article-detail"), path('category/<slug:slug>', CategoryView.as_view(), name="categories"), and finally here is my category.html {% extends 'base.html' %} {% block title %} {{ category.meta_title }} {% endblock %} {% block meta_extend %} <meta name="description" content="{{ category.meta_description }}"> <meta name="keywords" content="{{ category.meta_keywords }}"> <meta property="og:description" content="{{ category.meta_description }}"> {% endblock %} {% block content %} -
Bulk Lock Objects in Django
I have concurrent workers that bulk update objects in my Django application, and I'm running into deadlocks. I've tried to make the transaction atomic with the following code: with transaction.atomic(): users = User.objects.select_for_update().filter(id__in=list(list_of_users_to_update.keys())) for user in users: user.checked_date = list_of_users_to_update[user.id]["checked_date"] user.changed_date = list_of_users_to_update[user.id]["changed_date"] user.save() My deadlock is getting thrown on the line for user in users: How can I acquire a lock on the rows prior to initiating the transaction to avoid deadlocks? -
Url getting duplicated in django: sign/sign/
The sign/ url is getting duplicated on itself, as shown in the below image. How can I stop this url duplication? It was working fine before taking input from the user. When the user clicks on the submit button it duplicated itself in the url. This is View.py from django.http import HttpResponse # Create your views here. def Home(response): return render(response, "main/index.html",{}) def sign_up_in(reponse): if reponse.method == 'POST': email = reponse.POST.get('eemail') print(email) return render(reponse, "main/sign_up_in.html",{}) This is urls.py from . import views urlpatterns = [ path("", views.Home, name = "Homes"), path("sign/", views.sign_up_in, name = "sign_up_in") ] This is urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include("main.urls")), path('sign/', include("main.urls")), ] This is my sign_up_in.html code <form method="POST" class="form" id="a-form" action="{% url 'sign_up_in' %}"> {% csrf_token %} <h2 class="form_title title">Create Account</h2> <div class="form__icons"><img class="form__icon" src="svg_data" alt=""><img class="form__icon" src="svg_data"><img class="form__icon" src="svg_data"></div><span class="form__span">or use email for registration</span> <input class="form__input" type="text" placeholder="Name" name="eemail"> <input class="form__input" type="text" placeholder="Email"> <input class="form__input" type="password" placeholder="Password"> <button class="button" type="submit">SIGN UP</button> </form> <form method="POST" class="form" id="b-form" action=""> {% csrf_token %} <h2 class="form_title title">Sign in to Website</h2> <div class="form__icons"><img class="form__icon" src="svg_data" alt=""><img class="form__icon" src="svg_data"><img class="form__icon" src="svg_data"form__span">or use your email account</span> <input class="form__input" type="text" … -
How to get data between date range in django rest_framework?
I want to fetch some data between two dates, but got an error that is "AttributeError: 'str' object has no attribute 'values'". How I solve this issue? views.py class TestView(APIView): def get(self, request): user_obj = Payload.objects.all() usr = self.request.user print(usr) user_data = TestSerializer(user_obj, many=True) return Response({'status':'success'}) def post(self, request): serializers = TestSerializer(data=request.data) if serializers.is_valid(raise_exception=True): start_date = serializers.validated_data['start_date'] end_date = serializers.validated_data['end_date'] user_id = serializers.validated_data['user_id'] user_obj = Payload.objects.filter(user=user_id, timestamp__gte=start_date,timestamp__lte=end_date) sr = TestModelSerializer(user_obj, many=True) return Response({'status':sr.data}, status = status.HTTP_200_OK) else: print(serializers.errors,"errors") serializers.py class TestSerializer(serializers.Serializer): user_id = serializers.IntegerField() start_date = serializers.DateTimeField() end_date = serializers.DateTimeField() class TestModelSerializer(serializers.ModelSerializer): model = Payload fields = '__all__' models.py class Payload(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True, blank=False) input_values = models.CharField(max_length=20) def __str__(self): return self.input_values -
Logging the output of a management command run by a cron job
I have a cron job scheduled that runs a custom management command in Django. I would like to output all information on a success as well as a fail. How would I structure this? CRONJOBS = [ ('* * * * *', 'django.core.management.call_command', ['my_custom_command']) ] I've tried setting up a relative path in settings like this log_file_path = os.path.join(BASE_DIR, "log_files/cronjob.log") and then added '>> log_file_path' next to 'call_command' as well as 'my_custom_command' but neither work. I could also be structuring my relative path incorrectly. -
Django & Ajax : data get lost between the view and the template
Using Ajax and Django, my data get lost when sent back to my template and I can't retrieve them. Here is my code and the logic : Following the dependent dropdown lists tutorial offered by ["Simple is Better Than Complex"][1] I have implemented an Ajax request. Here is the html code: <p class="multiple-choice" id="mandate-city" data-url="{% url 'officials:ajax_load_mandate_city' %}">Local Mandate: {{ form.mandate_city }}</p> The ajax request is fired from this script: <script> $("#id_departments").change(function (){ var url = $("#mandate-city").attr("data-url"); var departmentId = $(this).val(); $.ajax({ url: url, data: { 'department': departmentId }, success: function (data){ $("#id_mandate_city").html(data); console.log(data); } }); }); </script> After check with console.log, the data are collected by the script. Then, they reach the view. Here is my view: def load_mandate_city(request): department_id = request.GET.get('department') mandate_city = MandateCity.objects.filter(department_id=department_id).order_by("department") return render(request, "officials/mandate_city_list.html", {mandate_city: mandate_city}) With a print, I have checked, and the data are treated as planned. Then the data are sent back through the url: path('ajax/load_mandate_city/', views.load_mandate_city, name="ajax_load_mandate_city") They seem not to reach the template: {% for mandate in mandate_city %} <option value="{{ mandate.pk}}">{{ mandate.get_mandate_display }}</option> {% endfor %} And I could not track them in my script. :-/ Can somebody let me know where the bug is ? Thanks. [1]: https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html -
Django, i would like to sent data from drop down menu to database when once the hit submit button but error occure
I am trying to send data to the database from the dropdown menu from index.html that is why I have created models.py as the initial class named as Program and later on used it to Contact class using ForeignKey. registered Contact at admin.py and later on i have used class name programs to in index.html and it is rendering the name of the programs which is entered by me at admin panel of django. but the issue is {{program2}} does display at the index page but when user go the form and selects and submits this program2 data is not going to the database. How could i use the dropdown to sent value to the database. Help appreciated, accepting to resolve it from my way. models.py class Program(models.Model): program1 = models.CharField(max_length=50, default='') class Contact(models.Model): name = models.CharField(max_length=50, primary_key=True) contact = models.CharField(max_length=50, default='') address = models.TextField(max_length=1000, default='') program2 = models.ForeignKey(Program, on_delete=models.CASCADE, null=True, blank=True) # program = models.CharField(max_length=50, default='') # bba = models.CharField(max_length=50, default="") # bhm = models.CharField(max_length=50, default="") email = models.CharField(max_length=50, default="") w3review = models.TextField(max_length=1000, default="") def __str__(self): return self.name views.py def index(request): if request.method == 'POST': name = request.POST.get('name', '') contact = request.POST.get('contact', '') address = request.POST.get('address', '') program2 = … -
pinax django URL -- The current path, account/signup/, didn’t match any of these Error
im new to django and python and i'm trying to implement pinax/django-user-account to my project. I followed all the instructions on pinax-documents and i suppose i controleld all the dynamics from original django documentation. But still i cant reach the sign-up and login pages using href link. Also i cant reach those pages via http://127.0.0.1:8000/account/signup/... im getting the error below: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/account/signup/ Using the URLconf defined in zetamedweb.urls, Django tried these URL patterns, in this order: i think i'm missing something really basic but what am i missing? main.url from django.contrib import admin from django.urls import path from django.conf.urls import url,include from zetamedweb import views from django.conf.urls.static import static app_name = 'Index' urlpatterns = [ url(r"^$", views.IndexView.as_view(),name='ındex'), url('admin/', admin.site.urls), url(r"^ Treatments/", include('Treatments.urls')), url(r"^ AboutUs /", include('About_Us.urls')), url(r"^ Contact /", include('Contact.urls')), url(r"^ Travel_Tips /", include('Travel_Tips.urls')), url(r"^ Destinations/", include('Destinations.urls')), url(r"^ FAQ/", include('FAQ.urls')), url(r"^ TailorMade/", include('TailorMade.urls')), url(r"^ APP/",include('APP.urls')), url(r"^account/", include("account.urls")), ] app.urls(pip installed, i only added app_name) from django.urls import path from account.views import ( ChangePasswordView, ConfirmEmailView, DeleteView, LoginView, LogoutView, PasswordResetTokenView, PasswordResetView, SettingsView, SignupView, ) app_name = 'Account' urlpatterns = [ path("signup/$", SignupView.as_view(), name="account_signup"), path("login/$", LoginView.as_view(), name="account_login"), path("logout/$", LogoutView.as_view(), name="account_logout"), path("confirm_email/<str:key>/$", ConfirmEmailView.as_view(), name="account_confirm_email"), path("password/$", ChangePasswordView.as_view(), … -
How to save a form which contains a container div with sub-divs that have been dynamically added in django
I am working on a job portal system. I provide users the change to edit their profiles by adding and removing job experience. The issue is I don't know how to send that data to the view so that it can retrieve all the fields and store them in the database accordingly. By retrieving, I mean for each job experience, retrieve their corresponding sub fields Here is my template file: <!--JOB EXPERIENCE--> <div class="job_experience"> <h5>Experience</h5> <hr> <!--FORM--> <form action="#" id="save_job_experience_form" method="POST"> {% csrf_token %} <div class="job_container"> {% for job in job_experience %} <div class="exp"> <label>Organisation</label> <input type="text" class="form-control" name="organisation placeholder="Organisation" value="{% if job.organisation %} {{job.organisation}}{% endif %}" required> <label>Job Title</label> <input type="text" name="job_title" class="form-control" value="{% if job.job_title %}{{ job.job_title }}{% endif %}" placeholder="Job Title e.g Backend Developer" required> <button style="margin-left:15px;" type="button" class="btn btn-danger remove_job_exp"><strong>Delete Job Experience</strong></button> </div> <hr> {% endfor %} </div> <!--BUTTONS--> <input type="submit"value="Save"> <input type="button" id="add_job_experience"value="Add one"> </form> </div> <script> $(document).on('click', '#add_job_experience',function(e){ e.preventDefault(); $(".job_container").append(`<div class="exp"> <!--IT GOES ON AS ABOVE --> $(document).on('click', 'button.remove_job_exp', function(e){ e.preventDefault(); $(this).closest('div.exp').remove(); }); models.py class StudentWorkExperience(models.Model): student = models.ForeignKey(StudentUser, on_delete=models.CASCADE) organisation = models.CharField(max_length=100) job_title = models.CharField(max_length=50) job_desc = models.TextField(null=True, blank=True) country = models.CharField(max_length=254) city = models.CharField(max_length=100) state = models.CharField(max_length=200) start_month = models.CharField(max_length=10, null=True, blank=True) … -
Django form errors are not showing in template
no form errors are showing up in my HTML template when the form is invalid. The form is placed within a carousel incase that's relevant. I'm calling out individual form elements instead of rendering as {{form.as_p}}, errors where showing when this was the case. The last item in the carousel is the password and if I leave this blank it will show a pop out that says "please fill in this field" but nothing more than that and only for that one field. Views.py def collapsecard(request): if request.method == 'POST': create_user_form = CreateUserForm(request.POST) safezone_form = SafezoneForm(request.POST) if create_user_form.is_valid() and safezone_form.is_valid(): user = create_user_form.save() safezone = safezone_form.save(commit=False) safezone.userid = user safezone.useremail = user.email safezone.save() user = authenticate(username=create_user_form.cleaned_data['username'], password=create_user_form.cleaned_data['password1'], ) login(request,user) api_key = 'XYZ' api_secret = 'XYZ' id = 'XYZ' mailjet = Client(auth=(api_key, api_secret)) data = { 'Email': safezone.useremail, 'Action': "addnoforce" } result = mailjet.contactslist_managecontact.create(id=id, data=data) print result.status_code print result.json() return redirect('safezoneaddedpage') return redirect('safezoneaddedpage') else: create_user_form = CreateUserForm() safezone_form = SafezoneForm() print(create_user_form.errors) print(safezone_form.errors) return render(request, 'V2maparonno_create_safe_zoneV2.html', {'create_user_form': create_user_form, 'safezone_form': safezone_form}) Extract from HTML <form action="" method="POST" class="form-control"> {% csrf_token %} <div id="carouselExampleIndicators" class="carousel slide" data-interval="false" style="width: 100%"> <ol class="carousel-indicators"> <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li> <li data-target="#carouselExampleIndicators" data-slide-to="1"></li> <li data-target="#carouselExampleIndicators" data-slide-to="2"></li> <li data-target="#carouselExampleIndicators" data-slide-to="3"></li> … -
Django channels Add users to group
I'm using django channels I'm making a Facebook clone and trying to add real time notifications using channel, so I've this idea when a notification happens i create a group and add the users the one who sent it and the one who received it and after receiving it, then the group gets discarded, can this be accomplished? -
Django All-auth, disable automatic login with google
I've got a similar problem to this question but I don't have enough reputation to comment on the original post. Django all-auth: How to disable automatic login via Google I'd like the user to choose a specific google account (because I'm filtering by a company email), the automatic login doesn't allow the user to change accounts when signing up and instead brings them to the "sign up is closed" page. Very new to Allauth and Oath so any help would be appreciated. I'm overriding the defualtsocialaccountadapter to filter the emails getting through and that works fine on incognito. -
How 'set_password' method works?
I've been looking for this in DRF and Django doc but I can't find it. Someone could explain how the base method works? Thanks! -
session maintain with simple salesforce
I would like to do session maintenance with simple salesforce. I am using dJango web framework for a tool I developed which is to update data salesforce. Can somebody help with below tasks Would like to sign-in to salesforce without providing Salesforce credentials like Username, password & security token If User wont provides credentials in web page, then framework should consider existing/previous session logged-in successfully. Session should expire after 30 minutes of in-Active I tried to save session in file where i can retrieve for next time, but facing multiple errors file = open(sf_sess_fl, "w") file.write(sf.instance) error: File "", line 1, in TypeError: write() argument must be str, not SFType Thank you in advance Dharani 3. -
Django_filters - MultipleChoiceFilter with ForeignKey not shown
I'm trying to filter a digital product with multiple filters. On of them includes the functionality model. So the user select a category and then, related to the category, can filter the existing products by their functionality models.py class DigitalProduct(models.Model): name = models.CharField(max_length=200, verbose_name='Name') thumbnail = models.ImageField(upload_to='DigitalProduct/thumbnails') category = models.ForeignKey(Category, on_delete=models.CASCADE) class Category(models.Model): category = models.CharField(max_length=200) filter_functions = models.ManyToManyField(Functionality, verbose_name='Filter by') class Functionality(models.Model): functionality = models.CharField(max_length=200) I installed django-filter v2.4.0 and trying to add the filters. filters.py ... class PlatformFilter(django_filters.FilterSet): func = django_filters.MultipleChoiceFilter(field_name='category', conjoined=True) Inside of my views.py function I pass the queryset=Platform.objects.filter(category=category) to get the correct digital products, which is working fine but the category values aren't shown in the MultipleChoiceField. So far I can see the MultipleChoiceField but no values are shown. I tried to change the field name to field_name='category.category' but I get an [invalid name]. Do I miss something? -
Rendering geojson with folium / leaflet.js in django
In a django application I render some geojson using the folium library. This generates html that I can use to display my map, and that all works great. Except that it's pretty sure it owns the universe: it generates the entire page: <!DOCTYPE html> <head>...</head> <body>...</body> <script>...</script> (Note that it doesn't generate an html tag.) My issue is that my site is themed in a certain way, I expect other content on this page explaining the map, my standard headers and footers. And inserting the folium-generated code into my page messes with that. My get_context_data() function, after some database lookups to get the geojson and other parameters I need for my multi-layer map, is just this: geomap = folium.Map(...) root = geomap.get_root() html = root.render() context["html_map"] = html return context Any suggestions how to integrate folium with django? (Or suggestions that I should be doing something totally different?) -
Better many to many filtering logic
Let's say I have 2 models like this: class ModelA(AbstractUser): is_author = models.BooleanField(default=True) class ModelB(models.Model): user = models.ForignKey(ModelA, ondelete=models.CASCADE) liked = models.BooleanField(default=False) date = models.DateTimeField(auto_now_add=True) Right now, let's say I wanted only all ModelB objects liked by the logged-in user, I would do something like this in my view: def view_funct(request): user = request.user modelb_objects = ModelB.objects.filter(liked=user).order_by("-date") This works, however, I feel like there is better and faster filtering I don't know of yet. Is there? -
Login Method in Django works fine with POSTMAN but with front end everything works except Login Method
I am new to React Js and want to connect my React app with Django.I had created CustomUser for authentication purpose , login() for session and used rest_framework.auth.Token (Token) for login Purpose. Now when I am sending POST Request through POSTMAN it creates sessions properly and return email and auth-token but when I am sending POST Request with React Js (Front End) Everything works properly (returns email and token) but login method doesn't create sessions, due to which user.is_authenticated returns False. How to solve this problem. Thanks in Advance. My views.py @csrf_exempt def signin(request): if request.method == 'GET': if request.user.is_authenticated: token,created = Token.objects.get_or_create(user=request.user) return JsonResponse({"Email":request.user.email,"Auth-token":token.key},safe=False) return render(request,'application/signup.html') if request.method == 'POST': # if not request.user.is_authenticated: data = JSONParser().parse(request) email = data['email'] print(email) b1 = email.replace("@","") password = data['password'] print(password) user = authenticate(request,email=email,password=password) if user: location = str(pathlib.Path().absolute())+'\Camera\DatabaseImage\DatabaseImage\\' + b1 + '.jpg' print(location) answer = facedect(location) if answer=="Retry": messages.error(request,"Captured Image is not clear Please be in light") #React #return render(request,"application/signup.html") return JsonResponse("Captured Image is not clear Please be in light",safe=False) if answer == True: login(request,user) token,created = Token.objects.get_or_create(user=request.user) messages.success(request,"Account created") #React #return redirect('http://localhost:8000/homepage/') return JsonResponse({"Email":request.user.email,"Auth-token":token.key,"answer":"abhi login hua hai"},safe=False) else: print("Face Not Found") messages.error(request,"Face Not Found") #React #return render(request, 'Facebook.html') return JsonResponse("Face … -
Django: how to get multiple input?
I m working on cylinder management system in which i want to give functionality that user can issue multiple cylinder. What i m wanting that user get a list of available cylinder where he can choose the cylinders item and submit the form. I m able to handle this for single cylinder , here is what i m applying for single cylinder:- models:- class Cylinder(models.Model): stachoice=[ ('Fill','fill'), ('Empty','empty') ] substachoice=[ ('Available','available'), ('Unavailable','unavailable'), ('Issued','issued') ] cylinderId=models.CharField(max_length=50,primary_key=True,null=False) gasName=models.CharField(max_length=200) cylinderSize=models.CharField(max_length=30) Status=models.CharField(max_length=40,choices=stachoice,default='fill') Availability=models.CharField(max_length=40,choices=substachoice,default="Available") EntryDate=models.DateTimeField(default=timezone.now) issue_Date=models.DateTimeField(null=True) issue_user=models.CharField(max_length=70,null=True) return_Date=models.DateTimeField(null=True) def get_absolute_url(self): return reverse('cylinderDetail',args=[(self.cylinderId)]) def __str__(self): return str(self.cylinderId) class Issue(models.Model): cylinder=models.ForeignKey('Cylinder',on_delete=models.CASCADE) userName=models.CharField(max_length=60,null=False) issueDate=models.DateTimeField(default=timezone.now) def save(self,*args,**kwargs): if not self.pk: if self.cylinder.Availability=='Available': Cylinder.objects.filter(cylinderId=self.cylinder.cylinderId).update(Availability=('Issued')) Cylinder.objects.filter(cylinderId=self.cylinder.cylinderId).update(issue_Date=self.issueDate) Cylinder.objects.filter(cylinderId=self.cylinder.cylinderId).update(issue_user=self.userName) super().save(*args,**kwargs) def __str__(self): return str(self.userName) class Return(models.Model): fill=[ ('Fill','fill'), ('Empty','empty'), ('refill','Refill') ] ava=[ ('yes','YES'), ('no','NO') ] cylinder=models.ForeignKey('Cylinder',on_delete=models.CASCADE) availability=models.CharField(max_length=20,choices=ava) status=models.CharField(max_length=10,choices=fill) returnDate=models.DateTimeField(default=timezone.now) def save(self,*args,**kwargs): if not self.pk: if self.cylinder.Availability=='Issued': Cylinder.objects.filter(cylinderId=self.cylinder.cylinderId).update(return_Date=self.returnDate) if self.availability=='YES' or self.availability=='yes': Cylinder.objects.filter(cylinderId=self.cylinder.cylinderId).update(Availability='Available') if self.status=='empty' or self.status=='Empty': Cylinder.objects.filter(cylinderId=self.cylinder.cylinderId).update(Status='Empty') else: Cylinder.objects.filter(cylinderId=self.cylinder.cylinderId).update(Availability='Unavailable') if self.status=='refill' or self.status=='Refill': Cylinder.objects.filter(cylinderId=self.cylinder.cylinderId).update(Status='Refill') if self.status=='empty' or self.status=='Empty': Cylinder.objects.filter(cylinderId=self.cylinder.cylinderId).update(Status='Empty') super().save(*args,**kwargs) def __str__(self): return str(self.cylinder) views:- @login_required def issue(request): if not request.user.is_superuser: return redirect('index') form=IssueForm() if request.method=='POST': form=IssueForm(data=request.POST,files=request.FILES) if form.is_valid(): form.save() return redirect(cylinderListView) return render(request,'entry/cylinder_form.html',{'form':form}) form template:- <div class='col-lg-12' id="divForm"> <br> <div class="form-group " id="form1"> <h3>New Entry</h3> <form method="post" > {% csrf_token %} {{ … -
Can i send POST request to view function from another view function in django?
I am creating a Django multi-wizard form. I need to send Data to an already created view through post request Here is the Wizard form: class UserQueryWizard(SessionWizardView): template_name = "wizards/index.html" form_list = [forms.ShippingForm, forms.ExporterdetailsForm, forms.ImporterdetailsForm, ] def done(self, form_list, **kwargs): post_data = [form.cleaned_data for form in form_list] ------need to send this post_data ------ return SEND('query/',method='POST') <--- Example I know its not correct its ruff idea what I want I set up the URL Like this: path('query/', views.UserQueryView.as_view(), name='user_query'),<--- Where i send POST Request And the view class UserQueryView(View): def post(self, request, *args, **kwargs): importer = request.POST.get('importer', '') .......etc...................... query = UserQuery.objects.create( make=make, model=model, version=version, launch_date=launch_date, body_type=body_type, importer_type=importer_type, vehicle_condition=condition, mileage=mileage, chasis_number=chasis_number, engine_number=engine_number, fuel_type=fuel_type, vehicle_color=vehicle_color, seating_position=seating_position, importer=importer, importer_country=importer_country, importer_city=importer_city, importer_name=importer_name, exporter_name=exporter_name, exporter=exporter, exporter_country=exporter_country, exporter_city=exporter_city, hs_code=hs_code ) result = render_to_string( 'partials/_alert.html', {"type": "success", "message": "Query Saved Successfully"}, request=request) query = render_to_string( 'partials/_table_row.html', {'vehicle': query}, request=request) return JsonResponse({"message": result, 'query': query}) -
How to include urls file from sub sub folder in django
i try to include urls from my Api folder i tried path('api/', include("main.Apps.Api.apps.urls")) but it doesn't work in my settings.py i add the app by INSTALLED_APPS += ["main.Apps.Api.apps.ApiConfig"] and i changed the app name in Api.apps.py to name = 'MikeWebsite.Apps.Api' Everything works But include the urls return me ModuleNotFoundError: No module named 'MikeWebsite.Apps.Api.apps.urls'; 'MikeWebsite.Apps.Api.apps' is not a package my project file tree look like this main └───_main ├── __init__.py ├── settings.py ├── urls.py ├── wsgi.py └──_Apps ├──_Api | └── urls.py └── ... What I'm doing is wrong? And if you have a good source of information on how to work with apps nested in Django