Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Gunicorn failed Triggered by gunicorn.socket: Failed with result 'exit-code'. error
I'm trying out a simple Django deployment app on VPS using this url. I went through every step of the work and successfully ran this project via python manage.py runserver where there isn't a mistake, but when I try to implement it with unicorn its launch following error ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Wed 2022-03-16 11:28:04 CET; 22h ago TriggeredBy: ● gunicorn.socket Main PID: 5578 (code=exited, status=2) Warning: journal has been rotated since the unit was started, output may be incomplete. Here are the files nano /etc/systemd/system/gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target nano /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=root Group=www-data WorkingDirectory=/home/pawnhost/page_builder ExecStart=/home/pawnhost/env/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind /run/gunicorn.sock \ pawnhost.wsgi:application [Install] WantedBy=multi-user.target systemctl status gunicorn.socket ● gunicorn.socket - gunicorn socket Loaded: loaded (/etc/systemd/system/gunicorn.socket; enabled; vendor preset: enabled) Active: active (listening) since Thu 2022-03-17 09:58:53 CET; 25min ago Triggers: ● gunicorn.service Listen: /run/gunicorn.sock (Stream) CGroup: /system.slice/gunicorn.socket Mar 17 09:58:53 mail2.pawnhost.com systemd[1]: Listening on gunicorn socket. systemctl status gunicorn ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Wed 2022-03-16 11:28:04 CET; 23h ago TriggeredBy: … -
PermissionError when uploading file on new production server
I migrated my Django project to a new production server. On the previous production server, everything worked fine. While migrating, I upgraded to Ubuntu 20.04 and Django 4.0.3. Now everything is working again, except for the uploading of files. When I try to create an instance of an Invoice object, it works, as long as I don't try to upload a file along with it. Adding an invoice with a file gives the following errors: Internal Server Error: /stock/create_invoice Traceback (most recent call last): File "/usr/local/lib/python3.8/dist-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/usr/local/lib/python3.8/dist-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/var/www/html/stock/views.py", line 346, in create_invoice invoice.save() File "/usr/local/lib/python3.8/dist-packages/django/db/models/base.py", line 806, in save self.save_base( File "/usr/local/lib/python3.8/dist-packages/django/db/models/base.py", line 857, in save_base updated = self._save_table( File "/usr/local/lib/python3.8/dist-packages/django/db/models/base.py", line 1000, in _save_table results = self._do_insert( File "/usr/local/lib/python3.8/dist-packages/django/db/models/base.py", line 1041, in _do_insert return manager._insert( File "/usr/local/lib/python3.8/dist-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python3.8/dist-packages/django/db/models/query.py", line 1434, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "/usr/local/lib/python3.8/dist-packages/django/db/models/sql/compiler.py", line 1620, in execute_sql for sql, params in self.as_sql(): File "/usr/local/lib/python3.8/dist-packages/django/db/models/sql/compiler.py", line 1547, in as_sql value_rows = [ File "/usr/local/lib/python3.8/dist-packages/django/db/models/sql/compiler.py", line 1548, in <listcomp> [ File "/usr/local/lib/python3.8/dist-packages/django/db/models/sql/compiler.py", line 1549, in <listcomp> self.prepare_value(field, self.pre_save_val(field, obj)) File "/usr/local/lib/python3.8/dist-packages/django/db/models/sql/compiler.py", … -
failed to get real commands on module "": python process died with code 1
I have a Django project in which I created several custom Django management commands. For some reason I can't explain, I got this error: "failed to get real commands on module "": python process died with code 1: command '' took too long and may freeze everything. consider adding it to 'skip commands' list" Although there are many questions on Stackoverflow on this topic I can't find the reason of why I am getting this error. It doesn't seem to me that this is a Pycharm bug (like in 2015). Could someone explain this error to me? What is it due to? -
Current datetime according to the timezone of the object in a query
I have a model that represents a restaurant: class Restaurant(models.Model): timezone = models.CharField(_("Timezone"), max_length=128, null=True, blank=True) ... I need to process restaurants if the current time for that restaurant is greater than 8:00h (start working day). How could I create an annotation with the current datetime for each restaurant to use in a query? I would like something like this: Restaurant.objects.annotate(restaurant_datetime=timezone.now().astimezone(pytz.timezone(timezone_of_the_restaurant))) -
channels slows app and creates many HTTP 500 errors
I use channels to inform the frontend of my app to force a page update. What I discovered is, that it is much slower in debug mode now and also I have tons of HTTP 500 in my webconsole. Occasionally I end up with: ERROR:daphne.server:Exception inside application: Single thread executor already being used, would deadlock Traceback (most recent call last): File "...\venv\lib\site-packages\channels\staticfiles.py", line 40, in __call__ return await self.staticfiles_handler_class()( File "...\venv\lib\site-packages\channels\staticfiles.py", line 56, in __call__ return await super().__call__(scope, receive, send) File "...\venv\lib\site-packages\channels\http.py", line 198, in __call__ await self.handle(scope, async_to_sync(send), body_stream) File "...\venv\lib\site-packages\asgiref\sync.py", line 382, in __call__ raise RuntimeError( RuntimeError: Single thread executor already being used, would deadlock And also all the HTTP 500 errors are usually some resources that can not be loaded - icons and other static files. Loading the page can last forever, but I remember for some time it worked just fine. I am using django-eventstream for creating my channels. How would I find out what is slowing me down, or how can I prevent it? Is my problem (probably) similar to this one: Django and Channels and ASGI Thread Problem? -
Filter query through an ID to another table in Django
Let's say I have this query Table 1 cardId = 1 table_1 = card_tbl.ocabjects.get(id=cardId).values('category1_id') and the Output for this is Table 1 is <QuerySet [{'category1_id': 1}]> Next is I want to match the value of table 1 to table 2 Table 2 table_2 = category1_tbl.objects.filter(Q(id=table_1)) The table 2 contains column which is a name and I want just to get result name through matching ID from different table for example jason Need help -
If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import
I get an circular import or " does not appear to have any patterns in it" error although I am sure of my spelling and syntax. searched in the internet but most of the problems I found were spelling or syntax related. This is my code: urls.py : from django.urls import path from hi import views urlpattern=[ path("", views.howarey, name="x") ] views.py: from django.http import HttpResponse from django.shortcuts import render # Create your views here. def howarey(request): return HttpResponse("hi") settings.py : INSTALLED_APPS = [ 'hi', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] urls.py: from xml.etree.ElementInclude import include from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('hi/', include("hi.urls")) ] The error from The CMD: raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'hi.urls' from 'C:\\Users\\ahmad\\mx\\hi\\urls.py'>' does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import. -
Django not show checkbox in html
I want to set checked in checkbox. This is html code if device.status is True then set checked in checkbox. {% for device in device %} <h2>status = {{device.status}}</h2> <!-- Rounded switch --> <label class="switch"> <form action="addStatus" method="post"> {% csrf_token %} {% if device.status == 1 %} <input type="checkbox" name="status" onChange="this.form.submit()" checked> {% else %} <input type="checkbox" name="status" onChange="this.form.submit()" > {% endif %} </form> </label> {% endfor %} It can show status = True but not show checkbox. How to fix it? -
Django give permissions to users per company
In my case I have different users which can be part of different companies. An user can belong to multiple companies and a company has multiple customers, products, services, … Now I want the user to be able to have different permissions per company. So let’s say user X can manage the customers in company A but can only read the products and services. And user X can manage the users, products and services in company B. I would like to work with roles: so manage everything would be the role “superadmin” and manage customers but read products and services would be the role “sales” for example. So in short: I want to create roles where I can assing permssions to and then add these roles to users per company. I am planning on using rsinger86/drf-access-policy to manage access control but any suggestions are welcome. Please suggest me a good way to accomplish this scenario. How am I able to add roles per company and am I still able to use the by-default-generated auth_permissions from Django? Thank you in advance! -
{ "product": [ "This field is required."] } in Django REST API
This is my models and I defined set null=True, blank=True for foreign key relations but when I hit my API then API response raised that { "product": [ "This field is required."] }. What I wrote wrong. please help me. **Here is my model:** class CashSell(models.Model): user_profile = models.ForeignKey('accounts.UserProfile', on_delete=models.CASCADE) product = models.ForeignKey('inventory.Product', on_delete=models.CASCADE, related_name='cash_sell', null=True, blank=True) cash_sell_debit = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) description = models.CharField(max_length=250) date = models.DateField() picture = models.ImageField(upload_to='cash_sell_pics', blank=True, null=True, default='images.png') def __str__(self): return self.user_profile.first_name class Meta: verbose_name = "Cash Sell" verbose_name_plural = "Cash Sell" -
How to design django app with integrated gRPC server?
I am currently working on a django project where I need a separate backend application to be able to initiate gRPC requests to my django frontend. Simply put: I want the backend to be able to access and change objects. Therefore I need my django project to also start my grpc server while starting up. I did a lot of research and didn't really find any best practice on that. As far as I would imagine, I could override the startup command of django to also start my grpc server on a seperate thread. But I am afraid that I will end up with a very bad practice solution. Is there any recommendable way to do this? I am excited about every hint :) -
How to query all the fields in parent as well as child model related with a foreign key in Django ? where id matches to the parent class?
I have 3 models in this project class products(models.Model): product_id = models.CharField(max_length=10, blank=False, null=False, primary_key=True) name = models.CharField(max_length=20, blank=False) description = models.TextField(blank=True, null=True) userslikedproduct = models.ManyToManyField(UserAccount, blank=True) def __str__(self): return self.product_id class productReviews(models.Model): review_id = models.CharField(max_length=10, blank=False, null=False, primary_key=True) product = models.ForeignKey(products, related_name='reviews', on_delete=models.CASCADE) user = models.ForeignKey(UserAccount, related_name='users', on_delete=models.CASCADE) review_desc = models.TextField(blank=True, null=True) review_rating = models.IntegerField(choices=RATING, null=True) date_added = models.DateTimeField(verbose_name='date_added', auto_now_add=True) class ReviewImage(models.Model): review = models.ForeignKey(productReviews, related_name='review_images', on_delete=models.CASCADE) image = models.ImageField(null=True, blank=True, upload_to="/images/") I want to fetch all the reviews related to a product id along with review images. I tried using Query1 = productReviews.objects.all().filter(product=product).values().order_by('-date_added') Query2 = ReviewImage.objects.filter(review__product__product_id=product).values_list('review', 'image') Query1 results in all the objects without images Query2 reults in all the images and review ids without review objects How can I fetch all the reviews of one particular product along with the review images? -
Getting url of image on django/wagtail site
I have a wagtail site - where blogpages are rendered by looping through a streamfield (in which each block can have an image, a heading and some text): <div class="col-md-8 mx-auto px-auto"> <div class="conundrum mb-3">{{ page.category }}</div> <h1>{{ page.title }}</h1> <p class="meta">{{ page.date }}</p> <div class="intro my-4 py-4">{{ page.intro }}</div> {% for block in page.content %} <div class="pb-4"> {% image block.value.image fill-1000x500 class='blog_image' %} <h2 class="py-2 my-2"> {% include_block block.value.heading %} </h2> {% include_block block.value.text %} </div> {% endfor %} </div> I want the 'tweet this' button on the blogpage to include the first image on that page. <meta name="twitter:card" content="summary" /> <meta name="twitter:site" content="@PsymatikDotCom" /> <meta name="twitter:title" content="{{page.title}}" /> <meta name="twitter:description" content="{{page.intro}}"/> <meta name="twitter:image" content="https://how_do_i_get_this_path" /> But it is not clear to me how to dynamically grab the url of the first image to enter it in the twitter:image section? -
I have followed the azure app service documentation but wasn't able to deploy my app and failed drastically. please if anyone can help me out
I have followed the azure app service documentation but wasn't able to deploy my app and failed drastically.. please if anyone can help me out with this https://github.com/akj1608/bicaption/runs/5498451909?check_suite_focus=true https://github.com/akj1608/bicaption https://frts.azurewebsites.net/ if anyone can help, please do! -
Why after parsing template ,my modals doesn't work
My reply comment modal doesn't work after I parsed the templates(navigation,footer,base).But if I put them all in same page (not parsing) is working.If I parse them,the modal reply (id="modal-reply") doesnt't work.Can anyone help me?What should I do to fix that? (blablablablablalbblablablablablablablabla) . . . . commentsAdmin.html {% extends 'AdminTemplates/baseAdmin.html' %} {% load static %} {% block contentAdmin %} <div class="content-wrapper"> <div class="container-fluid"> <!-- Breadcrumbs--> <ol class="breadcrumb"> <li class="breadcrumb-item"> <a href="{% url 'indexAdmin' %}">Anasayfa</a> </li> <li class="breadcrumb-item active">Yorumlar</li> </ol> <div class="box_general"> <!-- <div class="header_box"> <h2 class="d-inline-block">Yorumlar</h2> <div class="filter"> <select name="orderby" class="selectbox"> <option value="Any time">Any time</option> <option value="Latest">Latest</option> <option value="Oldest">Oldest</option> </select> </div> </div> --> <div class="list_general reviews"> <ul> <!-- {{stars}} --> {% for comment in comments %} <li> <span>{{comment.created_date}}</span> <span class="rating"> {% for star in comment.getStar %} <i class="fa fa-fw fa-star yellow"></i> {% endfor %} {% for star in comment.getNoneStar %} <i class="fa fa-fw fa-star"></i> {% endfor %} </span> <figure><img src="{{comment.course.image.url}}" alt=""></figure> <h4>{{comment.course.title}}</h4> <p>{{comment.comment}}</p> <p class="inline-popups"><a href="#modal-reply" data-effect="mfp-zoom-in" class="btn_1 gray"><i class="fa fa-fw fa-reply"></i> Reply to this review</a></p> </li> {% endfor %} </ul> </div> </div> </div> <!-- /container-fluid--> </div> {% endblock contentAdmin %} {% block scriptsAdmin %} <!-- Bootstrap core JavaScript--> <script src="{% static 'assetsAdmin/vendor/jquery/jquery.min.js' %}"></script> <script src="{% static 'assetsAdmin/vendor/bootstrap/js/bootstrap.bundle.min.js' %}"></script> <!-- Core … -
PageNumberPagination in django via custom queryset
Scenario : I am using django rest framework and I want to create an API to list products using Pagination. Problem: I have a dictionary coming through a defined method (which shows products for a filtered category) and now I want to pass this dictionary to queryset. Is it feasible? class PageNumberSetPagination(PageNumberPagination): page_size = 5 ordering = '-created_at' class ProductList(ListAPIView): queryset = getCategoryProduct() serializer_class = ProductSerializer pagination_class = PageNumberSetPagination In settings.py: REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 100 } -
Session items wont set on every Cart Item Added
Cart:- class Cart(View): def get(self , request): categories = Category.get_all_categories() if(request.session['cart']): productsToShow = request.session['cart'] else: productsToShow = [] productid = request.GET.get('product') product = get_object_or_404(Products, id=productid) sellername = request.GET.get('seller') seller = get_object_or_404(Sellers, name=sellername) productsToShow = [] prices = Price.objects.filter(product=product,seller=seller) for price in prices: product = price.product product.seller = price.seller product.price = price.cost productsToShow.append(product) request.session['cart'] = productsToShow return render(request , 'cart.html' , {'products' :productsToShow,'categories' : categories} ) AttributeError at /cart 'list' object has no attribute 'keys' -
is it possible to monitor the amount of cryptocurrency in an address on the blockchain app
I was wondering if i could display a counter for both Dogecoin and Bitcoin for my address on my website. You can get images of other websites so I thought this might be possible but I'm not sure. does anyone know if this is possible and if so, how would i do it. -
Html - Create dropdown menu links from logged in user's name
I would like to create a dropdown menu from the logged-in user account. currently, the top-right button in the navigation bar is either "Login" or "Logout" based on if user is logged in. I would hope to create a dropdown menu when user is logged in, which contains more options such as account, myorder, and logout. So I can save space in the navigation bar by avoiding having too many buttons. Some desired examples like below: The dropdown menu can contain two options (MyOrder and Logout). Please do not provide the external stylesheet as it will conflict/mess up my current page. CSS <style> .block [for=s1]{ width: 400px; display: block; margin:5px 0; } .block [for=s2]{ width: 800px; display: block; margin:5px 0; } .center [for=s1]{ text-align: center; } .center [for=s2]{ text-align: center; } label[for=s1]{ display: inline-block; width: 100px; text-align: right; } label[for=s2]{ display: inline-block; width: 70px; text-align: left; } input,textarea [for=s1]{ vertical-align: top; } input,textarea [for=s2]{ vertical-align: left; } .page-header { //background-color: #5E5A80; background-color: #454545; margin-top: 0; //padding: 20px 20px 20px 40px; padding: 5px 5px 5px 5px; } .page-header h1, .page-header h1 a, .page-header h1 a:visited, .page-header h1 a:active { color: #ffffff; font-size: 25pt; text-decoration: none; } input:focus{ border-color: #66afe9; outline: 0; … -
Django user Follow Unfollow Query
I am creating a Blog post application and one of my requirements is that users can follow and unfollow one another. I have created a profile model class for each user and in that I have added the following column to the user model using a many to many field. People Profile Model -> class People(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) following = models.ManyToManyField(to=User, related_name='following', blank=True) photo = models.ImageField(upload_to='profile_pics', blank=True,null=True) Phone_number = models.CharField(max_length=255,null=True,blank=True) Birth_Date = models.DateField(null=True,blank=True) Created_date = models.DateTimeField(auto_now_add=True) Updated_date = models.DateTimeField(auto_now=True) Now I am listing all the posts on a webpage and for each post the author is also mentioned on the template. The requirement is that I need to give a button to follow or unfollow the post author. Now for the first time if the user comes on the page on if the author of the post is already followed that I need to show an unfollow button and for this I need to check every post author followings and make changes to my template as per the response from the DB. This is the Query that I have written -> posts = Post.objects.exclude(users=request.user)\ .select_related('user__people','ProductAvailability').prefetch_related('images_set','Likes')\ .annotate(comments_Count = Count('comments_post',distinct=True)).annotate( Count('Likes',distinct=True),is_liked=Exists( Post.Likes.through.objects.filter( post_id=OuterRef('pk'), user_id=user_id ) ),isSaved=Exists( Post.favourites.through.objects.filter( post_id=OuterRef('pk'), user_id=user_id )), … -
DRF - Merge multiple querysets in one ModelViewSet with different models order by time
I am trying to combine three queryset in one which are from different model classes and trying to get json result ordered by time. Each models have time field. I want to merge all of the fields together and want to make a single queryset that can be send to api end point. models.py class DoseRate(models.Model): device = models.ForeignKey(Device, on_delete=models.CASCADE ,related_name='dose_rates') time = models.DateTimeField(_("Time"), default=timezone.now) cpm = models.IntegerField(_("Counts per minute"), default=0) uSv = models.FloatField(_("Dose rate in uSv"), default=0) time_diff = models.IntegerField(_("Time difference"), default=0) total_counts = models.IntegerField(_("Total counts"), default=0) total_time = models.IntegerField(_("Total time"), default=0) avg_count = models.FloatField(_("Average count"), default=0) std_dev = models.FloatField(_("Standard deviation"), default=0) class GPS(models.Model): device = models.ForeignKey(Device, on_delete=models.CASCADE ,related_name='gps') uSv = models.FloatField(_("Dose rate in uSv"), default=0) time = models.DateTimeField(_("Time"), default=timezone.now) latitude = models.FloatField(_("Latitude"), default=0) longitude = models.FloatField(_("Longitude"), default=0) address = models.CharField(_("Address"), max_length=200, blank=True, null=True, default=None) class DeviceStatus(models.Model): device = models.ForeignKey(Device, on_delete=models.CASCADE, related_name='device_status') time = models.DateTimeField(_("Time"), default=timezone.now) temprature = models.FloatField(_("Temprature"), default=0) frequency = models.IntegerField(_("Frequency"), default=0) voltage = models.FloatField(_("Voltage"), default=0) battery_level = models.IntegerField(_("Battery level"), default=0) serializers.py class AJAXSerializer(serializers.ModelSerializer): class Meta: model = DoseRate # This only provide the data for the avilaible fields fields = ( 'cpm', 'uSv', 'time_diff', 'total_counts', 'total_time', 'avg_count', 'std_dev',) def __init__(self, *args, **kwargs): super(AJAXSerializer, self).__init__(*args, **kwargs) self.request … -
django ORM join statements
I'm learning django queryset API and it's so overwhelming. I'm used to sql statement and I just want a basic join statement where 2 tables join together How can i get this result in shell? SELECT e.emp_lastname,e.emp_firstname,o.job_description FROM hs_hr_employee e INNER JOIN ohrm_job_title o ON e.job_title_code = o.id WHERE e.work_station='101'; hs_hr_employee emp_id,emp_lastname,emp_firstname,work_station,etc... hs_hr_job_title job_id,job_description,etc... -
Need to approve if the user's submitted the request and display the results in the user's page using django rest framework
models.py class Timelog(models.Model): STATUS_CHOICES = [ ('s', 'Submitted'), ('p', 'Approval Pending'), ('a', 'Approved'), ] client=models.ForeignKey(Client,on_delete=CASCADE,related_name='client4',default=None) project=ChainedForeignKey(Project,chained_field="client", chained_model_field="client",show_all=False, auto_choose=True, sort=True) user= models.ForeignKey(User,on_delete=CASCADE,related_name='user2',default=None,blank=True,null=True) job=ChainedForeignKey(Job,chained_field="project", chained_model_field="project",show_all=False, auto_choose=True, sort=True,unique=True) date= models.DateField(default = datetime.date.today) hours=models.DurationField(default=datetime.timedelta(),null=True) status = models.CharField(max_length=20, choices=STATUS_CHOICES,null=False, default='Submitted') class Meta: db_table ='Timelog' def __str__(self): return '{}'.format(self.date) admin.py class Add_Timelog_Admin(admin.ModelAdmin): date_hierarchy = 'date' list_display = ('id','job','project','date','hours','status') list_filter = ['project'] search_fields = ['date'] actions = ['make_approved'] def get_queryset(self, request): qs = super().get_queryset(request) if request.user.is_superuser: return qs return qs.filter(user__id=request.user.id) pass def make_approved(self, request, queryset): queryset.update(status='a') admin.site.register(Timelog, Add_Timelog_Admin) Basically if the user clicks the submitted choice in the status field which will be a button type in the javascript, the status will be shown as submitted in that admin page and it need to shown as approval pending in the users page. Once the admin changes the status to approved it should be shown as approved in users page and it shouldn't be edited by the users after they have submitted it. I have tried using the above code but it seems i couldn't able to acheive the goal. Kindly help to get through this it will be much appreciated, thanks in advance. -
What is the best wat to check if multiple forms in the profile is completely filled or not in Django?
I am working on a project where there are 4 forms and I want to show the profile completed status in percentage. Every form contains fields that are even required=False. Now my question is, how can I get the form is completely filled along the the fields that are not required fields too ? Is their any nice way to do it or just the same that is in my mind.. i.e., to check values individually in views.py using ORM of 4 different Model and then pass parameter to html template ?? -
How to get current user in forms?
I have a form in my Django project. In this form I can assign person. This is my form: class AssignForm(forms.ModelForm): user = forms.ModelChoiceField( queryset=UserProfile.objects.filter(is_active=True) label=_(u'User') ) class Meta: model = Customer fields = ('user',) I want to add another filter in this form. It is company. I get a list of all users in this form but I want to just listing the users that belongs to current user's company. So it should be : queryset=UserProfile.objects.filter(is_active=True, company = current_user.company) But I cannot get requests from forms. How can I handle it?