Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: creating new model through ForeignKey without manually inputting ForeignKey
So I have a base model, Parent, with a Child that's already existing in the database. Using a form input, the correct parent and child is queried, and the user is given authentication to continue to the next page if they have the correct input. In a separate app I want to be able to instantiate a new model, Child2, and make sure that it's an instance of Child through another one-to-many relationship. But the Child will have more instances added to it, and the base will as well, so the user could be accessing any one of these instances. How do I ensure that the new Child2 will be an instance of the correct Child/Parent instance that the user is accessing without manually inputting the ForeignKey or pk? For clarification: models.py class Parent(models.Model): parent_name = models.CharField() class Child(models.Model): child_name = models.CharField() parent = models.ForeignKey(Parent, on_delete=models.CASCADE) views.py from .forms import Form def index(request): if request.method == 'POST': form = Form(request.POST) if form.is_valid(): # Use form input to query for the correct parent and child here second models.py from first_app.models import Child class Child2 child_2_name = models.CharField() child = models.ForeignKey(Child, on_delete=models.CASCADE) I was thinking of using a .get() and using a โฆ -
After data model migrated, admin site was not synchronized
I defined data model in models.py and migrated them: In [58]: ! python manage.py makemigrations Migrations for 'forums': forums/migrations/0002_test.py - Create model Test In [60]: ! python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, forums, sessions Running migrations: Applying forums.0002_test... OK models.py class Block(models.Model): name = models.CharField("block name", max_length=100) desc = models.CharField("block description", max_length=100) admin = models.CharField("block admin", max_length=100) class Test(models.Model): name = models.CharField("block name", max_length=100) desc = models.CharField("block description", max_length=100) admin = models.CharField("block admin", max_length=100) However, when I visited admin page, there's no data model there. How to solve such a problem? -
Django Form error: expected string or bytes-like object for datetime object?
I have a very simple django form for renting out keys that defaults a due date for the user, the user can change the date and then go on and save the form. However whenever I save the key_instance, django throws a error: expected string or bytes-like object. I know the datetime object is causing this error because if i comment it out everything works fine. Here is my views.py and forms.py forms.py: class UpdateKeyRequestForm(forms.Form): APPROVE_CHOICES = [ ('d', 'Deny this key request'), ('a', 'Approve this key request') ] request_status = forms.CharField(label='Please select to accept or deny this request.',widget=forms.Select(choices=APPROVE_CHOICES)) due_date = forms.DateField(help_text='Enter a date (YYYY-MM-DD) between now and 4 weeks (default 3). ') def clean_due_date(self): due_date = self.cleaned_data['due_date'] approved_status = self.cleaned_data['request_status'] # Check date is not in past. if due_date < datetime.date.today(): raise ValidationError(_('Invalid date - renewal in past')) if due_date > datetime.date.today() + datetime.timedelta(weeks=4): raise ValidationError(_('Invalid date - renewal more than 4 weeks ahead')) return due_date, approved_status views.py: @permission_required('catalog.can_mark_returned') def update_key_request(request, pk): """ View function for renewing a specific keyInstance by admin """ key_inst=get_object_or_404(KeyInstance, pk=pk) # If this is a POST request then process the Form data if request.method == 'POST': # Create a form instance and populate it โฆ -
AWS + Django + Gunicorn
I am building an environment in AWS to host a django application. I am trying to figure out if I should be using nginx as part of the build. I am listing a few different environments below for example/comparison purposes. All environments make use of an AWS ALB. ENV 1 ALB -> dockercontainer running django +uses inbuilt django webserver, static files working -inbuilt django webserver not made for production use ENV 2 ALB -> dockercontainer running django/gunicorn +uses gunicorn (not django webserver) -static files NOT working ENV 3 ALB -> dockercontainer running django/gunicorn + nginx note: I have not tested this configuration yet. +uses gunicorn (not django webserver) +uses nginx static files should work I read this stackoverflow post and understand the differing roles of gunicorn vs nginx. I am being advised by a colleague that ENV 2 is all I need. That I should be able to serve static files with it. That the ALB provides similar functionality to NGINX. Is this correct? -
TypeError: 'style' is an invalid keyword argument for this function
I am following this tutorial http://www.django-rest-framework.org/tutorial/1-serialization/ And reached at this line .. //...then we restore those native datatypes into a fully populated object instance.// After I try to save the serializers then above TypeError occur. Any help ? -
Unable to install Django-Channel on Django 1.11.13
I am trying to install Django Channel 2.1.1 on Django 1.11.13, but getting some dependency error for async-time package: Collecting channels Using cached https://files.pythonhosted.org/packages/c0/24/f1f1ab62b4b35984d757dd1acbfed0f1c681c79e9beb4d275d18d42d4989/channels-2.1.1-py2.py3-none-any.whl Collecting asgiref~=2.3 (from channels) Using cached https://files.pythonhosted.org/packages/d3/dc/4cb440a69d3e26dfe430955520057c1cde51bc2fd9208215cf6b5662634f/asgiref-2.3.1-py2.py3-none-any.whl Requirement not upgraded as not directly required: Django>=1.11 in ./djangoenv/lib/python3.5/site-packages (from channels) (1.11.13) Collecting daphne~=2.1 (from channels) Using cached https://files.pythonhosted.org/packages/d8/52/f82abaad9c6d8faa863b3c83d524931ae5ba737d8f91bea0bbb1c4eaf8a8/daphne-2.1.1-py2.py3-none-any.whl Collecting async-timeout~=3.0 (from asgiref~=2.3->channels) Could not find a version that satisfies the requirement async-timeout~=3.0 (from asgiref~=2.3->channels) (from versions: 1.0.0, 1.1.0, 1.2.0, 1.2.1, 1.3.0, 1.4.0, 2.0.0, 2.0.1) No matching distribution found for async-timeout~=3.0 (from asgiref~=2.3->channels) Thanks -
Read json file using django python
I have a json file.I want to read json file in django python. Json file contains { "ATM Cash" : ["withdrawal"], "Expense" :["fees","goods","stationery","purchase","material","telephone"], "Income" : ["salary","deposit","rewards"], "Payment" : ["tranfer","payment"], "Medical" : ["dr ", "doctor","dr.","nursing","pharmacist","physician","hospital","medicine"], "Food/Restaurent" :["food","catering"], "Groceries" : ["big bazar"], "Shopping" : ["cloths"], "Mobile recharge" : ["airtel"], "Auto & Fuel" : ["fuel"], "Travel" : ["travel"], "General" : ["others"] } -
resizing image using pil while uploading in django
Checked many other answers and didn't find what am looking for! I'm working on a Django project and I have to let the user upload photos, now I need to resize the photos to fit the place where it will be shown at here are my files : models class Item(models.Model): # custom validators alphanumeric = RegexValidator(r'^[0-9a-zA-Z]*$', 'Only alphanumeric characters are allowed.') # fields dress_name = models.ForeignKey(Name, on_delete='DO_NOTHING', null=False, verbose_name='ูุตู ุงููุณุชุงู',) dress_size = models.ForeignKey(Size, on_delete='DO_NOTHING', verbose_name='ู ูุงุณ ุงููุณุชุงู') dress_color = models.ForeignKey(Color, on_delete='DO_NOTHING', verbose_name='ููู ุงููุณุชุงู') dress_image1 = models.FileField(upload_to='documents/%Y/%m/%d', null=False, verbose_name='ุงูุตูุฑุฉ ุงูุฃุณุงุณูุฉ ูููุณุชุงู', help_text='ูุง ูู ููู ุชุฑููุง ูุงุฑุบุฉ',) dress_image2 = models.ImageField(upload_to='documents/%Y/%m/%d', null=True, verbose_name='ุตูุฑุฉ ุฅุถุงููุฉ ') dress_image3 = models.ImageField(upload_to='documents/%Y/%m/%d', null=True, verbose_name='ุตูุฑุฉ ุฅุถุงูุฉ ') dress_action = models.ForeignKey(Action, on_delete='DO_NOTHING', verbose_name='ุงููุณุชุงู ู ุนุฑูุถ ูู ', help_text='ููุจูุน ุงู ููุฅูุฌุงุฑ ') dress_price = models.IntegerField(default=1, verbose_name='ุงูุณุนุฑ') dress_country = models.ForeignKey(Country, on_delete='CASCADE', verbose_name='ุงูุจูุฏ') dress_city = models.CharField(max_length=80, verbose_name='ุงูู ุฏููุฉ ุงู ุงูู ุญุงูุธุฉ') dress_mobile = models.CharField(max_length=20, validators=[alphanumeric], verbose_name='ุฑูู ุงููุงุชู ') created_by = models.CharField(max_length=250,) created_username = models.CharField(max_length=250, default='unknown') created_at = models.DateTimeField(auto_now=True) dress_active = models.BooleanField(default=False) dress_special = models.BooleanField(default=False) forms class AddDressForm(ModelForm): class Meta: model = Item exclude = ['created_by', 'created_at','dress_active','dress_special','created_username'] def clean_image(self): image = self.cleaned_data.get('image', False) if image: if image._size > 4*1024*1024: raise ValidationError("Image file too large ( > 4mb )") return image else: raise ValidationError("Couldn't read uploaded image") and โฆ -
Django ORM save object with all related fields
In my development I've got in situation when I need to save the model object with the all selected, related objects. Sounds weird but it is useful when you don't know which operations was done with the model object. Example: class User(models.Model): name = models.CharField(max_length=50) class Room(models.Model): user = models.OneToOneField(User) size_x = models.SmallIntegerField() size_y = models.SmallIntegerField() def do_some_stuff(room): room.user.name = "some new name" room = Room.objects.get(id="some_id") do_some_stuff(room) # we didn't know which related_fields would be loaded and modified here room.save() # <- here I want to save the room object and the user (if the user object was fetched or modified from db) Maybe there are some way how I can recursively get the all related objects which was loaded? Thanks. -
Custom Middleware in Django with Exclusions
I require to check authentication via token during execution of certain views, while some views can be accessed without authentication. So, how do i make a middleware and exclude some views from it. Any other idea to solve this is appreciated. -
Django Viewflow: Need to send mail when a task is assigned to any User
I need to send mail to some users when a task is assigned to someone. Viewflow provides signal for flow, tasks (link). But since task assignment is not an independent task in itself, how can we get signal or some other callable? -
`FileNotFoundError`: when issue `python manage.py collectstatic`
When I tried to issue commands to collect staticfiles In [41]: ! python manage.py collectstatic It throw FileNotFoundError: FileNotFoundError: [Errno 2] No such file or directory: '/Users/me/Desktop/Django/forum/static' Nevertheless, there exist file '/Users/me/Desktop/Django/forum/static' In [44]: ! tree -L 2 . โโโ db.sqlite3 โโโ forum โ โโโ __init__.py โ โโโ __pycache__ โ โโโ settings.py โ โโโ static โ โโโ templates โ โโโ urls.py โ โโโ wsgi.py โโโ forums โ โโโ __init__.py โ โโโ __pycache__ โ โโโ admin.py โ โโโ apps.py โ โโโ migrations โ โโโ models.py โ โโโ static โ โโโ templates โ โโโ tests.py โ โโโ urls.py โ โโโ views.py โโโ ll_forum โ โโโ bin โ โโโ include โ โโโ lib โ โโโ pip-selfcheck.json โ โโโ pyvenv.cfg โ โโโ share โโโ manage.py 14 directories, 15 files The setting.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #my apps "forums" ] STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), #notice the comma ) -
unable to upload images with pillow
I tried uploading images from the django admin but the images uploads as an empty image. Here's my settings for my project MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')` And here's my html for my html handler: <div class="row featurette"> <div class="col-md-3 "> <img class="featurette-image img-fluid mx-auto" data-src="holder.js/500x500/auto" src="{crimes.images}" alt="Generic placeholder image" width="200" height="200"> -
Django handle requests with theading
I have a Django project which make predictions on a VM with 2 CPU cores and 8 RAM. When my Django app starts it loads a large file (2.5GB, time to load:10 sec.) with information that the app needs. My app can handle a large amount of concurrent requests till I get error but it only use the 50% of my CPU (1 core), in order to use the 100% of my machines power I need to activate the second core through threading. How can I set the my app so can handle users requests through different threads ? Is there a recommended way to do that or an example ? -
Second field in django admin change list, action form
I would like to include a second input field to the admin action form. something like this. class TestCaseAdmin(AdminAdvancedFiltersMixin, MyModelAdmin): action_form = XForm.ActionForm class XForm(ActionForm): class ActionForm(forms.Form): action = forms.ChoiceField(label=_('Aktion:')) select_across = forms.BooleanField( label='', required=False, initial=0, widget=forms.HiddenInput({'class': 'select-across'}), ) Testsuite_form = forms.ModelChoiceField( required=None, queryset=TestSuiteModel.objects.all(), widget=autocomplete.ModelSelect2(url='testsuite-autocomplete') ) The problem is, i would like to read the data from my second field. The django admin seemes to verride or delete the value of the second field. If you remove the required=None tag, the form is not valid: This is my additional admin action def add_to_Testsuite(modeladmin, request, queryset): #this is triggert before post print("post info") form = XForm(request.POST or None) #add items from query to testsuite #need Testsuitename/XForm.ActionForm.Testsuite_form.value for that output is <XForm bound=True, valid=Unknown, fields=(action;select_across)> -
django 1.11 no changes detected
Hello i am stuck to a point in django migrations i have created a model class in "connection" app's model.py but my ubantu 14.04 terminal still saying while running "python manage.py makemigrations" no changes detected, also i have specify the app name in above command but did't worked. Please help me out. Thanks Here are my migrations: admin [X] 0001_initial [X] 0002_logentry_remove_auto_add analytics (no migrations) auth [X] 0001_initial [X] 0002_alter_permission_name_max_length [X] 0003_alter_user_email_max_length [X] 0004_alter_user_username_opts [X] 0005_alter_user_last_login_null [X] 0006_require_contenttypes_0002 [X] 0007_alter_validators_add_error_messages [X] 0008_alter_user_username_max_length connection [X] 0001_initial contenttypes [X] 0001_initial [X] 0002_remove_content_type_name reports (no migrations) sessions [X] 0001_initial is there anything else is required please ask in comment. And here is the table which i wanna add in db via model.py file of connection app. class Reports(models.Model): user = models.ForeignKey(User, related_name="reports_user") dataset = models.ForeignKey(DatasetRecord, related_name="dataset_record") name = models.CharField(max_length=100) created_date = models.DateTimeField(default=timezone.now, blank=True, null=True) updated_date = models.DateTimeField(default=timezone.now) def __unicode__(self): return '%s' % self.id class Meta: app_label = 'daas' and here is the model.py file code. # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.utils import timezone from django.db import models from daas.models import * # Create your models here. #on_delete=models.DO_NOTHING, class Dbconnection(models.Model): user = models.ForeignKey(User, related_name="db_user") hostname = models.CharField(max_length=50) port = โฆ -
Django: convert this into DetailView - a view function using two parameters from a URL
I'm really happy to discover Class Based Views in Django. It fits my tiny brain better. Now, I came across a situation where I directed users to a page based two parameters from the URL using a function view. views.py def step_detail(request, **kwargs): course_pk = kwargs["course_pk"] step_pk = kwargs["step_pk"] step = get_object_or_404(Step, course=course_pk, pk=step_pk) return render(request, "courses/step_detail.html", {"step": step}) urls.py urlpatterns = [ ... path("courses/<int:course_pk>/<int:step_pk>/", views.step_detail, name='step'), ] The document says that you can only pass "pk" or "slug" into DetailView but here I have two parameters so I am out of luck. By any chance is there still an elegant way to use Class Based Views here? My repo is here: https://github.com/jeremy886/DjangoBasics -
Django ModelForm inheritance and Meta inheritance
I have this ModelForm: class Event(forms.ModelForm): def __init__(self, *args, **kwargs): super(Event, self).__init__(*args, **kwargs) ##Here make some changes such as: self.helper = FormHelper() self.helper.form_method = 'POST' class Meta: model = Event exclude = something... widgets = some settings here also. And this child ModelForm: class UpgradedEvent(Event): def __init__(self, *args, **kwargs): super(UpgradedEvent,self).__init__(*args,**kwargs) class Meta(Event.Meta): model = UpgradedEvent UpgradedEvent is a child of Event model but has some extra fields. How can i inherit all the settings from the Event FORM into UpgradedEvent FORM? When running the above code, it renders the Event form. Is there a way to inherit only the settings inside __init__ ? -
DRF: Pass serializer depth with a GET parameter
It's possible to change a serializer depth with a GET parameter? For example calling http://localhost:8000/api-auth/?depth=1 -
Rendering Html in Django
I get a unicode decode error at / whenever I try to render a simple html page like so.. Below is my views file, with the folder structure at the side and the home.html is very basic html given below. please don't mind its functionality <html> <head> <meta charset="utf-8" /> </head> <body> <h1>Hello World</h1> <p>This is {html_var} coming through</p> </body> </html> Could anyone please help me with this? I've been stuck on it for three days. -
How to run python script on clicking html button from jsp page?
I have python script of sending mail and jsp login page . I want on clicking forgot password that python script of sending mail should run -
Configuring PyCharm Django unit tests with Heroku project
When running all my tests in a shell, I run: heroku local:run python manage.py -e .env-test It works perfectly. I want to run the same tests from PyCharm. On Pycharm menus, I clicked on run > edit configurations to try to create a test conf. I'm asked lots of sh** but not which command to run. How to tell Pycharm : "Just run this same command I'm typing in my shell and don't bother me with lots of options that I don't care?" -
Django Rest Framework detail_route in a ViewSet not accepting multiline docs
Using Django 1.11, DRF 3.7.4 and django-rest-swagger as browsable documentation. I have a @detail_route on a ModelViewSet: class AnalysisViewSet(ModelViewSet): """ API endpoint for analyses retrieve: Return the requested analysis, serialised as json list: Return a list of existing analyses create: Create a new analysis delete: Delete the requested analysis partial_update: Perform a partial update of the requested analysis update: Perform a full update of the requested analysis """ @detail_route(methods=('get', 'post')) def config(self, request, id=None): """ Get or set the configuration for this analysis get: Return the configuration applied by this analysis post: Set the configuration for this analysis """ analysis = self.get_object() if request.method == 'POST': # stuff pass return Response(analysis.config) According to this closed issue, that should generate individual documentation in the browsable API. But it doesn't - it renders the same docstring into both the GET and POST methods (see image). I'm not certain whether the root of this is in django-rest-swagger, or in DRF - can someone confirm that that should work in DRF? -
Display dict index or key name in django template
How do I traverse and display the dict "index name" or "key name" in Django Template? Below is the dict from the context. Basically this is the structure of my dict all_options[category][sub_category][name]. "Category, sub_Category and name" are dynamic. I wanted to display "Category" first then drill down to "Sub Category" then drill further down. Templates doesn't allow using square braces to access the dict attribute. Thanks in advance! Context 'Condenser (WC)': { 'Water Box': { '2MPA Condenser Water Box': { 'option': '2MPA Condenser Water Box', 'chillers': [{ 'chiller': 'xxxxxxxxxxx', 'factory': '2' , 'option': 'WB240.2U.F2HVKA> }, { 'chiller': 'xxxxxxxxxxx', 'factory': '1' , 'option': 'WB088.2H.F2AYFA> }] }, }, 'Anodes': { 'Magnesium Anodes': { 'option': 'Magnesium Anodes', 'chillers': [{ 'chiller': 'xxxxxxxxxxx', 'factory': '2' , 'option': 'WB240.2U.F2HVKA> }, { 'chiller': 'xxxxxxxxxxx', 'factory': '2' , 'option': 'WB240.2U.F2HVKA> }] } }, 'Stainless Steel Tube Sheet': { '304 SS Condenser Tube Sheets': { 'option': '304 SS Condenser Tube Sheets', 'chillers': [{ 'chiller': 'xxxxxxxxxxx', 'factory': '2' , 'option': 'WB240.2U.F2HVKA> }] }, } }, Template In the template, I added a comment and it's the string that needs to be printed. {% for category_name in all_options %} {{ category_name }} #Condenser (WC) {% for subcat in category_name %} {{ โฆ -
DjangoUnicodeDecodeError while getting field
I have faced a problem while I was reading from GEOSGeometry object. I have used this code ds = DataSource(shp file path) lyr = ds[0] for feat in lyr: geom_t = feat.geom.transform(wgs84, clone=True) name =feat.get('name') this code works fine for my shape files.but if name field contains a utf8 string such as 'ุชุณุช' it raises this error DjangoUnicodeDecodeError at /views/importdata/ 'utf-8' codec can't decode byte 0xc8 in position 0: invalid continuation byte. You passed in b'\xc8\xe1\xe6\xc7\xd1 \xc7\xe3\xc7\xe3 \xd1\xd6\xc7' (<class 'bytes'>) Unicode error hint The string that could not be encoded/decoded was: ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ well I find out this is an internal error which is related to gdal or geos wrapper in django. the error comes from this line return force_text(string, encoding=self._feat.encoding, strings_only=True) in field.py in this directory D:\Python\Python36\lib\site-packages\django\contrib\gis\gdal\field.py in as_string is there any way to find a solution for this problem? thanks