Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to do wildcard search for single character replacement ( ? ) in Django ORM?
I have a case where I need to do a wildcard search using Django ORM. I have a column - column1 which contains mobile numbers. I need to do a wildcard search for a single character replacement which is ? in SQL. I can do that like Mobilenumbers.objects.raw('SELECT * FROM MOBILENUMBERS WHERE COLUMN1 LIKE '98765?7644'). But how do I do that same thing in Django ORM. This is not a duplicate of Wildcard searching in Django. -
How do I add PointField in django-admin?
I can't seem to add a value in django-admin for PointFied. I am still new in django-admin so I don't really know what I'm missing here. Any help would be appreciated. I am using Django 2.2.2 and python 3.x -
The view accounts.views.profile didn't return an HttpResponse object. It returned None instead
here is my views. def profile(request, username): if User.objects.filter(username=username).exists(): u = User.objects.filter(username=username)[0] if not Followers.objects.filter(user=username, follower=request.user.username).exists(): following = "Follow" cls = "btn-p" else: following = "Following" cls = "btn-t" if u.profilepic == "": u.profilepic = "static/assets/img/default.png" followers_p = 0 following_p = 0 posts = 0 name = u.name bio = u.bio posts = Photo.objects.filter(owner=username) posts = len(posts) followers_p = len(Followers.objects.filter(user=username)) following_p = len(Followers.objects.filter(follower=username)) context = { 'ProfilePic': u.profilepic, "whosprofile": username, "logged_in_as": request.user.username, "following": following, "cls":cls, "posts":posts, "followers_p":followers_p, "following_p": following_p,"name":name, "bio":bio } if request.user.is_authenticated: return render(request, 'logged-in-profile.html', context) return render(request, 'profile.html', context) -
How to get the current stock quantity for each item in an inventory system?
I wanna summarize the current stock quantity of each item in django admin. In item page, each item have a column, and I wanna show the number in each column of item. This is my model: from django.contrib.auth.models import User from django.db import models class Item(models.Model): item_name = models.CharField(max_length=128) class In(models.Model): in_date = models.DateTimeField(') item = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='ins') quantities = models.IntegerField() class Out(models.Model): out_date = models.DateTimeField() item = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='outs') quantities = models.IntegerField() Model In means stock-in, Out means stock-out I write functions in my ADMIN.PY like below: class ItemAdmin(admin.ModelAdmin): list_display = ['item_name', 'pattern', 'vendor', 'item_ins', 'item_outs'] def item_ins(self, obj): return obj.ins.aggregate(Sum('quantities')).get('quantities__sum') item_ins.short_description = 'stock-in' def item_outs(self, obj): return obj.outs.aggregate(Sum('quantities')).get('quantities__sum') item_outs.short_description = 'stock-out' I already knew how to aggregate total stock-in/stock-out number of each item, but I don't know how to get current stock quantity(stock-in subtract sotck-out) of each item. Please help me! Thank you! -
Checkbox in Dropdown Django
I have a form in my django app and it contains a dropdown. Models.py class Quiz(models.Model): mtypes = (('A', 'A'), ('B', 'B'), ('C', 'C'), ('D', 'D'), ('E', 'E')) material_type = models.CharField(max_length=255, default=0, choices=mtypes) Views.py class QuizCreateView(CreateView): model = Quiz fields = ('material_type') template_name = 'classroom/teachers/quiz_add_form.html' def form_valid (self, form): quiz = form.save(commit=False) quiz.owner = self.request.user quiz.save() return redirect('teachers:quiz_change', quiz.pk) html {% load crispy_forms_tags %} {% block content %} <nav aria-label="breadcrumb"> <ol class="breadcrumb"> <li class="breadcrumb-item"><a href="{% url 'teachers:quiz_change_list' %}">RFQs</a></li> <li class="breadcrumb-item active" aria-current="page">Post New RFQ</li> </ol> </nav> <h2 class="mb-3">Post New RFQ</h2> {% csrf_token %} {#<h3>Material Details</h3>#} <div class="form-group col-md-4 mb-0"> {{ form.material_type|as_crispy_field }} </div> <button type="submit" class="btn btn-success">Save</button> I am able to display material_type as a dropdown list but can I add checkboxes to this DropDown? This is what the closest I could find but the documentation on the listed libraries is not so clear. How do I do that? -
Save the data in the Postgresql database
I don't catch how to save the scraped data in the Postgresql database. I tried to use Psycopg2 without effect... I learned that I can use django models for this The scraper should scrape every blog post on each page Data from the scraper should go to the Postgresql database, where the following statistics will be counted: 1.The 10 most common words along with their numbers under the address /stats 2.The 10 most common words with their numbers per author available under the address / stats / / posts authors with their name available in the address / stats / / available under the address / authors / in the code below, for example, I tried to get the names of the authors but I get such an error : authors = Author(name='author name') TypeError: 'NoneType' object is not callable importing models to the scraper does not help either... Here is my scraper: import requests from bs4 import BeautifulSoup as bs from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from collections import Counter url = 'https://teonite.com/blog/page/{}/index.html' all_links = [] headers = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'User-Agent': 'Mozilla/5.0' } with requests.Session() as s: r = s.get('https://teonite.com/blog/') soup = bs(r.content, 'lxml') article_links = … -
celery not working in django and just waiting (pending)
i'm trying found how celery is working. i have a project that have about 10 app.now i want use celery . setting.py: CELERY_BROKER_URL = 'amqp://rabbitmq:rabbitmq@localhost:5672/rabbitmq_vhost' CELERY_RESULT_BACKEND = 'redis://localhost' i created a user in rabbitmq with this info:username: rabbitq and password:rabbitmq . then i create a vhost with name rabbitmq_vhost and add rabbitmq permission to it. all is fine i think because all of error about rabbitmq disappear . here is my test.py: from .task import when_task_expiration def test_celery(): result = when_task_expiration.apply_async((2, 2), countdown=3) print(result.get()) task.py: from __future__ import absolute_import, unicode_literals import logging from celery import shared_task from proj.celery import app @app.task def when_task_expiration(task, x): print(task.id, 'task done') return True now when i call test_celery() in python shell it's pending.i try to replace @shared_task and @app.task(blind=True) but noting changed.even i try use .delay() instead apply_async((2, 2), countdown=3) and again nothing happend. i'm trying to use celery to call a function in specific time during this queation that i ask in past.thank you. -
How to count total occurrence of distinct field of same model in django?
I am trying to get the total count of occurrence of a field in same model in django. Is it possible to do it or not? for example I have a model as below: class Blog(DateTimeModel): title = models.CharField(max_length=255) description = models.TextField() category = models.CharField(max_length=255, null=True, blank=True) and a table of data as below: id | title | description | category ----+-------------------------------------+----------------------+---------- 1 | blog title first | description 1 | social 2 | blog title second | description 2 | social 3 | blog title third | description 3 | community 4 | blog title fourth | description 4 | community 5 | blog title fifth | description 5 | people I want a result to be as: <QuerySet [{'category': 'social', 'blog_count': '2'}, {'category': 'community', 'blog_count': '2'}, {'category': 'people', 'blog_count': '1'}]> I have tried doing Blog.objects.values('category').order_by('category').distinct('category').count() and got result as 3 which is true because it had count the total distinct values related to category. Django annotate count with a distinct field this post provide a solution where we can count fields based on two models. But i want the results from the same model. -
Re-write a php script in python using django framework
I have recently started learning python using the Django framework. I have a PHP script that I wrote that consumes some web services using Curl. I would like to re-write this script in Django but I have nowhere to start. Below is the PHP script <?php if($_POST) { $selectedGrowerNo = $_POST['vnumber']; $bookingDate = $_POST['bookingdate']; $selectedSaleDate = $_POST['dated']; $bales = $_POST['bales']; $reoffer = $_POST['reoffer']; $floorCode ="ATT"; //take from parameters table $bookedBy = "USERNAME"; $data_Array = array(); $url = "https://webserviceexample.com/insertbookingWebservices"; $post_data = array( 'grower' => $selectedGrowerNo, 'saleDate' => $selectedSaleDate, 'floor' => $floorCode, 'bookingDate' => $bookingDate, 'balesBooked' => $bales, 'saleDate' => $selectedSaleDate, 'bookedBy' => $bookedBy, 'reoffer' => $reoffer ); $headers[] = 'Accept: */*'; $headers[] = 'Content-Type: application/x-www-form-urlencoded'; $headers[] = 'Authorization: Digest nonce="4jM0NjkxNDY3NDU3NzYuNDo3YWNiNjk3NjIzNmY2MWU2ZmY2ZGRlZWRlMWFiYmVhNw",nc="1",cnonce="20eb5a87df578f43b2b780a610ed2f68",qop="auth",username="USERNAME",uri="/insertbookingWebservices",response="6ac54919e2547192f82cd0a431cee47b"'; $options = array( CURLOPT_URL => $url, CURLOPT_HEADER => false, CURLOPT_HTTPHEADER => $headers, CURLOPT_VERBOSE => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => false, CURLOPT_SSL_VERIFYPEER => false, // for https CURLOPT_HTTPAUTH => CURLAUTH_DIGEST, CURLOPT_POST => true, CURLOPT_POSTFIELDS => http_build_query($post_data) ); $ch = curl_init(); curl_setopt_array( $ch, $options ); try { $raw_response = curl_exec( $ch ); // validate CURL status if(curl_errno($ch)) throw new Exception(curl_error($ch), 500); // validate HTTP status code (user/password credential issues) $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); if ($status_code != 200) throw new Exception("Response with Status … -
How to combine the values of two models under another model
I have an app which includes three models as below. 'PersonelBilgisi' and 'SalonBilgisi' have thousands entries. I want to relate these two model to SinavBilgisi. Since 'PersonelBilgisi' and 'SalonBilgisi' have many entries, I cannot use ManyToManyField to relate. I want to create an entry for SinavBilgisi, assign the entries of 'PersonelBilgisi' and 'SalonBilgisi' to the entry of SinavBilgisi automatically and save to the database. models.py class PersonelBilgisi(models.Model): unvan = models.CharField(max_length=75) adsoyad = models.CharField(max_length=75) class SalonBilgisi(models.Model): bina =models.CharField(max_length=45) kat =models.CharField(max_length=45) class SinavBilgisi(models.Model): donem =models.CharField(max_length=45) ders = models.CharField(max_length=45) I tried to relate it in views.py and listed in html file but could not manage to relate with SinavBilgisi. views.py def atama (request): personels =[p for p in PersonelBilgisi.objects.all()] salon = [sa for sa in SalonBilgisi.objects.all()] return render(request, 'organizasyon/home.html', {'personels ':personels , 'salon':salon}) EXPECTED OUTCOME In html file donem: 2019-2020 ders: AA unvan | adsoyad| bina | kat Dr | Alice | Karaagac | Second Prof. Dr | Jonny| MYO| Third *In admin page under SinavBilgisi * donem: 2019-2020 ders: AA (When I clik it, I want to see the entries listed in html file as shown above) donem: 2019-2020 ders: AB donem: 2019-2020 ders: AC -
Weather request can't send to open weather map
I am sending request to openweathermap for weather but it can't send to it. from django.shortcuts import render import requests def index(request): url = 'api.openweathermap.org/data/2.5/weather?q={}&units=imperial&appid=*************************' city = 'lahore' r = requests.get(url.format(city)) print(r.text) return render(request,'weather/weather.html') Invalid URL 'api.openweathermap.org/data/2.5/weather?q=lahore&units=imperial&appid=**********************': No schema supplied. Perhaps you meant http://api.openweathermap.org/data/2.5/weather?q=lahore&units=imperial&appid=***********************? Error Picture -
How to pass variables from the Django view to a template
I want to pass a variable from views.py to home.html. I tried everything I could and I am new to django. It doesn't give any error but it doesn't display the variable as well. I may have made mistakes in url.py or settings.py settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'project1' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'project1.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'project1.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_URL = '/static/' urls.py from django.contrib import admin from django.urls import path, include from django.views.generic.base import TemplateView from django.conf import settings from django.conf.urls.static import static from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', TemplateView.as_view(template_name='home.html'), name='home'), … -
Getting the IP address from USER in Django forms
Here's the code In forms.py from django import forms class CmdForm(forms.Form): ip_address = forms.CharField(label='Enter IP address:') command = forms.CharField(label='Command to execute:') In Views.py from django.shortcuts import render from first_app.forms import CmdForm from django.http import HttpResponse def index(request): my_dict = {'insert_me': ""} return render(request,'first_app/index.html',context=my_dict) def form_name_view(request): if request.method == "POST": form = CmdForm(request.POST) if form.is_valid(): from netmiko import ConnectHandler devices = { 'device_type':'cisco_ios', 'ip':'ip_address', 'username':'mee', 'password':'12345', 'secret':'12345', } ipInsert = request.POST.get('ip_address', '') cmd = request.POST.get('command', '') netconnect = ConnectHandler(**devices) #print("connection established with", devices['ip']) getIP = netconnect.send_command(ipInsert) output = netconnect.send_command(cmd) return render(request,'first_app/forms.html', {'form': form, 'output':output, 'getIP':getIP}) else: form = CmdForm() return render(request,'first_app/forms.html', {'form': form}) else: return render(request,'first_app/forms.html', {}) however i m getting the error:- NetMikoTimeoutException at /Automation_page/ Connection to device timed-out: cisco_ios ip_address:22 Request Method: POST Request URL: http://127.0.0.1:8000/Automation_page/ Django Version: 2.2.3 Exception Type: NetMikoTimeoutException Exception Value: Connection to device timed-out: cisco_ios ip_address:22 Exception Location: C:\Users\karti\AppData\Local\Programs\Python\Python37-32\lib\site-packages\netmiko\base_connection.py in establish_connection, line 864 Python Executable: C:\Users\karti\AppData\Local\Programs\Python\Python37-32\python.exe Python Version: 3.7.3 Python Path: ['K:\Work\DevNet\first_project', 'C:\Users\karti\AppData\Local\Programs\Python\Python37-32\python37.zip', 'C:\Users\karti\AppData\Local\Programs\Python\Python37-32\DLLs', 'C:\Users\karti\AppData\Local\Programs\Python\Python37-32\lib', 'C:\Users\karti\AppData\Local\Programs\Python\Python37-32', 'C:\Users\karti\AppData\Local\Programs\Python\Python37-32\lib\site-packages'] why i m getting the time-out though my devices are up and running. thanx to those willing to help.! :-) -
Calling a column within database. I'm workin on django for python
I am currently stuck on program wherein it will output all the post that has a value of category_id == 1 within the table. I can't seem to call the said function can you guys help? thank you it will be fully appreciated. {% for knowledgepost in kposts %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="#">{{ knowledgepost.author }}</a> <small class="text-muted">{{ knowledgepost.date_posted|date:"F d, Y" }}</small> </div> <h3><a class="article-title" href="{% url 'knowledge-detail' knowledgepost.id %}">{{ knowledgepost.title }}</a></h3> ++++++++ the line of code should be here+++++++++++ <p class="article-content">{{ knowledgepost.content|safe|truncatewords:"50"|linebreaks }}</p> </div> </article> I expect the output to be able to call the column within the database -
Django admin change history log
In Django admin application there is a history page, which shows the modification history for a given model. In different models the changes field shown differently: action or comment. Cannot add pics, so here is the link to the pic: https://ibb.co/ynnBp55 Is it possible to change the comment to action, because it is not properly displays modifications. Why is the comments has different format of messaging. We are not using any external packages like simple-history etc. It is just default django logging. We couldn't find any information about overwriting the history block of admin app. And in the code nowhere specified comment or action -
how to implement add to cart with membership purchase
I need help in best practices for add to cart functionality with Premium membership. In backend django,psql and in frontend angular I have already developed app to add to cart functionality https://www.vertabelo.com/blog/technical-articles/database-model-for-an-online-store. Also there is decoupled app to buy a premium membership. Now client wants a new functionality. When user goes to view cart page, he can see the product prices in one column and in another column he will see the discount price for each product if he buys the membership. There will be a button to proceed to checkout and another button buy membership and proceed. Please suggest the best practices to design database for this and what steps should I follow. Also How can I make robust APIs and what are the best practices. Membership Table: user_id FK plan_id FK status 0 deactive 1 active start_date date end_date date created_at updated_at Subscription Plans Table: features name description price item_discount days created_at updated_at -
Edit and Delete the particular user without using admin panel in django
I have created my models using django user model. I am able to perform the edit functionality to the created form.Now i want to do DELETE the particular user details by using DELETE button.Here is my code forms.py class EditProfileForm(forms.ModelForm): class Meta(): model = User fields = ['first_name','last_name','username','email','password'] help_texts={ 'username': None } views.py def edit_profile(request): user = request.user form = EditProfileForm(request.POST or None, initial={'first_name':user.first_name, 'last_name':user.last_name, 'username':user.username, 'email':user.email, 'password':user.password}) if request.method == 'POST': if form.is_valid(): user.first_name = request.POST['first_name'] user.last_name = request.POST['last_name'] user.username = request.POST['username'] user.email = request.POST['email'] user.password = request.POST['password'] user.save() return HttpResponseRedirect(reverse('signupapp:index')) context = {"form": form} return render(request, "signupapp/edit_profile.html", context) edit_profile.html <form method="POST" action="" class="" > {% csrf_token %} {{ form.as_p }} <button type="submit">Save</button> </form> Now here how can add the delete functionality within the edit_profile method of views file. Can anyone help me to do this functionality. Thanks in advance.. -
Decode resulting json and save into db - Django + Postgres
I have a model like this: class MyClass(models.Model): typea = models.CharField(max_length=128) typeb = models.CharField(max_length=128) If for example, the resulting json from an API is like this: { "count": 75, "results": [ { "typea": "This tipe", "typeb": "A B type", "jetsons": [], "data": [ "https://myurl.com/api/data/2/", ], "created": "2014-12-15T12:31:42.547000Z", "edited": "2017-04-19T10:56:06.685592Z", }, I need to parse this result and save typea and typeb into the database, I'm kind of confused on how to do this. I mean, there is the JSONField on Django, but I don't think that will work for me, since I need to save some specific nested string of the json dict. Any example or idea on how to achieve this? I mean, my confusion is on how to parse this and "extract" the data I need for my specific fields. Thank You -
I Develop a movie review project and the only problem that i cannot solve is how to redirect to the movie that i reviewed after deleting the review
How to redirect to the movie that I reviewed after deleting the review of that movie. I did try overriding get_success_url but the pk it will get is the pk of the review not the pk of the movie. example my url in my movie detail is /movie/1/ and the review id is 10 so if i return reverse('movie-detail', kwargs={'pk': self.object.pk}) after i delete the review it will redirect to the /movie/10 instead i want to redirect to /movie/1/ . I hope you get my point and you can help me. Thanks in advance :) views.py class PostDeleteView(DeleteView): model = Review template_name = 'reviews/post_confirmed_delete.html' def get_success_url(self): return reverse('movie-detail', kwargs={'pk': self.object.pk}) urls.py urlpatterns = [ path('', views.index, name='index'), path('movies/', views.movie_list, name='movie-list'), path('movies/', MovieListView.as_view(), name='movie-list'),#This is movie list path('movie/<int:pk>/', MovieDetailView.as_view(), name='movie-detail'),#every detail of movies path('movie/<int:pk>/review', PostCreateView.as_view(), name='post-create'),#adding review to a specific movie path('review/<int:pk>/', ReviewDetailView.as_view(), name='review-detail'),#every detail of every reviews path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'), path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'), ] I expect that after I deleted the review, it will redirect to the movie detail that I reviewed. -
How to adjust two divs in views.py
I have made a loop in divs. First div is for first column and another div for second column. I just want it to manage in views.py. I made two functions in views.py for two separate divs. But it is not showing me the result of last function. It is just showing me the first function pics and only the first div is working. index.html {% static 'images/fulls' as baseUrl %} {% static 'images/thumbs' as hiUrl %} <div class="row"> {% for dest in dest1 %} <div class="col-lg-4"> <a href="{{baseUrl}}/{{dest.img}}"> <img src="{{hiUrl}}/{{dest.img}}" alt="" /> <h3>{{destt.desc}}</h3> </a> </div> {%endfor%} </div> {% for destt in dest2 %} <div> <a href="{{baseUrl}}/{{destt.img}}"> <img src="{{hiUrl}}/{{destt.img}}" alt="" /> <h3>{{destt.desc}}</h3> </a> </div> {% endfor %} def index(request): dest1 = Destination() dest1.desc = 'Hello, How arE you?' dest1.img = '01.jpg' return render(request, 'index.html', {'dest1':dest1}) def nextt(request): dest2 = Destination() dest2.desc = 'Hello, How arE you?' dest2.img = '02.jpg' return render(request, 'index.html', {'dest2':dest2}) -
How can I get url of images from browser in django view
What should I do to allow django to read the image url from browser? I'm learning to do a django app for getting dominant colors from images in grasshopper, so that the results could appear in rhino. which need to get images from browser. Images were downloaded in my PC could work , but not images from browser. Then I wonder if there is any python library could help with this problem? jsob = {"clusters": 5,"path": 0} if request.method == "POST": try: data = request.POST["data"] print(data) received = json.loads(str(data)) jsob.update(received) path = jsob.get("path") clusters = int(jsob.get("clusters")) dc = DominantColors(path, clusters) colors = dc.dominantColors().tolist() print(colors) print(type(colors)) results = {"colors":colors} return JsonResponse(results) except Exception as e: PASS -
How to upload image file in django related to a perticular user only
I'm trying to upload a file in django such that uploaded file is linked to a foreign key. i.e. if I upload a file then in database it should reflect that with which database subject it is related to This is my views.py file: def pod_upload (request, pk): lr_object = get_object_or_404(LR, id=pk) if request.method == 'POST': form = UploadPODform(request.POST, request.FILES) form.lr_connected = lr_object form.save() if form.is_valid(): form.lr_connected = lr_object form.save() return redirect('home') else: form = UploadPODform() form.lr_connected = lr_object return render(request, 'classroom/suppliers/model_form_upload.html', {'form': form}) This is my forms.py file: class UploadPODform(forms.ModelForm): class Meta: model = Uploaded_pod fields = ('document',) def __init__ (self, *args, **kwargs): super(UploadPODform, self).__init__(*args, **kwargs) # self.fields['lr_connected'].required = False This is my models.py file: class Uploaded_pod(models.Model): document = models.FileField(upload_to='pods/') lr_connected = models.ForeignKey(LR, on_delete=models.CASCADE, related_name='lr_pod') I expect that if some user upload a file then it must be saved with respect to the LR object. -
"Error occurred while reading WSGI handler" Problem in deploying a Django app on IIS
I am in the process of deploying a Django app in IIS. I have gone through this link https://www.mattwoodward.com/2016/07/23/running-a-django-application-on-windows-server-2012-with-iis/ and followed it step by step. But when I hosted my Django app named 'sample', other apps that were hosted on the IIS started showing the below error while browsing and to mention other apps were developed in different frameworks. Error occurred while reading WSGI handler: Traceback (most recent call last): File "C:\virtualenvs\sample\Lib\site-packages\wfastcgi.py", line 791, in main env, handler = read_wsgi_handler(response.physical_path) File "C:\virtualenvs\sample\Lib\site-packages\wfastcgi.py", line 633, in read_wsgi_handler handler = get_wsgi_handler(os.getenv("WSGI_HANDLER")) File "C:\virtualenvs\sample\Lib\site-packages\wfastcgi.py", line 616, in get_wsgi_handler raise ValueError('"%s" could not be imported%s' % (handler_name, last_tb)) ValueError: "django.core.wsgi.get_wsgi_application()" could not be imported: Traceback (most recent call last): File "C:\virtualenvs\sample\Lib\site-packages\wfastcgi.py", line 605, in get_wsgi_handler handler = handler() File "C:\virtualenvs\sample\lib\site-packages\django\core\wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "C:\virtualenvs\sample\lib\site-packages\django\__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "C:\virtualenvs\sample\lib\site-packages\django\conf\__init__.py", line 57, in __getattr__ self._setup(name) File "C:\virtualenvs\sample\lib\site-packages\django\conf\__init__.py", line 44, in _setup self._wrapped = Settings(settings_module) File "C:\virtualenvs\sample\lib\site-packages\django\conf\__init__.py", line 107, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Python37-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, … -
I literally been stuck in this loop for days. edit/update can't detect the pk of the model?should i submit a ticket?
the error : .Reverse for 'patient_update' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['patients/update/(?P<pk>[0-9]+)$']? whenever i try calling the url in a template whether in action of a form tag or just a normal anchor. I made a view where users can edit the patients information and as I'm using a custom user model I had to make a custom update/delete view.The views are working when i enter them manually by the url but when i put a link reference to them by an anchor tag i get an error that it can't access the pk,I tried following many answers here and vids on YT but the error is still there Views.py def PatientUpdateView(request,pk=None): patient = get_object_or_404(models.Patient, pk=pk) form = forms.PatientForm(request.POST or None ,instance=patient) if form.is_valid() : patient = form.save(commit=False) patient.save() messages.success(request,"patient updated!") context = { 'patient': patient, 'form': form } return render(request,'patients/patient_edit_form_success.html',context) else: context = { 'patient' : patient, 'form': form, } return render(request, 'patients/patient_edit_form.html', context) and here's how i call it in an anchor tag <a class="btn btn-info btn-sm" href="{% url 'patients:patient_update' patient.pk %}">Open</a> I tried pk = patient.pk pk = pk pk={{ patient.pk}} and many other ways of calling it. urls.py here's the url … -
Drop Down group create and auto user add
The idea of my app is this. At the welcome screen the user has two options either register as a buyer or a seller. If the user decides to go for the simple buyer registration I'm going to use Django's built in sign up form for it but when the user signs up as a seller I want to create a group named "Owner" and their the user is automatically added and has a different dashboard according to their respective group. But this group gets created just once not on every view call. Please give me an idea to how can I achieve this. models.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib.auth.models import Group from django.db import models from cities_light import models as CityModel from phonenumber_field.modelfields import PhoneNumberField from django.contrib.auth.models import User class HallOwnerData(models.Model): owner_name = models.CharField( max_length=256) owner_address = models.CharField("Address",max_length = 256) owner_cnic = models.CharField("CNIC", max_length = 16) contact_number = PhoneNumberField() class HallProperties(models.Model): hall_name = models.CharField(max_length = 128) hall_city = models.ForeignKey(CityModel.City, max_length=512) hall = models.ForeignKey(HallOwnerData,on_delete = models.CASCADE) hall_address = models.CharField("Address", max_length = 128) hall_capacity = models.PositiveSmallIntegerField("Max Capacity") hall_number = PhoneNumberField() views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.http import HttpResponse from …