Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AWS ElasticBeanStalk Error
I am trying to put a Django based WebApp using ElasticBeanStalk,However in the middle of deployment, I get that there is some error,Please check Log file.I searched the log file but cannot understand the error,Can anybody help me to understand what is happening? Logs: * The following required packages can not be built: * freetype ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-n5etdtzo/matplotlib/ 2017-04-18 02:06:43,611 ERROR Error installing dependencies: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1 Traceback (most recent call last): File "/opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py", line 22, in main install_dependencies() File "/opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py", line 18, in install_dependencies check_call('%s install -r %s' % (os.path.join(APP_VIRTUAL_ENV, 'bin', 'pip'), requirements_file), shell=True) File "/usr/lib64/python2.7/subprocess.py", line 541, in check_call raise CalledProcessError(retcode, cmd) CalledProcessError: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1 (ElasticBeanstalk::ExternalInvocationError) caused by: Requirement already satisfied: appdirs==1.4.3 in /opt/python/run/venv/lib/python3.4/site-packages (from -r /opt/python/ondeck/app/requirements.txt (line 1)) Requirement already satisfied: aws-requests-auth==0.3.0 in /opt/python/run/venv/lib/python3.4/site-packages (from -r /opt/python/ondeck/app/requirements.txt (line 2)) Collecting awscli==1.11.61 (from -r /opt/python/ondeck/app/requirements.txt (line 3)) Using cached awscli-1.11.61-py2.py3-none-any.whl Collecting awsebcli==3.10.0 (from -r /opt/python/ondeck/app/requirements.txt (line 4)) Using cached awsebcli-3.10.0.tar.gz Collecting backports.ssl-match-hostname==3.5.0.1 (from -r /opt/python/ondeck/app/requirements.txt (line 5)) Using cached backports.ssl_match_hostname-3.5.0.1.tar.gz Collecting bdist-mpkg==0.5.0 (from -r /opt/python/ondeck/app/requirements.txt (line 6)) Using cached bdist_mpkg-0.5.0.tar.gz Collecting blessed==1.14.1 (from -r β¦ -
Django Reoder norecaptcha field on allauth signup using crispy forms
I was able to get the noRecaptcha form on my Django-allauth signup form, with the template using crispy forms. Using this answer The question is really about forcing a field order on the crispy form layout, when the form is contained in django-allauth and does not specify a layout (per the author). So when overriding the signup form with a custom form of my own, I've tried to specify a layout, but am not sure I'm getting it recognized. Combining other posts' answers: from django import forms from neatf.users.models import User from nocaptcha_recaptcha.fields import NoReCaptchaField class AllauthSignupForm(forms.Form): captcha = NoReCaptchaField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2', 'captcha'] field_order = ['username', 'email', 'password1', 'password2', 'captcha'] def signup(self, request, user): """ Required, or else it throws deprecation warnings """ pass I'm sure I have the wrong model referenced or it's simply ignored. The noRecaptcha field just sits happily at the top of the form, instead of at the bottom where I'd like it. I've also tried using FormHelper - but must clearly be doing it wrong. helper = FormHelper() helper.form_class = '.form-inline' helper.field_template = 'bootstrap4/layout/inline_field.html' helper.layout = Layout( Fieldset('Contact data', 'username', 'email',), Fieldset('Password', 'password1', 'password2', 'captcha')) I'd β¦ -
Django web app audio file upload validation
I've been searching for a while on how I can validate/scan audio file uploads to my Django web app, which returns user uploads as a list of HTML audio elements. One solution here allows you check that the extension, size etc. is correct but it also explains that a audio library is needed to parse the header. here the solution recommends using a library called Python Audiotools to validate the file. I've installed python audio tools in my virtual environment, but can't seem to get it work correctly. I'm planning on hosting on Heroku and I'm not sure if there's some better solution that I'm overlooking. Anyone experienced in file validation know of an up to date solution? -
How can I implement a nested representation using intermediate model?
I am quite new to Django and Django Rest Framework. What I like to do in my project is display intermediate model's information using ListAPIView and also include detailed information about another Model connected to the intermediate model with a Foreign Key Relationship in the form of nested representation. I have 3 models in my project, User, Content, Bookmark. My model goes like below. class MyUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) username = models.CharField(max_length=50) joined_date = models.DateTimeField(auto_now_add=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) facebook_id = models.CharField(max_length=50, blank=True) is_facebook = models.BooleanField(default=False) is_active = models.BooleanField(default=False) class Content(models.Model): seq = models.CharField(max_length=20, unique=True) title = models.CharField(max_length=100, null=True) start_date = models.DateField(null=True) end_date = models.DateField(null=True) place = models.TextField(null=True) realm_name = models.TextField(null=True) area = models.TextField(null=True) price = models.TextField(null=True) content = models.TextField(null=True) ticket_url = models.TextField(null=True) phone = models.TextField(null=True) thumbnail = models.TextField(null=True) bookmarks = models.ManyToManyField(User, through='Bookmark') The last model, an intermediate model to connect MyUser and Content. class Bookmark(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) content = models.ForeignKey(Content, on_delete=models.CASCADE) created_date = models.DateTimeField(auto_now_add=True) description = models.CharField(max_length=200, null=True) class Meta: unique_together = (('user', 'content'),) ordering = ['-created_date'] def __str__(self): return '{} bookmarked by user {}'.format(self.content, self.user) I want to use BookmarkListAPIView to show certain user's bookmark information and some detailed information of Contents that β¦ -
What is the issue with my django code?
I'm following to this video on youtube (Django Tutorial for Beginners - 13 - Connecting to the Database) I'm trying to display the album titles on the webpage but instead of displaying one album followed by the next album on a different line, it is giving me both albums on the same line and the second album cannot even be clicked on. I suspect there is a problem with my for loop (but I cannot detect it and that is only a guess). I am new to django. I will include the screenshots of my code and the results. If anyone can help it would be greatly appreciated. Thank You Here is my code Here are results -
Incompatible Comparison Error from Filter Length
Question I am getting an incompatible comparison error detailed below, but it's dependent on the size of the string I'm passing to the filter. Anyone know what the cause of or solution to this error would be, or where I can dig in deeper to identify the root-issue? Details When I query filtering with a string of length 255 I receive a False response as I expected (doesn't quite match my inserted column value): >>> from core.models import TestTable >>> test_str = '--publication_filter|920,921,922,923,925,926,927,928,929,930,932,933,934,935,936,937,938,939,940,941,1024,1237,1239,1255,1302,1386,1442,1724,1842,9926,9929,9979,12818,12822,12864,12867,21301,21417,21418,21419,21420,21570,22046,22080,22081,22087,22167,1234' >>> len(test_str) 255 >>> test1 = TestTable.objects.filter(test_column=test_str) >>> test1.exists() False However, with a string of length 256 which I expect return True (matches my inserted column value), it instead raises an error (this test is exactly the same as the one above except test_str is one character longer): Note: I've redacted my path in the traceback below. >>> from core.models import TestTable >>> test_str = '--publication_filter|920,921,922,923,925,926,927,928,929,930,932,933,934,935,936,937,938,939,940,941,1024,1237,1239,1255,1302,1386,1442,1724,1842,9926,9929,9979,12818,12822,12864,12867,21301,21417,21418,21419,21420,21570,22046,22080,22081,22087,22167,12345' >>> len(test_str) 256 >>> test2 = TestTable.objects.filter(test_column=test_str) >>> test2.exists() Traceback (most recent call last): File "<console>", line 1, in <module> File "/[REDACTED]/.venv/local/lib/python2.7/site-packages/django/db/models/query.py", line 565, in exists return self.query.has_results(using=self.db) File "/[REDACTED]/.venv/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 441, in has_results return bool(compiler.execute_sql(SINGLE)) File "/[REDACTED]/.venv/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 818, in execute_sql cursor.execute(sql, params) File "/[REDACTED]/.venv/local/lib/python2.7/site-packages/sql_server/pyodbc/base.py", line 325, in execute return β¦ -
How to define just one revision for updates in several models with django-reversion
I need version my django application in a "per-model" fashion. That is, I have to consider just one version for a series of updates in model instances, so I can identify one version for all that models updates. I think a good package to manage versions in django is django-reversion, but I don't know if it is good to manage revisions considering a revision updates in several different models instead of just one. With low level API to manage revisions I see that I can set a revision block, make changes in more than one model and then set that revision until I start another revision block like (in django-reversion docs). # Declare a revision block. with reversion.create_revision(): # Save a new model instance. obj = YourModel() obj.name = "obj v1" obj.save() # Store some meta-information. reversion.set_user(request.user) reversion.set_comment("Created revision 1") # Declare a new revision block. with reversion.create_revision(): # Update the model instance. obj.name = "obj v2" obj.save() # Store some meta-information. reversion.set_user(request.user) reversion.set_comment("Created revision 2") But I don't know if this way is applied in my case. I'm using djano-rest-framework and for each model that I update I have a class based view, and so I treat an update β¦ -
How do I automatically add time to a datetime field in django models?
I have a Django Model with a start_datetime and a end_datetime. It all works fine, except for the fact that when I save data into the model, it saves it as 2017-04-19 00:00:00 and 2017-04-29 00:00:00. I want to be able to save it as 2017-04-19 00:00:00 and 2017-04-19 23:59:59 automatically, without having to take user input for time again. My models: class ProductNotes(models.Model): start_datetime = models.DateTimeField('Start Date', null=True, blank=True) end_datetime = models.DateTimeField('End Date', null=True, blank=True) How can I do this? -
Inspect django model value before saving
I have a Sandwich model with a list of Ingredients attribute (a many-to-many relationship so I can see Sandwiches using Ingredients and vice-versa). I also have a field has_dairy that I want to set when the model gets saved based on inspecting attributes of the ingredients. Unfortunately, overriding the save method won't cut it, as you can't inspect the value of the many-to-many field without first saving. Else, you get an error. ValueError: "<Sandwich: test sandwich>" needs to have a value for field "sandwich" before this many-to-many relationship can be used. Ideally, I could save, update has_dairy, and save again, but calling super(Sandwich, self).save(*args, **kwargs) in the save method twice throws an integrity error, as it's expecting an unsaved state. How does one accomplish this? -
Web-app or client based application in Python?
After a few years of using plain but functional Tkinter GUIs in my Python apps, I would like to implement a GUI which is more visually appealing. With abundant website creation templates all over the internet with interesting features, graphics and animations, I'm considering to build a 'web app' instead of an executable to take advantage of the variety of beautiful/available templates. Probably Django given that its thriving at the moment. My question is: When is it recommendable to create a webapp rather than a client based app? Are there any particular questions I should be asking myself before taking this decision? The development need is essentially a dashboard which displays a custom mix of information scraped from websites and potentially with some home automation (i.e. touch screen functionality) -
Django cms nested plugins rendered wrong
Although my parent plugin's HTML is defined this way: <div class="parent"> {% for plugin in instance.child_plugin_instances %} {% render_plugin plugin %} {% endfor %} </div> And my child plugin's HTML is defined: <div class="child">...</div> I get the following DOM structure: - parent - child - child - child Instead of the expected: - parent - child - child - child Any reason for the second and third child to be rendered outside of the parent container? -
Processing a HTTP post request using Django and generating a alert box on another page
I am trying to generate a alert box on a page viewed by the user . Here is the scenario: Lets imagine I have 2 templates one is main.html and processing.html,both have their views function defined. Suppose one user is currently viewing main.html in his browser and while he is viewing there is a post request to get Processing.html. So processing.html view function processes that post request and generates some data, Now I want this data to be showed as alertbox in the main page that user is viewing(mainpage.html). Can anybody guide me how to accomplish this? -
Connect Django to live Heroku Postgres database
I've added a Postgres database to my Heroku app, and am trying to connect my Django app to it. However, my app always connects to the local Postgres database instead. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'app_db', 'USER': 'admin', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '', } } db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) I've set 'DATABASE_URL' in the .env file to be the url for the Postgres database on my Heroku app, but it doesn't seem to update the database. How do I force my app to connect to the Heroku database rather than the local one? -
MyModelForm' object has no attribute 'user using django
i want to create i simple django image processing .first i have create correct a django auth and multi upload images in my app. now i want the user can select one self image from a list django form where i create and that image i get for my processing.i create something but not work. i take that error : 'MyModelForm' object has no attribute 'user' here the code : views.py @login_required(login_url="login/") def myview(request): Myf = MyForm(request.user,request.POST) return render(request,'home.html',{'Myf':Myf}) forms.py class MyModelForm(ModelForm): def __init__(self, *args, **kwargs): if 'user' in kwargs: self.user = kwargs.pop('user') super(MyModelForm, self).__init__(*args, **kwargs) choices = [(obj.id, obj.upload.url) for obj in MyModel.objects.filter(user=self.user)] self.fields['upload'].widget = Select(choices=choices) class Meta: model = MyModel fields = ('upload',) if i replace Myf = MyForm(request.user,request.POST) with Myform = MyModelForm(user=request.user) then i think list worked like this image list but i cant take select image for image processing. any idea ? -
Django Models - How do I insert a datetimeoffset preserving the offset
I have a problem when dealing with datetimeoffset and Django. The problem is that I want to insert a row with a datetimeoffset column that must be the result of datetime.now() with the offset being included. For that, I decided to use the following function: def save(self, *args, **kwargs): self.updated_at = timezone.make_aware(datetime.now(),timezone.get_default_timezone()) return super(LoggableModel, self).save(*args, **kwargs) If I print self.updated_at, it returns something like: 2017-04-17 16:59:34.720000-03:00, which is the value I want to be stored, but on my database it is inserted as 2017-04-17 19:59:34.0000000 +00:00. How can I avoid the offset to be added to the final datetimeoffset object? I'm using SQL Server by the way Any ideas on how can this be solved? Thanks. -
Decoding JSON in recordset in Django vView
In my view I'm reading in multiple rows from a database and then returning this data to my template and most of the data is being displayed in the HTML. However, a few of the record columns are n JSON format. I've seen solutions for decoding the JSON data to python in the view, but how do I apply that technique to individual columns in mt record set? -
Opening a django file to process in python 3.6 is running into typeerror
This is what my code looked like in 2.7 report = FileContainerModel.objects.get() lines = report.document.read().splitlines() for line in lines: dostuff(line.split('\t')) And now with the same code I'm running into this error: TypeError: a bytes-like object is required, not 'str' How should I be approaching this? -
Django-url-filter find objects with existing related object
I am using django-url-filter(Link) package to search via URL, For example: example.com/listview/?name__contains=foo But, I have for listview`s model a related field names Task (related_name='tasks') sometimes my model contains related task(s) and sometimes no any. I need to find via url all objects that have one or more tasks. How should I do that? Thank you! -
Domain only accessible on certain browsers
I've deployed a django app with PythonAnywhere and purchased a domain from godaddy. I've followed this guide on pointing the domain to the hosted app https://help.pythonanywhere.com/pages/OwnDomains/ However, when I try to access the domain, it only seems to work on certain browsers. On some, it comes up with a 503 errors, others just a blank page or a godaddy page saying it's parked. Is there something I'm missing? Thanks -
how to use View data to fill in django forms
I have this view: def edit(request): data = {} user = request.user data['requestor'] = user data['user'] = user data['member'] = models.Member.objects.get(User=user) data['Address'] = models.Address.objects.filter(User=user).filter(Primary=True).first() data['Phone'] = models.Phone.objects.filter(User=user).filter(Primary=True).first() data['Family'] = models.Family.objects.filter(Primary=data['member']) data['Sponsor'] = models.Family.objects.filter(Dependent=data['member']).first() data['rank'] = models.Promotion.objects.filter(User=user).latest('Date_Effective') data['form'] = forms.profile return render(request, "member/profile/page_user_edit.html", data) I'm using this form to work with the view. Of note, this form includes fields from multiple models, hence why it's not a modelform: class profile(forms.Form): first_name = forms.CharField(label='First Name', max_length=50, widget=forms.TextInput(attrs={'class': 'md-input'})) last_name = forms.CharField(label='Last Name', max_length=50, widget=forms.TextInput(attrs={'class': 'md-input'})) profile_image = forms.FileField() Street = forms.CharField(label='Street Address', max_length=500, widget=forms.TextInput(attrs={'class': 'md-input'})) City = forms.CharField(label='City', max_length=50, widget=forms.TextInput(attrs={'class': 'md-input'})) State = forms.CharField(label='State', max_length=40, widget=forms.TextInput(attrs={'class': 'md-input'})) Zip = forms.CharField(label='Zip', max_length=20, widget=forms.TextInput(attrs={'class': 'md-input'})) County = forms.CharField(label='County', max_length=20, widget=forms.TextInput(attrs={'class': 'md-input'})) Country = forms.CharField(label='Country', max_length=50, widget=forms.TextInput(attrs={'class': 'md-input'})) Country_Code = forms.CharField(label='Country Code', max_length=5, widget=forms.TextInput(attrs={'class': 'md-input'})) Area_Code = forms.CharField(label='Area Code', max_length=5, widget=forms.TextInput(attrs={'class': 'md-input'})) Number = forms.CharField(label='Phone Number', max_length=20, widget=forms.TextInput(attrs={'class': 'md-input'})) Gender = forms.ChoiceField(choices=choices.GENDER_CHOICES) Height = forms.FloatField(widget=forms.TextInput(attrs={'class': 'md-input'})) HairColor = forms.CharField(max_length=10, widget=forms.TextInput(attrs={'class': 'md-input'})) about = forms.Textarea() facebook = forms.CharField(max_length=50, widget=forms.TextInput(attrs={'class': 'md-input'})) twitter = forms.CharField(max_length=50, widget=forms.TextInput(attrs={'class': 'md-input'})) in the template: <div> <div class="uk-input-group"> <span class="uk-input-group-addon"> <i class="md-list-addon-icon uk-icon-facebook-official"></i> </span> <label>{{ form.facebook.label }}</label> {{ form.facebook }} </div> </div> The label and the form element shows on the page without β¦ -
Django static files 404 (Not Found)
I am trying to include static files not located within the band app, but in a separate directory called static. This directory contains a build directory, which contains CSS & JS directories. Along with the files inside the CSS and JS directories, I'd also like to include minified files such as jquery, react and browser which are inside the bower_components directory. My project structure below: Music/ βββ band/ β βββ migrations/ β βββ __init__.py β βββ admin.py β βββ apps.py β βββ models.py β βββ serializers.py β βββ tests.py β βββ urls.py β βββ views.py βββ music/ β βββ __init__.py β βββ settings.py β βββ urls.py β βββ views.py β βββ wsgi.py βββ node_modules/ βββ static/ βββββ static/ β βββ bower_components/ β βββ build/ β βββ css/ β βββ images/ β βββ js/ βββ templates/ βββ band/ βββ MasterPages/ βββ index.html My settings.py within music contains the following: STATIC_URL = '/static/' STATIC_ROOT = 'C:/Users/Broski/PycharmProjects/Music/static' MEDIA_ROOT = 'C:/Users/Broski/PycharmProjects/Music/upload' This MasterPage.html file is located in the MasterPages directory, under templates: {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <title>Music</title> <link rel="stylesheet" href="{% static 'build/css/main.css' %}" type="text/css" /> </head> <body> {% block content %} {% β¦ -
Cant seem to find the cause of Not Null Failed error
Now I am running into a minor issue and I know it is something small but I am getting programmers block and cant seem to figure out where this error is coming from. I am creating a way to send friends request to other users. What happens is that the person logged in will search fro a user and get directed to their profile. There is then an add friend link that will send the loggedin user record and searched user record. then it will grab both of thier usernames and save them in the database table and add a status. block of code from the relationship.py file: def Send_Valid_Request(User, Request): newRequest = Friends(User_1 = User.Username, User_2 = Request.Username, Status = 1) db_session.add(newRequest) db_session.commit() relationship = db_session.query(Friends).\ filter(and_(Friends.User_1 == User.Username, Friends.User_2 == Request.Username)).\ filter(Friends.Status == 1).\ first() if relationship == None: flash('There was an error with the request') return redirect(url_for('UserProfile', current_user = Request.Username)) else: flash('A request to ' + Request.Username + ' has been sentf') return redirect(url_for('Home')) Here is the table: class Friends(Base): __tablename__ = 'friends' ID = Column(Integer, primary_key = True) User_1 = Column(String(22), nullable = False, index = True) User_2 = Column(String(22), nullable = False, index = True) β¦ -
Python return into HTML file and updating it
people, hope you all are having a lovely day. But let's go to the question, well I am working on a project and I got stuck in a problem, see I am using python, more specifically a library called Beautiful Soup, to do a Web Scraping of a web page, but I realy want to put a specific part of the html into a webpage made by me, and the python code I made can do the getting the specific part thing. However, I to this code to be update everytime the user refresh the page, but I do not know how can I do that, in other words I wanted the python return of a html file be a part of my html file and it could be run evrytime the site begun. I think that writing in a html file from python return from the function could get the code into the html, but how can update it? Can I use a script to do it? Can Django helps? Anything can be useful even if not uses python. -
Django automatic emails not send after migrating from custom server to virtualmin
On a server, i had got a django project that send automatic emails via smtp, here is the configuration that works for my old server EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.lauto-resultat.com' EMAIL_PORT = 25 EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' EMAIL_USE_TLS = False DEFAULT_FROM_EMAIL = 'Auto-resultat mail automatique <no_reply@lauto-resultat.com>' I migrated the project on a new server with virtualmin and now the mails doesn't work I don't understand what's the difference between my old postfix configuration and the virtualmin postfix configuration. The server is a deebian Jessie The django project version is 1.9 And the virtualmin version is the last one Thank you for any response / help. -
how get context react using django
i need get context in react using django but i cant do it this is my code in my jsx <h1>{{titulo}}</h1> <h2>{{ejemplo}}</h2> in my template: {% load staticfiles %} <!DOCTYPE html> <html> <head> <title>Index</title> </head> <body > <div id="app"></div> <script type="text/javascript" src="{% static 'bundle.js' %}"></script> </body> </html> in my view py: def registro (request,giro): reg = 'Registro Normal' if giro==1: reg='Registro Especial' context = { 'ejemplo':'tests', 'titulo':reg } return render(request,'home/registro.html',context) but does not render and wild error appeared :( Uncaught ReferenceError: titulo is not defined