Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
__init__() got an unexpected keyword argument 'lookup_type'
Please help me why this error coming on remote server but it was work fine on local machine, please find below error sample. Request Method: GET Request URL: https:***********.***?job_function=dir&job_type=parttime&max_experience=100&min_experience=3&name=test&owner_id=571&page_size=10 Django Version: 1.8.14 Exception Type: TypeError Exception Value: __init__() got an unexpected keyword argument 'lookup_type' Exception Location: env/local/lib/python3.4/dist-packages/django/forms/fields.py in __init__, line 245 Python Executable: env/bin/python3.4 Python Version: 3.4.3 Python Path: '/home/deployment/backend', '/home/deployment/backend/env/bin', '/home/deployment/backend', '', '/home/deployment/backend/env/local/lib64/python3.4/site-packages', '/home/deployment/backend/env/local/lib/python3.4/site-packages', '/home/deployment/backend/env/lib64/python3.4', '/home/deployment/backend/env/lib/python3.4', '/home/deployment/backend/env/lib64/python3.4/site-packages', '/home/deployment/backend/env/lib/python3.4/site-packages', '/home/deployment/backend/env/lib64/python3.4/plat-linux', '/home/deployment/backend/env/lib64/python3.4/lib-dynload', '/home/deployment/backend/env/local/lib/python3.4/dist-packages', '/usr/lib64/python3.4', '/usr/lib/python3.4' -
how to hide column in django form and set foreign key value
I want to hide the column bh in the html page so I am hiding it by exclude in forms.py and trying to set foreign key column bh with request.user.username in the views but it is giving me this error: Cannot assign "]>": "Bed.bh" must be a "Hospital" instance. Is there any way to resolve the issue. Please help! `#forms.py class BedForm(forms.ModelForm): class Meta: model=Bed fields = ('bed_id','bed_type','created_date','bh',) exclude=('bh',) if request.method == "POST": form = BedForm(request.POST) if form.is_valid(): bed = form.save(commit=False) bed.created_date = timezone.now() hh = Hospital.objects.filter(hospital_id=request.user.username) bed.bh=hh bed.save() b = Bed.objects.filter(bh=request.user.username) ` -
Surpress naive timezone warnings django
This question was asked suppress django naive datetime warnings But the answer is to stop supporting Time zones. My app has other functionality that will indeed need to support timezones, but I am working on a feature currently that requires raw support for relative time (ie user was online in the past x minutes) If I switch to django.utils.timezone will that throw off relative time? if so, is there another way to squelch this warning? -
using django name 'HttpResponse' is not defined
So brand new to Python, trying to get past this django error: NameError at /hello/ name 'HttpResponse' is not defined Request Method: GET Request URL: http://localhost:61892/hello/ Django Version: 1.11.7 Exception Type: NameError Exception Value: name 'HttpResponse' is not defined Exception Location: c:\users\mblaylock\source\repos\mysite\mysite\mysite\views.py in hello, line 6 Python Executable: c:\users\mblaylock\source\repos\mysite\mysite\env\Scripts\python.exe Python Version: 3.6.2 Python Path: ['c:\users\mblaylock\source\repos\mysite\mysite', 'c:\users\mblaylock\source\repos\mysite\mysite', 'c:\users\mblaylock\source\repos\mysite\mysite\env\Scripts\python36.zip', 'C:\Program Files\Python36\DLLs', 'C:\Program Files\Python36\lib', 'C:\Program Files\Python36', 'c:\users\mblaylock\source\repos\mysite\mysite\env', 'c:\users\mblaylock\source\repos\mysite\mysite\env\lib\site-packages'] Server time: Mon, 13 Nov 2017 18:09:39 +0000 My code is: class views(object): """description of class""" from django.http import HttpResponse def hello(request): return HttpResponse("Hello world") Using visual studio for my IDE on windows 10, if that matters. Thanks in advanced! -
Uploading venv folder on github
Is it necessary to upload venv folder that itself contains 100's of files along with other folders and files of the same project to GitHub? -
Bind dynamic choices to ModelForm in Django
I'm trying to bind a dynamic list of choices to a ModelForm. The form is rendered correctly. However, when using the form with a POST Request, I get an empty form back. My goal is to save that form into the database (form.save()). Any help would be much appreciated. Model I'm using a multiple choice select field ( https://github.com/goinnn/django-multiselectfield ) from django.db import models from multiselectfield import MultiSelectField class VizInfoModel(models.Model): tog = MultiSelectField() vis = MultiSelectField() Forms class VizInfoForm(forms.ModelForm): class Meta: model = VizInfoModel fields = '__all__' def __init__(self,choice,*args,**kwargs): super(VizInfoForm, self).__init__(*args,**kwargs) self.fields['tog'].choices = choice self.fields['vis'].choices = choice View Choices are passed from the view when instantiating the form. def viz_details(request): options = [] headers = request.session['headers'] for header in headers : options.append((header, header)) if request.method == 'POST': #doesnt' get into the if statement since form is empty! #choices are not bounded to the model although the form is perfectly rendered form = VizInfoForm(options, request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/upload') else: #this works just fine form = VizInfoForm(options) return render(request, 'uploads/details.html', {'form': form}) -
Dockerizing existing Django project
I can't wrap my head around how to dockerize existing Django app. I've read this official manual by Docker explaining how to create Django project during the creation of Docker image, but what I need is to dockerize existing project using the same method. The main purpose of this approach is that I have no need to build docker images locally all the time, instead what I want to achieve is to push my code to a remote repository which has docker-hub watcher attached to it and as soon as the code base is updated it's being built automatically on the server. For now my Dockerfile looks like: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install Django RUN pip install djangorestframework RUN pip install PyQRCode ADD . /code/ Can anyone please explain how should I compose Dockerfile and do I need to use docker-compose.yml (if yes: how?) to achieve functionality I've described? -
Avoid changes on FK table Django Models 1.11
This is the way that I modeled my shopping cart. I have a Product table, a "temporary" cart which is deleted after the order is complete. And my CompleteOrders list, which contains the data of each order of the user. The thing is that when I modify the price or the name of my product, it changes on CompleteOrders list too. Is there a way to avoid this? class Product(models.Model): name = models.CharField(max_length=30) price = models.IntegerField() class Cart(models.Model): product = models.ForeignKey(Product) class CompleteOrders(models.Model): product = models.ForeignKey(Product) My approach was to store in CompleteOrder the info of the product instead of using the FK but I didn't see that very optimal. Thanks in advance. -
Sphinx doesn't find project.settings module
When running 'make html' in the sphinx-folder I get the following error-message: File "<frozen importlib._bootstrap>", line 948, in _find_and_load_unlocked ModuleNotFoundError: No module named 'studfest' spinhx-apidoc managed to run fine, and found all the files. It's Django 1.11 and Sphinx 1.6.5. The project has the following structure: studfest-master +--studfest | +--__init__.py | +--settings.py | +--wsgi.py | +-- ... +--templates +--etc The spnix-files are in an adjacent folder. . +--docs +--studfest-master In the conf.py in sphinx, the folders are configured as such: import django import os import sys sys.path.insert(0, os.path.abspath('D:\School\IT1901\final_studfest\test\studfest_master')) os.environ['DJANGO_SETTINGS_MODULE'] = 'studfest.settings' django.setup() Somewhy sphinx is unable to find studfest.settings, any ideas on what might be causing this, and how to fix it? PS: Please my excuse my directory-formatting. -
Django model DateField: How to ensure a two-digit year is saved as "19xx"?
I have a form that takes a user's birthdate. By default, Django accepts three input formats for dates, including MM/DD/YY. However if I enter something like 02/13/45, it saves as 02/13/2045. I've looked through the places I expected to find some threads in the docs but still nothing. Can someone push me in the right direction? -
django admin returns 403 csrf error
I am producing a django/angular project. Django being the backend administration and Angular being the frontend/public display. I have created a Django 1.11 app and loaded all files, installed dependencies, etc. Locally, the site works fine and as expected. Also, since forms will be Angular js I commented out the 'django.middleware.csrf.CsrfViewMiddleware' in my settings.py which I thought would disable the csrf token even being needed, but apparently not. After setting up server and installing files the admin login page appears but I get the following error when I try and login: Forbidden (CSRF token missing or incorrect.): /admin/login/ Any ideas on why this is happening would be greatly appreciated. -
not able to open registration form page
trying to create a registration form, and I am facing an issue. so, below are my python pages: form.py from .models import User from django import forms from django.forms import ModelForm class SignUpForm(ModelForm): class Meta: model = User fields = ('username','password','email') models.py from django.db import models #from django.core.urlresolvers import reverse from django.contrib.auth.models import User class Registration(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) urls.py urlpatterns = [ url(r'^register/$', views.SignUpFormView, name= 'register'), ] test.html {% extends 'user_info/base.html' %} {% block body %} {% block content %} <form method="POST"> {% csrf_token %} {{ form }} username:<br> <input type="text" name="username"><br> password:<br> <input type="text" name="password"><br> email:<br> <input type="text" name="email"><br> <input type="submit" value="Submit" /> </form> {% endblock %} {% endblock %} views.py def SignUpFormView(request): template_name = 'test.html' try: if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') email = form.cleaned_data.get('email') return render(request, template_name, {'form':form}) except ValueError: print("Oops! That was not a valid entry, try again...") else: SignUpForm() return render(request, 'user_info/about.html') The issue is, my "SignUpFormView" function in views.py is not entering the "if" statement, its directly going to "else". I seem to be lost here. I have 'about.html'. I do not see any error as well. Which I find very weird. … -
Django with MySQL deploy on aws ec2
I want to deploy my django with MySQL db for production on aws ec2. Files and db are present on the server. -
website to activate my python scraper using c# and possibly a raspberry pi
I am interested in making a website that activates a python script. I am most familiar with c# but I have a python scraping script I would like to use that currently runs well on my raspberry pi. My question is: How do I make a C# asp.net website that activates the python script? what is the best approach? should i just forget c# all together and use something like django to host the site? -
Errors converting pdf to jpg using wand, Imagemagick, and Django
I am using ImageMagick 6.7.7-10 2017-07-31 Q16 on Ubuntu 14.04, through Wand 0.4.4, Python 3.4.3 and Django 1.11. I am trying to create a jpg thumbnail of a pdf file. On the command line, I can do this with no errors: convert -thumbnail x300 -background white -alpha remove Lucy.pdf[0] output_thumbnail.jpg But when I try to use wand on the same image I get this error: Traceback (most recent call last): File "/home/mark/python-projects/memorabilia-project/memorabilia/models.py", line 24, in make_thumb pages = Image(blob = b) File "/home/mark/.virtualenvs/memorabilia/lib/python3.4/site-packages/wand/image.py", line 2742, in __init__ self.read(blob=blob, resolution=resolution) File "/home/mark/.virtualenvs/memorabilia/lib/python3.4/site-packages/wand/image.py", line 2822, in read self.raise_exception() File "/home/mark/.virtualenvs/memorabilia/lib/python3.4/site-packages/wand/resource.py", line 222, in raise_exception raise e wand.exceptions.MissingDelegateError: no decode delegate for this image format `' @ error/blob.c/BlobToImage/367 I looked at the delegates.xml file for ImageMagic in /etc, and there are entries for pdf files. Thanks for any suggestions on how to get this conversion to work through wand. Mark -
Installing Django when Python is already installed through Anaconda?
I am having the common issue when trying to run: django-admin startproject hellodjango that I am getting the error: 'django-admin' is not recognized as an internal or external command, operable program or batch file. I have run: pip install Django Which ran successfully. However, when I navigate to my C:\Python 3\Scripts folder, I don't see any djangoadmin.py or related files in there. Python 3 is added as a PATH environmental variable. When I run: python --version I get the following: Python 3.6.2 |Anaconda, Inc.| (default, Sep 19 2017, 08:03:39) Could my issue potentially be that my version of python is actually within the Anaconda package, rather than an explicit standalone python installation? (Just a guess as i'm not sure where i'm going wrong). -
Django Modelform OneToOneFielld
I'm currently writing a system in Django where I'd like to save a user at the same time i'm creating another model. Model Code: class MyModel(models.Model): user = models.OneToOneField(User,related_name="profile",primary_key=True) custom_field = models.CharField(...) The model is more elaborate of course, but it shows the setup of the whole thing. Example form: First name: [input] Last name: [input] Email: [input] Password: [pass_input] Custom Text: [text_input] Is this at all possible using a ModelForm? -
django can i name a class as mixin which inherits a view
In django, can I name a class as some mixin while inheriting a View: class MyMixin(FormView): is this correct? -
Django, ReactJS and Webpack
I am creating a login page with Django as backend and ReactJS as frontend. When I start the frontend serv with npm start and execute the login, the api make a post to the Django backend endpoint and works. However, if I start the frontend serv using a Webpack (npm run dev) and execute the login, the same post returns 404. Any ideas why ? What files do you need to see my configuration ? Thanks. -
Django hidden form shown not working
I'm creating a form in Django and Python 2.7. I'm using html to hide a section of the form until a service is selected that needs the new piece of the form. It will be shown but the piece will not work. It won't drop down. Below is what I have in my html page and javascript. <p class="field-wrapper"> <label for="subject" accesskey="S"> <span class="required">Service</span> {{form.service}} </label> </p> <div id="showadditionalphotos"> </div> <div id="showadditionalphotoscontent" class="hidden"> <p class="field-wrapper"> <label for="additionalphotos" accesskey="S"> <span class="required">Additional Photos</span> {{form.additional_photos}} </label> </p> </div> Here is the script. <script> function showadditionalphotos(){ var x = document.getElementById("id_service"); var updatedStatus = x.options[x.selectedIndex].value; console.log('Showing Additional Photos'); if(updatedStatus != "matterport-only"){ console.log('Getting html'); htmlcontent = $('#showadditionalphotoscontent').html(); $('#showadditionalphotos').html(htmlcontent); } else{ $('#showadditionalphotos').empty(); } }; </script> The javascript works great. The hidden field is shown. When I click on it it won't drop down. It is populated with 25 options to choose from. I know this as for once it is shown I inspect the object in the browser and I'm able to see the options I have available to see. Is there a better way to go about Django forms and only showing once that need to be shown once a selection is made? -
How does django's RegexURLPattern __init__ work
I am trying to understand the inner workings of the django framework. Specifically, how URL requests and views function. I'm stuck in understanding how the init method in the RegexURLPattern class works. I'm a beginner with Python as well as django, and I'm not sure what to call this behavior in order to Google it. I'm using the pycharm debugger to step through the code as the django server is starting up and initializing it.From what I understand the initialization process is as follows. To begin the process of initializing the URL pattern the as_view class method is first initialized, it returns the view function url(r'^reset/(?P[0-9A-Za-z_-]+)/(?P[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', PasswordResetConfirmView.as_view( template_name='passreset/pmp_password_reset_confirm.html', ), name='password_reset_confirm') In django.conf.urls init this function receives the url, regex, reference to the view function from step 1 and possibly other arguments def url(regex, view, kwargs=None, name=None): if isinstance(view, (list, tuple)): # For include(...) processing. urlconf_module, app_name, namespace = view return RegexURLResolver(regex, urlconf_module, kwargs, app_name=app_name, namespace=namespace) elif callable(view): return RegexURLPattern(regex, view, kwargs, name) else: raise TypeError('view must be a callable or a list/tuple in the case of include().') in the elif block above a RegexURLPattern object is instantiated. Hitting F7 on the debugger and diving into the object as it is … -
Using JS/Ajax to pass multiple checkboxes to new form/template
It's been suggested to me to use Ajax/JS to pass the selections on the following template that allows the user to select multiple check boxes. Now I'd like for those options to be passed after the user pushes a button, i have multiple groups but i'll keep it simple for this example. If i'm going about this the wrong way let me know and give a suggestion. <div class="container"> <div class="row"> <div class="col"> <h3>Financial</h3> <ul> {% for app in fingrouplist %} <li><input type="checkbox" name="request_reports" value ="{{app.report_id}}" > {{ app.report_name_sc }}</li> {% endfor %} </ul> </div> <div class="col"> I'm using the following to try to pass result of my checkboxes on report_id to a new form and have it pre-populated with these items after hitting my input/submit button. </br></br> <input class="btn btn-primary" type="button" value="Request Access"> Below is my view and as you'll see I have a lot more grouplists that all use report_id and I want all them to be passed to the form that is generated based on these checkboxes. def profile(request): owner = User.objects.get (formattedusername=request.user.formattedusername) reportdetail = QVReportAccess.objects.filter(ntname = owner.formattedusername, active = 1).values('report_name_sc') reportIds = QVReportAccess.objects.filter(ntname = owner.formattedusername).values_list('report_id', flat=True) reportaccess = QvReportList.objects.filter(report_id__in= reportIds).values_list('report_name_sc', flat = True) reportGroups = QVReportAccess.objects.filter(ntname … -
How to change djangos default User Creation Form
I extended the Django User Model and added a required ForeignKeyField called company. Now I also need to Change the default user creation Form. What I tried so far was: Creating a new Form that Inherits from the default UserCreationForm form: class MyUserCreationForm(UserCreationForm): company = forms.ModelChoiceField(queryset=Company.objects.all()) class Meta: model = MyUser fields = ('username', 'company') Adding it to my extended Django Admin: class ExtendedUserAdmin(UserAdmin): add_form = MyUserCreationForm ... admin.site.register(MyUser, ExtendedUserAdmin) This does not work. What am I missing? -
`getattr(self, 'name', False):` V.S. `has(self,'name')
I am learning to compose professioal codes through exploring Django source code. In django.urls.resolvers | Django documentation | Django, it reads: class LocaleRegexProvider(object): def describe(self): description = "'{}'".format(self.regex.pattern) if getattr(self, 'name', False): description += " [name='{}']".format(self.name) return description I assume that getattr(self, 'name', False): can be substituted by more readable code hasattr(self, 'name') For exmaple In [22]: if getattr(str,'split',False): ...: print("Str has 'split' attribute") ...: else: ...: print("Str has not 'split' attribute") ...: Str has 'split' attribute In [25]: if getattr(str,'sp',False): ...: print("Str has 'sp' attribute") ...: else: ...: print("Str has not 'sp' attribute") ...: Str has not 'sp' attribute As for hasattr In [23]: if hasattr(str,'split'): ...: print("Str has 'split' attribute") ...: else: ...: print("Str has not 'split' attribute") ...: Str has 'split' attribute In [24]: if hasattr(str,'sp'): ...: print("Str has 'sp' attribute") ...: else: ...: print("Str has not 'sp' attribute") ...: Str has not 'sp' attribute It seems hasattrshort and readable. There's question about their comparison which do not cover this point. Python hasattr vs getattr - Stack Overflow Is it a better practice to apply getattr() in this context? -
Best practices for storing references to AWS S3 objects in a database?
We store files in Amazon AWS S3, and want to keep references to those files in a Document table in Postgres. I am looking for best practices. We use Python/Django, and currently store the URL that comes back from boto3.s3.key.Key().generate_url(...). But so many issues with that: Must parse the bucket and key out of the URL. Need to urldecode the key name. Doesn't support object versioning. Unicode support is easy to mess up, esp due to the urlencode/decode steps. So, I'm considering storing the Bucket, Key, and Version in three separate fields, and creating the Key as a combination of the DB primary key plus a safely-encoded filename, but didn't know if there were better approaches?