Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Heroku Django Gunicorn Error H18 (Request Interrupted) errors
I'm using Django with Gunicorn on heroku. And I make https requests via post to my backend sending some files (which don't need to be stored), locally everything works fine. But on heroku when I send small files (<13kbytes) it works, but for larger files I get Error H18 (Request Interrupted). I couldn't understand the reason for the error, if it's from heroku itself, if it's from the body of the request to be large or from gunicorn. What would be the best way to find out the possible cause of this, any ideas? -
How to get the value of manytomany field as a list in Django queryset
class Subject(models.Model): name = models.CharField(max_length=100, blank=True, null=False) category = models.CharField(choices=TYPE_CHOICES, null=True, max_length=50) setting = models.ManyToManyField(Contact) class Contact(models.Model): name = models.CharField(max_length=50, blank=True, null=True) email = models.EmailField(max_length=50, blank=True) id subject_id contact_id 1 66 13 2 66 28 3 71 13 4 71 28 5 98 13 6 98 28 7 98 37 8 20 13 Subject.objects.values('id', 'setting') -> [{'id': 66, 'setting': [13, 28]}, {'id': 71, 'setting': [13, 28]}, {'id': 98, 'setting': [13, 28, 37]}, {'id': 20, 'setting': [13]}] I was wondering how to get the value of manytomany field as a list in Django queryset. The queryset above is the result I want, but I get the output as below. How can I get the value of manytomany field into a list? Subject.objects.values('id', 'setting') -> [{'id': 66, 'setting': [13]}, {'id': 66, 'setting': [28]}, {'id': 71, 'setting': [13]}, {'id': 71, 'setting': [28]}, {'id': 98, 'setting': [13]}, {'id': 98, 'setting': [28]}, {'id': 98, 'setting': [37]}, {'id': 20, 'setting': [13]}] -
How to use serilaizers for django dashboard to fill up the information
create a django application having the functionality of register, login and logout and dashboard screen having profile information (name, email, date of birth, phone number). Connect the app with postgresql database. Note: use serializer for filling up the information. -
how to filter a set of locations during a createview to select one or more locations
I'm stuck on how to approach the design of this problem - or even how to search for answers. I'm still a bit new with Django. The goal is to have a user select one or more locations (libraries in my problem) from a list of locations. I'd like the user to be able to type in an address and then have the list of locations filter based on distance between the locations. I envision the list of locations to be selection field. I'm assuming there will be an input field for the distance (canned choices or just a whole number) and a button to apply the filter. I know how to get the user's location (as a postal address) converted to lat/long using py-geocoder. I have the lat/long of each library. I know how to calculate the distance between two points (py-haverstine or maybe geometry-distance). Where this seems squirrely is the mechanics of filtering the list. How would I do the "filter" action (submit) versus the "save" action if I'm using a model based view? So far, when I hit the server, I've been processing the form as a submission, not a portion. Or would this be better done … -
Bootstrap-Select not updating on mobile
I am using Bootstrap-select for multi-select items with Django. It works fine on desktop, but when the native mobile drop-down is enabled, the selected values of the dropdown do not populate. HTML <!-- start product brand info --> <div class="row"> <div class="col-md-6 col-xs-*"> <div> <label for="id_brand-name" class="form-label">Products</label> </div> <select multiple class="form-control selectpicker mb-3" id="id_brand-name" name="brand-name" mobile="true" multiple required> {% for product in products %} <option value="{{product.id}}" id="optiion">{{ product.brand.name | title }} - {{product.name | title}}</option> {%endfor%} </select> <div class="invalid-feedback"> Select at least one product. </div> </div> </div> <!-- end product info --> <script> //Enble native drop down on mobile window.onload = function () { $('#id_brand-name').selectpicker({ container: 'body' }); if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { $('#id_brand-name').selectpicker('mobile') }}; </script> No matter how many items are selected, the selector always shows Nothing selected. When the data is posted, it is apart of the form though. -
I am getting null value in column "user_id" violates not-null constraint, how can I get foreign key data to register on my comment form?
This my models.py file from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager class UserAccountManager(BaseUserManager): def create_user(self, name, email, password, **other_fields): if not email: raise ValueError('Users must have an email adress') email = self.normalize_email(email) user = self.model(name=name, email=email, password=password) user.set_password(password) user.save() return user def create_superuser(self, name, email, password = None, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) return self.create_user(name=name, email=email, password = password, is_superuser=True) class UserAccount(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=355, unique=False) is_superuser = models.BooleanField(default=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=True) objects = UserAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] def __str__(self): return str(self.id) I have a foreign key on my comment model, I tested this on django admin and it works fine, but with my comment form, the foreign key isn't populating, i just get "null value in column "user_id" violates not-null constraint", I dont know what im doing wrong class Comment(models.Model): comment = models.CharField(max_length=250) user = models.ForeignKey(UserAccount, on_delete=models.CASCADE) def __str__(self): return str(self.user.id) serializers.py from djoser.serializers import UserCreateSerializer from django.contrib.auth import get_user_model from rest_framework.serializers import ModelSerializer from accounts.models import Comment User = get_user_model() class UserCreateSerializer(UserCreateSerializer): class Meta(UserCreateSerializer.Meta): model = User fields = ('id', 'name', 'email', 'password') I am reffering my foreign key user as a … -
Responsive height Plotly&Django&Python&Bootstrap
i need to make chart height inherited (100% parent) You want the chart to take up 100% of the height and 100% of the width of the modal window What are the ways to solve the problem? My code: from plotly.offline import plot import plotly.graph_objects as go ticks = list(range(1, int(data['x'])+1)) fig = go.Figure() for key, val in data['dict'].items(): fig.add_scatter(x=ticks, y=val, name=key) fig.update_layout( xaxis=dict( tickmode='array', tickvals=ticks, ticktext=ticks, title_text='x' ), yaxis=dict( title_text='y' ), autosize=True, ) return plot({'data': fig}, config={'responsive': True}, output_type='div', include_plotlyjs='cdn') My template: <div class="modal-graphic modal fade" id="Graphic" tabindex="-1" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-body"> {% autoescape off %} {{ graphic }} {% endautoescape %} </div> </div> </div> </div> My result: Modal window -
Is there a way do color specific dates in input, type = "date"
I would like to implement reservations. Because of that, some date ranges are already reserved. Is there any way to color specific dates in the pop up that comes out when I click the little calendar icon. I would like to achieve something like this enter image description here where the red dates are already reserved I'm open for any kind of implementation -
Terminal error when I try to runserver in my virtual enviroment
I haven't run my django server in a bit and when I go to run it now I get this error: Traceback (most recent call last): File "/Users/almoni/Desktop/Code/screenplayrules/backend/screenplayrules_django/manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/almoni/Desktop/Code/screenplayrules/backend/screenplayrules_django/manage.py", line 22, in <module> main() File "/Users/almoni/Desktop/Code/screenplayrules/backend/screenplayrules_django/manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? I'm a bit new to django so although I can read the words in the error I don't know what it's trying to tell me if that makes sense. -
Dropdown list in admin registration panel Django
I would like to have a dropdown list in the login field of authenti(fi)cation panel in Django : for admin and for a worker. Do you have any idea how to implement it? -
Slug need to store some text in the admin before it will allow me to see my contents
I'm Using pk in my urls but i change it to slug. But every time i added a new question in my Question model the page throws me an error like this: Reverse for 'view-Question' with arguments '('',)' not found. 1 pattern(s) tried: ['view/(?P[-a-zA-Z0-9_]+)/\Z'] but when i go to the admin and add some text in to the slug field the error is gone and i can be able to see my content in the viewQuestion template and home template. but when I also added a new one the error still appear in my home template. How can i solve this error without adding some text into the slug Field, and gives me the slug url please. class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100, blank=False, null=False) body = RichTextField(blank=False, null=False) category = models.CharField(max_length=50, blank=False, null=False) slug = models.SlugField(unique=True, max_length=50) def __str__(self): return str(self.title) def viewQuestion(request, slug): question = get_object_or_404(Question, slug=slug) answers = Answer.objects.filter(post_id=question) context = {'question':question, 'answers':answers} return render(request, 'viewQuestion.html', context) class My_Question(LoginRequiredMixin, CreateView): model = Question fields = ['title', 'body', 'category'] template_name = 'question.html' success_url = reverse_lazy('index') def form_valid(self, form): form.instance.user = self.request.user return super (My_Question, self).form_valid(form) my urls path('view/<slug:slug>/', views.viewQuestion, name='view-Question'), my home template: <div class="container"> … -
Using django's ORM to average over "timestamp without time zone" postgres field
I'm trying to average over a timestamp without time zone postgres field with django's excellent ORM like so: from django.db.models import Avg ModelName.objects.filter(a_field='some value').aggregate(Avg('time')) However I'm getting: function avg(timestamp without time zone) does not exist LINE 1: SELECT AVG("model_name"."time") AS "time__avg" FROM "m... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. Is there a way to do this with django's ORM?If not, how then do I workaround? -
Graphene mutation defined as null despiete returned value is NonNull
Im working with graphene to handle mutations on an application with django as backend. I wrote the following mutation: import graphene from django.db import transaction from graphql_jwt.decorators import login_required from app1.enums import SomeOptions from app1.models import SomeModel from app2.utils.some_api import SomeApi class SetOtherAppConfig(graphene.Mutation): url = graphene.NonNull(graphene.String) @login_required @transaction.atomic def mutate(self, info, *args, **kwargs): authorization_url = SomeApi().authorization_url user_id = int(info.context.session['_auth_user_id']) company_id = int(info.context.session['id_emp']) SomeModel.objects.get_or_create( company_id=company_id, code=SomeOptions.API.name, defaults={ 'name': SomeOptions.API.value, 'username': '', 'password': '', 'token': '', 'base_url': '', 'others': '', 'created_by_id': user_id, 'updated_by_id': user_id, }, ) return SetSomeConfig(url=authorization_url) The problem is that the mutation itself its being reported as null or string. The attribute url on the other hand can only be String as expected. How can I tell graphene that the mutation(or the class) can not be null? -
Seting Auth headers in Django tests
I am trying to write a test which goes through the signup/login workflow, and then attempts to change the status of a user, which requires them to be logged in. I verified that the first 2 POST requests work (the user is indeed created and then gets a valid auth token after logging in), however I cannot seem to pass in said token in the headers for the 3rd and final POST request. I also checked that the auth_headers variable is indeed set with the correct token, but I keep getting back a 401 status code. Thanks in advance! tests.py from email.headerregistry import ContentTypeHeader from urllib import request from wsgiref import headers from django.http import HttpRequest from django.test import TestCase, Client from rest_framework import status from rest_framework.test import APITestCase from django.urls import reverse from rest_framework.authtoken.models import Token from django.contrib.auth.models import User from profiles_api.serializers import UserProfileSerializer from django.contrib.auth import get_user_model from profiles_api.views import UserLoginApiView client = Client() User = get_user_model() class MyTestCase(APITestCase,UserLoginApiView): def test_add_status_to_profile(self): response = self.client.post("/api/profile/", data={ 'email':"John@gmail.com", 'name':'Pavle', 'password':'password' }) response = self.client.post("/api/login/", data={ 'username':"John@gmail.com", 'password':'password' }) auth_headers = { 'Authorization': 'Bearer ' + response.json()['token'] } response = self.client.post("/api/feed/", content_type='application/json', data={ 'status_text':'Hello world!' }, **auth_headers) self.assertEqual(response.status_code, status.HTTP_201_CREATED) -
Download multiple files with one link as zipped file django
I have a model with multiple files that when I get an object from it I want to be able to download all its related files from one click on anchor as a zip file -
After post or update request, I get 1062, "Duplicate entry '' for key 'crmapp_employees.email'". [Foreign key]
The concept is that I try to post or update a Case. The fields "title", "customer", "assigned_to" and "created_by" is required. Also the "assigned_to" and "created_by", are foreign keys of model Employees with email field as unique.I get the validation error for "title" if it's null but for the others I get the "Duplicate entry" error. The rest of the requests for Employees and Customers are working great.Thanks everybody in advance. Below you'll find the necessary code: -----------MODELS------------------------------ class Employees(models.Model): #auto increment id email = models.EmailField(unique=True) class Customers(models.Model): #auto increment id email = models.EmailField(unique=True, null=True, blank=True) class Cases(models.Model): #auto increment id title = models.CharField(max_length=100) assigned_to = models.ForeignKey( Employees, on_delete=models.PROTECT, related_name='assignee') created_by = models.ForeignKey( Employees, on_delete=models.PROTECT, related_name='creator') customer = models.ForeignKey( Customers, on_delete=models.PROTECT, related_name='cases',null=True, blank=True) -----------Serializers------------------------------ class SimpleEmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employees fields = ['id', 'full_name', ] read_only_fields=('full_name',) full_name = serializers.SerializerMethodField(method_name='get_full_name') def get_full_name(self, obj): return '{} {}'.format(obj.first_name, obj.last_name) class SimpleCustomerSerializer(serializers.ModelSerializer): class Meta: model = Customers fields = ['id', 'full_name',] read_only_fields=('full_name',) full_name = serializers.SerializerMethodField( method_name='get_full_name') def get_full_name(self, obj): return '{} {}'.format(obj.first_name, obj.last_name) class ViewUpdateCaseSerializer(WritableNestedModelSerializer, serializers.ModelSerializer): class Meta: model = Cases fields = ['id', 'category', 'title', 'description', 'customer', 'assigned_to', 'created_by', 'priority', 'status', 'creation_date', 'start_date', 'resolved_date', 'due_date', 'comments', 'cost', 'earning_fixed','earning_percent', 'clear_earning', 'price_without_vat','price_with_vat'] customer = … -
pip3 install cryptography MacOs gives error
the title says it all. This is my error message: ERROR: Command errored out with exit status 1: command: /Library/Developer/CommandLineTools/usr/bin/python3 /Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/site-packages/pip/_vendor/pep517/_in_process.py get_requires_for_build_wheel /var/folders/wy/9tlqy66d5630rd5htpz1dtnr0000gn/T/tmppjwpg3pg cwd: /private/var/folders/wy/9tlqy66d5630rd5htpz1dtnr0000gn/T/pip-install-cz6pcrd6/cryptography Complete output (52 lines): =============================DEBUG ASSISTANCE============================= If you are seeing a compilation error please try the following steps to successfully install cryptography: 1) Upgrade to the latest pip and try again. This will fix errors for most users. See: https://pip.pypa.io/en/stable/installing/#upgrading-pip 2) Read https://cryptography.io/en/latest/installation/ for specific instructions for your platform. 3) Check our frequently asked questions for more information: https://cryptography.io/en/latest/faq/ 4) Ensure you have a recent Rust toolchain installed: https://cryptography.io/en/latest/installation/#rust Python: 3.8.9 platform: macOS-12.0.1-x86_64-i386-64bit pip: 20.2.3 setuptools: 49.2.1 setuptools_rust: 1.3.0 =============================DEBUG ASSISTANCE============================= Traceback (most recent call last): File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/site-packages/pip/_vendor/pep517/_in_process.py", line 280, in <module> main() File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/site-packages/pip/_vendor/pep517/_in_process.py", line 263, in main json_out['return_val'] = hook(**hook_input['kwargs']) File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/site-packages/pip/_vendor/pep517/_in_process.py", line 114, in get_requires_for_build_wheel return hook(config_settings) File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/site-packages/setuptools/build_meta.py", line 146, in get_requires_for_build_wheel return self._get_build_requires( File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/site-packages/setuptools/build_meta.py", line 127, in _get_build_requires self.run_setup() File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/site-packages/setuptools/build_meta.py", line 142, in run_setup exec(compile(code, __file__, 'exec'), locals()) File "setup.py", line 39, in <module> setup( File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/site-packages/setuptools/__init__.py", line 165, in setup return distutils.core.setup(**attrs) File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/site-packages/setuptools/_distutils/core.py", line 108, in setup _setup_distribution = dist = klass(attrs) File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/site-packages/setuptools/dist.py", line 429, in __init__ _Distribution.__init__(self, { File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/site-packages/setuptools/_distutils/dist.py", line 293, in __init__ … -
Exceptions not bubbling up from LiveServerTestCase
We use LiveServerTestCase with Selenium for integration tests of a multi-page user flow. One of the flows is raising an exception at runtime, yet the test is passing. The exception is visible in the test logs, but does not cause the test to fail. Simplified example: class SmokeTest(LiveServerTestCase): def this_should_fail_but_passes(self): driver = webdriver.Chrome() driver.get('/home') # This test passes class HomeView(TemplateView): def get(self, request, *args, **kwargs): raise Exception("You would think the test would fail, but it doesn't.") Test passes, though exception is visible in logs... ... raise Exception("You would think the test would fail, but it doesn't.") Exception: You would think the test would fail, but it doesn't. . ---------------------------------------------------------------------- Ran 1 test in 2.248s OK The root cause seems to be that LiveServerTestCase launches a separate server instance and runtime errors that it experiences are logged, but do not bubble up as exceptions to the test client. -
Using multiprocessing with a dictionary that needs locked
I am trying to use Python's multiprocessing library to speed up some code I have. I have a dictionary whose values need to be updated based on the result of a loop. The current code looks like this: def get_topic_count(): topics_to_counts = {} for news in tqdm.tqdm(RawNews.objects.all().iterator()): for topic in Topic.objects.filter(is_active=True): if topic.name not in topics_to_counts.keys(): topics_to_counts[topic.name] = 0 if topic.name.lower() in news.content.lower(): topics_to_counts[topic.name] += 1 for key, value in topics_to_counts.items(): print(f"{key}: {value}") I believe the worker function should look like this: def get_topic_count_worker(news, topics_to_counts, lock): for topic in Topic.objects.filter(is_active=True): if topic.name not in topics_to_counts.keys(): lock.acquire() topics_to_counts[topic.name] = 0 lock.release() if topic.name.lower() in news.content.lower(): lock.acquire() topics_to_counts[topic.name] += 1 lock.release() However, I'm having some trouble writing the main function. Here's what I have so far but I don't know exactly how the arguments should be passed. def get_topic_count_master(): topics_to_counts = {} raw_news = RawNews.objects.all().iterator() lock = multiprocessing.Lock() with multiprocessing.Pool() as p: Any guidance here would be appreciated! -
Django ORM __in but instead of exact, contains case insensative?
I am currently trying to use the Django ORM to query the Recipe model's ingredients. class Recipe(models.Model): account = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True, blank=True) name = models.TextField(null=True, blank=True) class RecipeIngredients(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, null=True) ingredient = models.TextField(null=True, blank=True) What I have so far is ingredients = ["eggs", "bacon", "potato"] recipes = Recipe.objects.filter( recipeingredients__ingredient__in=ingredients ).alias( ningredient=Count('recipeingredients') ).filter( ningredient__gte=len(ingredients) ) From my understanding of this answer this will return all the items that contain only "eggs", "bacon", and "potato", but not say Eggs or Scrambled EGGS. Is there anyway to adjust this to have it search for all items that contains the ingredients and case insensative? -
Django: Avoid users uploading files, use their local storage instead?
So I have a Python script that extracts data from .ifc (3D models for the AEC Industry) files to a .csv or .xlsx and I would like to make it available in a web app. The files can get pretty big (> 400MB) and users are rarely owners of these files, so they are probably not allowed to upload them. So I am looking for a way to avoid the file upload. Is something like that possible with a Django App? Or should I look into creating a desktop app with some other framework? -
Radio button not saving selected option when refreshed (Django)
i have been having issues with my django ecommerce application one part of my application the user is meant to check a radio button the issue <input class="align-middle h-100" type="radio" name="deliveryOption" id="{{option.id}}" value="{{option.id}}"> my ajax $('input[type=radio][name=deliveryOption]:checked').on('change', function (e) { e.preventDefault(); $.ajax({ type: "POST", url: '{% url "checkout:cart_update_delivery" %}', data: { deliveryoption: $(this).val(), csrfmiddlewaretoken: "{{csrf_token}}", action: "post", }, success: function (json) { document.getElementById("total").innerHTML = json.total; document.getElementById("delivery_price").innerHTML = json.delivery_price; }, error: function (xhr, errmsg, err) {}, }); }); once i check the radio button, everything works fine but once i refresh the page, the selected radio button disappears but the radio button value is still stored in session. how do i fix it in such a way that even though i refresh the page, the selected radio button would still be selected. -
Can Djago create a database query that returns a dictionary of dictionaries?
Can Djago create a database query that returns a dictionary of dictionaries? The model contains a foreign key. Using these keys, I would like to have the query results sorted out. I would then like to provide these results using a rest framework. Illustration model: class Record(BaseModel): evse = models.ForeignKey( 'core.Evse', verbose_name=_('EVSE'), related_name='record_evse', on_delete=models.CASCADE, ) current_rms_p1 = models.FloatField( _('Current RMS P1'), default=0, validators=( MinValueValidator(0), MaxValueValidator((2**16 - 1) * 0.1), ) ) current_rms_p2 = models.FloatField( _('Current RMS P2'), default=0, validators=( MinValueValidator(0), MaxValueValidator((2**16 - 1) * 0.1), ) ) current_rms_p3 = models.FloatField( _('Current RMS P3'), default=0, validators=( MinValueValidator(0), MaxValueValidator((2**16 - 1) * 0.1), ) ) View: class RecordListAPIView(generics.ListAPIView): queryset = Record.objects.all() serializer_class = RecordSerializer def get_queryset(self): return Record.objects.all() How to edit a query to get this result? { "evse 1": [ { "current_rms_p1": 0.0, "current_rms_p2": 0.0, "current_rms_p3": 0.0 }, { "current_rms_p1": 0.0, "current_rms_p2": 0.0, "current_rms_p3": 0.0 } ], "evse 2": [ { "current_rms_p1": 0.0, "current_rms_p2": 0.0, "current_rms_p3": 0.0 } ] } Or this result: [ [ { "evse": 1, "current_rms_p1": 0.0, "current_rms_p2": 0.0, "current_rms_p3": 0.0 }, { "evse": 1, "current_rms_p1": 0.0, "current_rms_p2": 0.0, "current_rms_p3": 0.0 } ], [ { "evse": 2, "current_rms_p1": 0.0, "current_rms_p2": 0.0, "current_rms_p3": 0.0, } ] ] -
widgets for Category choice in Django
I just want add a class 'form control' in category choices class BlogForm(forms.ModelForm): # blog_title= forms.TextInput(label='Title',widget=forms.TextInput(attrs={'class':'form-control'})) # blog_content= forms.Textarea(label='Blog Content',widget=forms.Textarea(attrs={'class':'form-control'})) # blog_image= forms.ImageField(label='Blog Thambnail',widget=forms.ClearableFileInput(attrs={'class':'form-control'})) class Meta: model=Blog fields=['blog_title','category','blog_content','blog_image'] widgets={ 'blog_title':forms.TextInput(attrs={'class':'form-control'}), 'blog_content':forms.Textarea(attrs={'class':'form-control'}), 'category':forms.? 'blog_image':forms.ClearableFileInput(attrs={'class':'form-control'}), } is there any specific input field for that?i have given a question mark there. -
('28000', "[28000] [Microsoft][ODBC SQL Server Driver][SQL Server]Login failed for user 'hostname'
I have successfully deployed my django web application through Microsoft IIS FastCGI. So look wise my website seems to be fine. But after submitting the form on the website I am getting a database mssql error. So in the error, the username after the word USER is showing different from the username I have mentioned in views.py to establish a connection with the database. The username which is visible in the error is actually the hostname of the server on which I am deploying the web app (The sql server is in another server having another hostname). I am not able to figure out why the username is getting changed automatically and then giving an error. P.S - The web application is working fine without the deployment. Error views.py