Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Extending the page in Django
Hi everyone I create my first page extension in Django-cms I save the info buy I can obtain it again my model is like this class PageDescriptionExtension(PageExtension): description_page = models.TextField('description', default = None, help_text = 'Please provide a small description about this page', max_length = 250, ) image = models.ImageField(upload_to='icons') extension_pool.register(PageDescriptionExtension) my admin.py is this class PageDescriptionExtensionAdmin(PageExtensionAdmin): pass admin.site.register(PageDescriptionExtension, PageDescriptionExtensionAdmin) and my toolbar class PageDescriptionExtensionToolbar(ExtensionToolbar): # defines the model for the current toolbar model = PageDescriptionExtension def populate(self): # setup the extension toolbar with permissions and sanity checks current_page_menu = self._setup_extension_toolbar() # if it's all ok if current_page_menu: # retrieves the instance of the current extension (if any) and the toolbar item URL page_extension, url = self.get_page_extension_admin() if url: # adds a toolbar item current_page_menu.add_modal_item(_('Description page'), url=url, disabled=not self.toolbar.edit_mode) no in my template when I try to bet the element {% if request.current_page.pagedescriptionextension %} <img src="{% static request.current_page.pagedescriptionextension.image.url %}"> {% else %} here {% endif %} this code print here I do this in home page request.current_page return home but request.current_page.pagedescriptionextension don't return anything, any idea about that. Thank in advance -
Filtering by dates in django using date picker
I am using Django Chartit to plot graphs from django model ie., django database. The graph is getting created successfully. Now I would like to implement Date Picker, from which I can be able to select the date range. Is there any way I can do it in Django. I was able to filter in Django admin using list_filter. Is there any approach to do it on web page? I found this on stackoverflow link but, It is not that helpful model.py class racktestresult(models.Model): Date = models.DateTimeField() TestCaseID = models.CharField(max_length=255) PassNumbers = models.IntegerField() FailNumbers = models.IntegerField() views.py def reports_chart_view(request): #Column Chart 1 ds = DataPool( series= [{'options': { 'source': racktestresult.objects.all()}, 'terms': [ 'PassNumbers', 'TestCaseID', 'FailNumbers']} ]) cht= Chart( datasource = ds, series_options = [{'options':{ 'type': 'column', 'stacking': True}, 'terms':{ 'TestCaseID': [ 'PassNumbers', 'FailNumbers'] }}], chart_options = {'title': { 'text': 'Test Cases (Pass/Fail)'}, 'xAxis': { 'title': { 'text': 'Test Case Name'}}}) return render( request, "app/report.html", { 'revochart': [cht], } ) report.html <script> $(function() { $( "#datepicker-1" ).datepicker(); $( "#datepicker-2" ).datepicker(); }); </script> <table> <tr> <td> From </td> <td><input type="text" id="datepicker-1" class="datepicker" name="q1" placeholder="MM/DD/YYYY"> </td> <td> To </td> <td><input type="text" id="datepicker-2" class="datepicker" name="q2" placeholder="MM/DD/YYYY"></td> <br> <td><input type="submit" value="Search"></td> </tr> </table> {% load … -
Django REST Framework: upload image and rename it
My frontend application sends me base64-encoded files. Using this code: class Base64ImageField(serializers.ImageField): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.default_error_messages['image_not_png'] = _( 'Only .png files are supported.' ) def to_internal_value(self, data): if isinstance(data, six.string_types): if 'data:' in data and ';base64,' in data: header, data = data.split(';base64,') try: decoded_file = base64.b64decode(data) except TypeError: self.fail('invalid_image') file_name = str(uuid.uuid4()) file_extension = self.get_file_extension(file_name, decoded_file) if file_extension is not 'png': self.fail('image_not_png') complete_file_name = '%s.%s'.format(file_name, file_extension) data = ContentFile(decoded_file, name=complete_file_name) return super().to_internal_value(data) def get_file_extension(self, file_name, decoded_file): return imghdr.what(file_name, decoded_file) I was able to decode and save it to the disk with some randomly generated name. Now I'm wondering how to name that file properly. To elaborate a bit more: A restaurant named 'Uber Restaurant' is sending their logo to my REST backend and what I need, is to save it under the name of uber_restaurant_logo.png for example. Where should I put the code to rename the file? -
Checking for widget attribute in Django templates
I'd need to pass some data from my manually generated form to the template, and would need to check the presence of that information there. I'm generating my form as such (in the __init__ part): for i in days_in_month: self.fields["info_%s" % i] = forms.ChoiceField(label="%s" % i.strftime("%a %d-%m-%Y"), required=False, choices=Information._meta.get_field('info').choices, widget=forms.Select(attrs={'something': 'test'})) What I would like to do, is to check in the template whether the attribute something is set, and if so, display its value (in the example above: test). Any idea? I tried with {{ field.attribute }} as per Access form field attributes in templated Django and the below: {% for field in form %} {{ field.label_tag }} {{ field }} {{ field.widget.attrs.something }} {% endfor %} ... but that doesn't work (invalid). -
How to replace content_type and object_id fields by a field with actual object in admin inline?
I have inline, which shows data of contenttype model, so instead of real objects, I see content_type and object_id fields. I can exclude these fields - this is not a problem, but also I want to get real object as selected with another Places in a dropdown list. Could anyone tell me, how can I do this? Model: class Criterias(models.Model): name = ... class Places(models.Model): name = ... class PlacesToCriterias(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() criteria_group = models.ForeignKey(Criterias) Admin: class CriteriaPlacesInlineAdmin(admin.TabularInline): model = PlacesToCriterias class CriteriasAdmin(admin.ModelAdmin): inlines = [CriteriaPlacesInlineAdmin] admin.site.register(Criterias, CriteriasAdmin) -
How to dynamically change Django query?
For example: class AbstractEndpoint(APIView): def post(self, request): instance = Model.objects.get() if request.user in instance.profile.users.filter(control=True): I want to change it by adding one layer of relations when subclassing: if request.user in instance.parent_model.profile.users.filter(control=True): How can this be done? -
Call Cloud Code function from Django
I'm trying to call Cloud Code from Django using these docs https://parseplatform.github.io//docs/rest/guide/#cloud-code My code from Django is: sess = requests.session() sess.headers['X-Parse-Application-Id'] = 'appID' sess.headers['X-Parse-Master-Key'] = 'masterKey' sess.headers['Content-Type'] = 'application/json' data = {'albumId': 'abc123'} data = json.dumps(data) resp = sess.post('https://api.parse.com/1/functions/testing', data=data) My Cloud Code function is: Parse.Cloud.define("testing", function(request, response) { var albumId = request.params.albumId; console.log('TESTING CALL FROM DJANGO!'); response.success(); }); I'm not getting a response or error message. Is "sess.post" correct? I appreciate the feedback. -
AWS pkg_resources error while deploying
This is my requirements.txt files- awscli==1.11.3 awsebcli==3.7.8 blessed==1.9.5 botocore==1.4.61 cement==2.8.2 colorama==0.3.7 Django==1.10 django-cors-headers==1.1.0 djangorestframework==3.4.3 docker-py==1.7.2 dockerpty==0.4.1 docopt==0.6.2 docutils==0.12 jmespath==0.9.0 lxml==3.6.4 numpy==1.11.1 pandas==0.18.1 pathspec==0.3.4 Pillow==3.3.1 pkg-resources==0.0.0 psycopg2==2.6.2 pyasn1==0.1.9 pymongo==3.3.0 python-dateutil==2.5.3 pytz==2016.6.1 PyYAML==3.12 reportlab==3.3.0 requests==2.9.1 rest-pandas==0.4.0 rsa==3.4.2 s3transfer==0.1.8 selenium==2.53.6 semantic-version==2.5.0 six==1.10.0 texttable==0.8.4 wcwidth==0.1.7 websocket-client==0.37.0 And the logs- Could not find a version that satisfies the requirement pkg-resources==0.0.0 (from -r /opt/python/ondeck/app/requirements.txt (line 20)) (from versions: ) No matching distribution found for pkg-resources==0.0.0 (from -r /opt/python/ondeck/app/requirements.txt (line 20)) You are using pip version 7.1.2, however version 8.1.2 is available. You should consider upgrading via the 'pip install --upgrade pip' command. 2016-10-13 19:00:47,624 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 540, 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 (Executor::NonZeroExitStatus) -
Error installing mysql-python (Windows)for DJANGO
I m using python 3.4, n i have Django. I have installed mysql latest version +mysql workbench. When i try 2 install mysqldb, i get an error saying Visual C++ 2010 is required n can't find it bla bla bla install it from this shit website . I have run these code 1)cd ~/your_project_directory 2) virtualenv env 3)source env/bin/activate 4)pip install django 5)pip install mysql-python i get error on line 3 nd 5 i tried using easy_install located in C:\Python34\Scripts same shit error Visual c++ n shit In Environment Variables in My computer properties my %PATH% is C:\RailsInstaller\Ruby2.2.0\bin;C:\Ruby21\bin;C:\RailsInstaller\Git\cmd;C:\RailsInstaller\Ruby2.1.0\bin;C:\Users\vaibhav2\AppData\Roaming\Composer\vendor\bin;C:\Python34\Scripts;C:\Python34\;C:\Python34\Lib\site-packages;C:\Python34\Lib;C:\Python34\DLLs;C:\Python34\Lib\lib-tk;C:\Program Files\MySQL\MySQL Workbench 6.3 CE;C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Tools;C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC;C:\Users\vaibhav2\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0 %VS90COMNTOOLS% value is (i have Visual studio 2015) VS150COMNTOOLS %PYTHONPATH% is C:\Python34;C:\Python34\Lib\site-packages;C:\Python34\Lib;C:\Python34\DLLs;C:\Python34\Lib\lib-tk;C:\Python34\Scripts **Note i have already read this ** 1) Install mysql-python (Windows) 2) Django mysqlclient install I have already wasted 2 much time reading 2 many articles so plz dont tell me its duplicate ,it isn't+ i have give these articles 2 tell that i have read these articles n then contacted u ppl -
django - subclassing a model just to add new methods
I need to subclass a model from a third-party app (django-oscar). If i do this from oscar.apps.catalogue.models import Category class NewCategory(Category): @property def product_count(self): return self.product_set.all().count() class Meta: db_table = 'catalogue_category' Django will think that it is a multi-table inheritance, and NewCategory is a child model for Category. This will result in errors such as OperationalError at /api/categories/ no such column: catalogue_category.category_ptr_id I can get away with this def product_count(self): return self.product_set.all().count() Category.product_count = product_count but this doesn't seem nice, plus I am unable to add a @property decorator this way. Is there a cleaner way to do this? -
How to squash recent Django migrations?
In Django's migrations code, there's a squashmigrations command which: "Squashes the migrations for app_label up to and including migration_name down into fewer migrations, if possible." So, if you want to squash, say, the first 5 migrations, this will help. What's the best way to squash starting with a particular migration_name? In a project I'm currently working on, we've added 5-10 new migration files as we've added new features. We'll deploy the whole project at once and it looks like running these individually will take too long. I'd like to squash all the migrations for this project into a single migration and test the time to run that. -
Import Pandas on apache server causes timeout error
I've got a Django project working on an Apache server. I installed pandas and want to use it to start manipulating data - however something odd is happening. Anytime I use the import pandas on the production environment, the server will hang up and (after a while) throw a 408 timeout error. I can comment out the pandas portion and the server responds normally without issue. I can't recreate it in the development environment or command line interface with django. Here are the httpd-app.conf file: Alias /tooltrack/static "C:/Users/myfolder/Bitnami Django Stack Projects/tooltrack/static/" <Directory "C:/Users/myfolder/Bitnami Django Stack Projects/tooltrack/static/"> Options +MultiViews AllowOverride All <IfVersion < 2.3 > Order allow,deny Allow from all </IfVersion> <IfVersion >= 2.3> Require all granted </IfVersion> <IfVersion < 2.3 > Order allow,deny Allow from all </IfVersion> <IfVersion >= 2.3> Require all granted </IfVersion> </Directory> WSGIScriptAlias / 'C:/Users/myfolder/Bitnami Django Stack projects/tooltrack/tooltrack/wsgi.py' <Directory "C:/Users/myfolder/Bitnami Django Stack projects/tooltrack/tooltrack"> Options +MultiViews AllowOverride All <IfVersion < 2.3 > Order allow,deny Allow from all </IfVersion> <IfVersion >= 2.3> Require all granted </IfVersion> <IfVersion < 2.3 > Order allow,deny Allow from all </IfVersion> <IfVersion >= 2.3> Require all granted </IfVersion> </Directory> <Directory "C:/Users/myfolder/Bitnami Django Stack projects/tooltrack"> Options +MultiViews AllowOverride All <IfVersion < 2.3 > Order allow,deny … -
What db schema to use with one-to-two correspondence in django?
I know that OneToOneField makes one to one correspondence, and ForeignKey makes one-to-many correspondence. Is there a more efficient way than ForeignKey to store one-to-two correspondence? Thank you. -
Best way to dynamically add multiple abstract class instances to inheriting class instance
I spent quite a bit of time looking for an answer to this question but am unsure of even what it is exactly that I'm looking for. I may even be approaching this entirely wrong by using abstract classes so clarification in any way will be helpful. I want to allow users to add multiple symptoms and treatments to a single disease from within the form template. With my limited knowledge, the only way I can imagine making this work is by having the maximum expected number of symptom and treatment model fields already defined i.e.: class Symptoms(models.Model): symptom_one = models.CharField(max_lenth=20) symptom_one_severity = models.PositiveIntegerField() symptom_two = models.CharField(max_lenth=20, blank=True) symptom_two_severity = models.PositiveIntegerField(blank=True, null=True) etc. This is what I currently have: Models.py class Symptoms(models.Model): symptom = models.CharField(max_lenth=20) symptom_severity = models.PositiveIntegerField() class Meta: abstract = True class Treatments(models.Model): treatment = models.CharField(max_length=20) class Meta: abstract = True class Diseases(Symptoms, Treatments): disease = models.CharField(max_length=20) Forms.py class DiseaseForm(ModelForm): model = Diseases fields = ( 'symptom', 'symptom_severity', 'treatment', 'disease', ) My proposed method isn't very DRY so I'm wondering what is the best way to dynamically add multiple abstract models to an inheriting class? -
Django: Filtering query to a specific id
I have a podcast management website where a user is able to setup his account and after that will be able to create multiple episode from that specific user. After an episode is done, a button will appear where he can see some links that is created automatically for the user to use. The problem I am having is that for every episode, I am trying to show the links for that specific one but it always keeps showing the links from the one I recently created and other episodes that were previously created. This is the button where the user click when the episode has created the links: <a class="btn btn-info box-shadow--6dp" href="{% url 'pf:episodereview' production_id=instance.id %}" role="button"><i class="fa fa-link" aria-hidden="true"></i>&nbsp Review Links</a> The URL pattern in urls.py: url(r'^episodereview/(?P<production_id>[0-9]+)/$', views.EpisodeReview.as_view(), name="episodereview"), This is what happens in views.py: class EpisodeReview(LoginRequiredMixin, ProductionRequiredMixin, ListView): template_name = 'pf/forms_episode_review.html' podcast = None def get(self, request, *args, **kwargs): production_id = kwargs.get('production_id', None) if production_id: production = Production.objects.filter(id=production_id).first() if not production: return self.handle_no_permission() return super(EpisodeReview, self).get(request, *args, **kwargs) def get_queryset(self): return Production.objects.filter(podcast=self.podcast) def get_success_url(self): return reverse('pf:dashboard') And the template where everything is displayed: {% extends "pf/base.html" %} {% load crispy_forms_tags %} {% block content %} <br> … -
Integrate Visa and Mastercard in DJango 1.8 app
I have made a DJango app where I show products, now I want to create a shopping cart where the clients will pay for products and shipping. I found this for visa Visa checkout but i don't how how to use it, and also this for Master Card Master card payment gateway service. I understand that they manage all the security and fraud prevention, that's I'm thinking in an external plugin. As an extra I found this package for PayPal Django-Paypal. Will somebody give me advices or recommend me tutorials for their usage? -
Calling Python Django File in Android Java Code
I'm developing an android app in Java. I was using a php file to interact w/ the database, but I want to use Python Django instead of php. Could I call the python file that interacts with the database in the same way that I called the php file? URL url = new URL("http://10.0.3.2/MYCODE/app/login.php"); String urlParams = "name="+name+"&password="+password; HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setDoOutput(true); OutputStream os = httpURLConnection.getOutputStream(); os.write(urlParams.getBytes()); os.flush(); os.close(); -
How do I create a form in Django based off tables in my non default db?
Let's say I have class A and class B that belong in database Y which is not the default database in my Django application. class A(models.Model): attA = models.CharField(max_length = 1024) class B(models.Model): forA = models.ForgeinKey(A) attB = models.CharField(max_length = 8) class BForm(forms.ModelForm): class Meta: model = B In this case, tables A and B both reside in my non-default database. How do I specify to use this database to look up these tables instead of looking in my default one. In my view I have form = BForm() But I get an error saying Programming error: relation does not exist, since it is looking in my default db and not the alt one where the tables are actually present. How do I resolve this? -
How to define custom relationships between legacy models in Django REST Framework
I am working with some legacy database models in a Django REST Framework application: class Variable(models.Model): var_id = models.AutoField(primary_key=True) resource_type = models.CharField(max_length=1, blank=True, null=True) resource_id = models.BigIntegerField(blank=True, null=True) var_name = models.CharField(max_length=500, blank=True, null=True) class Meta: managed = False db_table = 'variables' class Project(models.Model): project_id = models.AutoField(primary_key=True) name = models.CharField(unique=True, max_length=100, blank=True, null=True) class Meta: managed = True db_table = 'projects' Project and Variable are related models such that when the resource_type of a Variable is 'P', then its resource_id represents the project_id of the Project it belongs to. If the resource_type is something other than 'P, then that Variable belongs to a different type of model. I unfortunately can not make significant changes to the database schema for these models. Is there a way to define a custom relationship between these two models so that I can treat them as if Variable was defined with a ForeignKey to Project? Or as if Project has a ManyToManyField relationship to Variable? I'd ultimately like to be able to create a nested serializer relationship. Something like: class Variable(serializers.ModelSerializer): class Meta: model = models.Variable fields = ('var_id', 'resource_type', 'resource_id', 'var_name') class ProjectSerializer(serializers.ModelSerializer): variables = VariableSerializer(many=True) class Meta: model = models.Project fields = ('project_id', 'name', … -
AbstractUser Login View
I've spent a couple of days on this, read the docs, read some Two Scoops info, and I'm missing something. I'm trying to make a view to log in an AbstractUser. The AbstractUser model is in my_app and the view is in an app called mainsite, that I use to store project-wide views. After the user logs in, they will have access to class-based views that they will use to add, edit, and delete database records. These users are not staff, so I am not giving them access to the admin. Every time I try to log in as a user, authenticate(username, password) (in views.py) returns none. What am I missing? Here's the setup--I have a custom Person model that extends the AbstractUser model: # my_app.models.py class Person(AbstractUser): date_left = models.DateField(blank=True, null=True) phone_number = models.IntegerField(blank=True, null=True) def _full_name(self): return self.get_full_name() full_name = property(_full_name) def __str__(self): return self.get_full_name() class Meta: verbose_name_plural = 'People' I've added Person to settings.py: # settings.py ... AUTH_USER_MODEL = "my_app.Person" ... I have the following URLconf: # project/urls.py from mainsite.views import login_view ... url(r'^login/$', login_view, name='login'), ... This view logs in the user: # mainsite.views.py def login_view(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] … -
How can I get the generated access_token and access_token_secret by twitter for the authenticated user in python-social-auth
I need to get the access_token and access_token_secret for a user which is being authenticated by twitter in Python-Social-Auth. Need to save these in a database for future use. I am using Django framework. -
Django Across All Apps
I am creating a rather large django project which will require two things. 1) I need a few template files to be accessible across all apps. 2) I need a model to be accessible across all apps. How do I go about doing that? As far as the templates are concerned, it seems adding it to the TEMPLATES directive doesn't work. As far as the models are concerned, can I have a models.py in the project/project folder or something like that to be accessible by all apps? Django 1.10 and Python 3.5 TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { [...] -
URL parameters with GET request in django
guys. I'm passing parameters via GET requests to my view. But it seems that django is not properly handling my URL. With parameters longer than one char, it works, but if I use a single char, I get Page not found (404) error. Example: Works: http://localhost:8000/my_url/test Not found: http://localhost:8000/my_url/t urls.py code fragment: url(r'^my_url/(?P<username>\w.+)/$', views.my_url, name='my_url'), Is there any django restriction to the length of parameters passed via GET? Thanks a lot in advance! -
DRF - serialize different models into one
I have several models that have a user as a foreign key. For example, I have model Profile, model profilePic and model userQuestions - in all that models user is foreign key. Is the there a way a can get a profile, a profilePic and userQuestions that corresponds to given user in one single json response ? -
Django + matplotlib : image is not refreshed after new figsave()
I have a model that calls matplotlib to create and save a figure. When the user creates a new object instance, matplotlib creates and save a fig and I return to the user a page that includes the fig.This works. When the user edits the object instance : matplotlib creates a new figure that overrides the existing figure file, this works : I have checked that the figure file is updated on the server. My problem is that the image is not updated in the page returned to the user : the user has to simply refresh the page and then the image is updated. this happens not always : sometimes the image is updated whithout need for refreshing. I wonder if perhaps the page is displayed to fast when the new matplotlib fig is not already saved on the disk. Any idea ? models.py (extract) class Appareil(models.Model): title = models.CharField(max_length=100,default=None, blank=True, null=True) ...............(other fields) ............. def __unicode__(self): return self.title def save(self, *args, **kwargs): self.picture_file_name=figure(self.filed1,self.field2) super(Appareil, self).save(*args, **kwargs) views.py (extract) def figure(field1, field2) : #Init figure fig = plt.figure(figsize=(20, 10),dpi=80, facecolor='w', edgecolor='k') #various matplot commands #........................... #field_png = etc.... picture_file_name = "/static/images/" + file_png + ".png" plt.savefig("static/images/" + fichier_png + …