Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Jinja2 templating with components? blocks? templates?
A little question to jinja2 templating: I want to create a reusable template to include and then overwrite blocks. Macros do not let me write junks of HTML easily as parameters do they? Say I want to reuse an include several times and am using BIG junks of HTML in blocks that I want to dynamically assign how would I do it? certainly not with macros I guess, or am I wrong? {% render_foo('bar',2) %} is fine {% render_foo('<table><tr><th>something</th><th>somethingelse</th></tr><tbody><tr>....etc') %} is not fine any more is it "what do you really want to do?" yes, what I told you, I have a way I create containers for my data. The container is ALWAYS the same. The content is completely different on each usage. Once a table. Once a bootstrap component. Once a form. The surrounding elements are always the same to reproduce the simple error this is what I did: {% include 'full_section.html' %} {% block fullsection %} <table><tr><th>something</th><th>somethingelse</th></tr><tbody><tr>....etc{% endblock %} {% include 'full_section.html' %} {% block fullsection %} <form>//some cool LONG big form </form>{% endblock %} full_section.html contents just for completeness, it is a lot more complex in reality <div class="my_cool_full_section"> {% block full_section %}{% endblock %} </div> TemplateAssertionError: … -
How to redirect to the Startup object detail after the user updates/deletes/creates a Post (or cancels in either of the 3 cases)
To use the Django Unleashed schema, suppose the user is on a Startup detail page and starts to create a Post, then decides to cancel. If I wanted the cancel button to redirect to a Startup list, that's easy: href="{% url 'organizer_startup_list' %}" class="button button-primary"> Cancel ...but the user expects it to redirect to the Startup detail. Something like {% url 'organizer_startup_detail' startup.pk %} comes to mind. The problem is there's no startup object in the context. So I need to put the startup object in the context when the user goes to create or update or delete a Post, but the author is using ObjectCreateMixin in the organizer app, so its difficult to customize. His view looks like: class StartupCreate(ObjectCreateMixin, View): form_class = StartupForm template_name = 'organizer/startup_form.html' -
Dashes instead of Date-Time in djangotables2
I am getting dashes in my Django table for all of the columns that are supposed to be showing a date and time. I have found this post, but it did not help me: Dash instead of the date of django-table My table and model code from models.py class Special(CommonHideableModel): API_FILTER_FIELDS = ( "hiddenfield1", "field1", "hiddenfield2", "field2", "date1", "field3", "date2" ) API_FIELDS = API_FILTER_FIELDS field2 = models.CharField(max_length=255,unique=True) def __unicode__(self): return self.field1 ....#more code irrelevant to date and time class SpecialTable (tables.Table): date1 = tables.DateTimeColumn() #I've tried variations permutations of this, including leaving it out all together and moving it to the model. date2 = tables.DateTimeColumn() class Meta: model = Special fields =[ "field1", "field2", "date1", "field3", "date2" ] What else should I try/what am I doing wrong? The non date fields (except for one...different issue...are showing up correctly). -
django models.py - migrating from one model class to another
I am trying to break up an existing model class. The original class is not optimal so I want to move all customer relevant information from CustomerOrder into a new class Customer. What is the best way to do this in Django? Old model class: http://dpaste.com/1W7NW28 New model class: http://dpaste.com/1QB9XC4 There are duplicates in the old model so i want to remove those as well. -
Django page not found when deleting object with foreign key (1 to many)
This is my first time trying to delete objects with a foreign key. The models have a 1 to many relationship: class NumObject(models.Model): title= models.CharField(max_length=50) number= models.IntegerField() ident= models.IntegerField() usersave= models.CharField(max_length=100, blank= True) def __str__(self): return self.title def save(self, *args, **kwargs): super(NumObject,self).save(*args,**kwargs) def get_absolute_url(self): return reverse('posts:detail', kwargs={'id': self.id}) class Sounds(models.Model): numobj = models.ForeignKey(NumObject) title = models.CharField(max_length=50) sound = models.FileField() def __str__(self): return self.title def get_absolute_url(self): return reverse('posts:detail', kwargs={'title': self.title}) The views for the NumObject and Sounds look like this: def post_detail(request,id= None): instance= get_object_or_404(NumObject, id=id) context= { 'title': instance.number, 'instance': instance, } return render(request,'post_detail.html',context) def sound_detail(request,id= None): instancesound= get_object_or_404(Sounds, id=id) context= { 'sound': instance.number, 'instancesound': instancesound, } return render(request,'sound_detail.html',context) in my template, I'm able to display all "Sounds" objects associated with a "NumObject" object by doing this: {% for obj in instance.sounds_set.all %} {% include 'sound_detail.html' %} {% endfor %} sound_detail.html has a ul that displays all the sound objects, as well as a link to the delete view for each sound object: <a href="/{{instance.id}}/delete/">Delete</a> The url for the delete view looks like this: url(r'^(?P<id>\d+)/delete/$', views.post_delete, name= 'delete'), And the delete view: def post_delete(request, id): sound= get_object_or_404(Sounds, pk=id).delete() return redirect('posts:list') For some reason, when I try and delete the individual … -
node js multi part file upload to django not showing my file in request.FILES.get('filename')
I'm using the requests npm library for node js and attempting to do a multipart upload to an api. How can I set up my body of my post request to be properly be recognized by [request.FILES.get('filename')][1] In the django framework? I'm currently formatting my post request as shown below. body = {file_size: bytes ,checksum_sha256: sha256, checksum_md5: md5, part: i} I'm really not sure how to tie declaring the image a file so the django framework recognizes it, naming it, and actually linking the data together with fs.createReadStream(filepath); Any help would be appreciated. -
Django / Django REST Framework: serializer.is_valid() false and can't save web API query to Postgres
When I run from manage.py shell the following: from accounts.views import * c = ExtractCRMDataAPIView() c.crm() It evaluates to Failed. per the code in my views.py. I looked into the conditions where serializer.is_valid will be false per (serializer.is_valid() failing though `required=False` - Django REST Framework), and my model and serializer meet the criteria of optional fields being blank=True and required=False. Furthermore, while I know the query is successful because I can run it in its own crm.py and have it print in the console, this is not saving the web API query result to the database and I am not sure why. Any suggestions? --views.py-- import requests import json from django.contrib.auth import get_user_model from rest_framework.response import Response from rest_framework.status import HTTP_200_OK, HTTP_400_BAD_REQUEST from rest_framework.views import APIView from rest_framework.permissions import ( AllowAny, IsAuthenticated, ) from .models import Accounts from .serializers import UserLoginSerializer, ExtractCRMDataSerializer class ExtractCRMDataAPIView(APIView): permission_classes = [IsAuthenticated] serializer_class = ExtractCRMDataSerializer def crm(self): #set these values to retrieve the oauth token crmorg = 'https://ORG.crm.dynamics.com' #base url for crm org clientid = '00000000-0000-0000-0000-000000000000' #application client id client_secret = 'SUPERSECRET' username = 'asd@asd.com' #username userpassword = 'qwerty' #password authorizationendpoint = 'https://login.windows.net/ZZZZZZZZ-ZZZZ-ZZZZ-ZZZZ-ZZZZZZZZZZZZ/oauth2/authorize' tokenendpoint = 'https://login.windows.net/ZZZZZZZZ-ZZZZ-ZZZZ-ZZZZ-ZZZZZZZZZZZZ/oauth2/token' #oauth token endpoint #set these values to query your … -
How to store data into sqlite database from existing json file in django
Suppose I have .json file {Key1:value, key2:value, key3:value} {Key1:value, key2:value, key3:value} Now I want to store this data into sqlite data which should have one table having fields: Key 1, Key 2, Key 3. How can I save this data into database by writing script? -
How do I create a site where a registered user has a personal url for the site
I'm working on a project and I want to make it in such a way that each registered user has a personal url for the site. For example, a user named james, when logged in, the url will look like this: james.google.com. Just like the same format as wordpress P.S I'm using django -
Is there a way to include multiple javascript files in a django template?
Write now in my Django template I have something that looks like this with like 10 files: <script type="text/javascript" src="{% static "/js/main_1.js" %}"></script> <script type="text/javascript" src="{% static "/js/main_2.js" %}"></script> <script type="text/javascript" src="{% static "/js/main_3.js" %}"></script> What I was wondering was if there was a way to do: <script type="text/javascript" src="{% static ["/js/main_1.js","/js/main_2.js","/js/main_3.js"] %}"></script> and then have python have a minified version of all them. -
Django Randomly generated words (passphrase or mimetic word)
I'm looking for a django package that generate mimetic words. here is the scenario, when a new user finished the registration he will be redirected to a new page where a random sentence of 5 words appears, the user must save this sentence to use it when he want to reset his account password. ** i'm no going to use the email password reset process. -
can't compare datetime.datetime to unicode
I need to compare my input time with current time. If my input time is older than 5 days, I will do d = X_value. Otherwise, d = Y_value. The format of my input time like this: my_input__time: 2017-07-05 22:52:00+00:00 my view.py looks like this: import datetime five_days_ago = datetime.datetime.now() - datetime.timedelta(5) if my_input_time < five_days_ago: d = X_value else: d = Y_value I am getting TypeError:can't compare datetime.datetime to unicode. How do I convert my_input_tine and five_dys_ago into same format so I can compare? -
How to run Python code in djungo
am beginner in Python. I will make my Web Application by python. Am use Django 1.11 and python 3.6 It now i have python 1 file a = 1 if a == 1: print ("Hello World !") print ("ABC") And I need to open and use the code on my web app by Django pleases tell me the how to. Thank you :) -
uploading image to cloudinary using django
im trying to use cloudinary to upload an image in django but i get an error that says 'ascii' codec can't decode byte 0x89 in position 568: ordinal not in range(128). the function for the upload was taken from the docs on cloudinary def upload(request): context = dict( backend_form = ImagesForm()) if request.method == 'POST': form = ImagesForm(request.POST, request.FILES) context['posted'] = form.instance if form.is_valid(): form.save() return render(request, 'capcha/upload.html', context) -
Django App build failing with Visual Studio 2017
I am currently getting this error when Using the Python->Publish feature in Visual Studio 2017 (Enterprise). Severity Code Description Project File Line Suppression State Error Cannot evaluate the item metadata "%(FullPath)". The item metadata "%(FullPath)" cannot be applied to the path "C:\"path to static files"/static [0x7FFA7E7AAB13] ANOMALY: use of REX.w is meaningless %28default operand size is 64%29\%2a%2a\%2a". Illegal characters in path. DCCPWebsite C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\Microsoft\VisualStudio\v15.0\Python Tools\Microsoft.PythonTools.Django.targets 105 It is coming from this line in Microsoft.PythonTools.Django.targets <FilesForPackagingFromProject Include="@(_DjangoStaticFiles)" Condition="'%(FullPath)' != ''"> Any help would be great! Thank you. -
How to modify Django CMS admin panel?
I need to add extra search boxes (like on the picture) that should be chained by AND operator(chained filtering). Any hints on how to do that? I've found that Django CMS admin can be modified via djangocms-admin-style. But how to add new input using it? pic -
push notification in django rest framework apis
How to implement push notification apis in django rest framework. Tried a number of methods and procedures . Looking for complete procedure and code for push notification in django rest framework -
Django Tables 2 - Accessing Fields
I recently upgraded from django-tables (version 1) to djangotables2 in order to upgrade my code to Django 1.11 (from Django 1.6). I have a table containing several fields, and I am trying to access specific fields. The following code is not working in the HTML: <td>{{ item.entered_by }}</td> <td>{{ item.last_updated|date:"m/d/Y j:i a" }}</td> I can iterate through all fields, and all fields will be displayed if I write: {% for field in item%} <td>{{ field }}</td> {% endfor %} However, I only want certain fields to be printed (for instance, the 'entered_by' and 'last_updated') fields. How can I do this/check the field name? I've looked through the documentation here: http://django-tables2.readthedocs.io/en/latest/pages/api-reference.html# without success. -
running celery with specific linux user
I am using celery with Django app. I am using specific user to run the app. I can run django server with specific user - deployer but cant run the celery process with that user. Its starting the celery with root user. So, I cant use environment variable from that user profile (~/.bashrc). Configuration of celery: [program:celery_supervisor] environment=PYTHONPATH=PYTHONPATH:/usr/local/koob/fireball/ direcotry=/usr/local/koob/fireball/ command=/usr/local/koob/fireball/env/bin/python /usr/local/koob/fireball/env/bin/celery -A fireball worker -l info autostart=true autorestart=true user=deployer stderr_logfile=/usr/local/koob/fireball/celery.err.log stdout_logfile=/usr/local/koob/fireball/celery.out.log Configuration of django: [program:fireball_supervisor] directory=/usr/local/koob/fireball/ environment=PLAY_ENV=production command=uwsgi --ini fireball.ini autostart=true autorestart=true stderr_logfile=/usr/local/koob/fireball/fireball.err.log stdout_logfile=/usr/local/koob/fireball/fireball.out.log -
Django/Python url regex with dash
I am trying to create a url with regex settings to allow for all job numbers that are just numeric values, have dashes or that start/contain a letter. My url originally was: url(r'^jobs/(?P<job_number>\w+)/$', JobDashboardView.as_view(), name='job') I attempted to do the following for dashes: url(r'^jobs/(?P<job_number>\w+(-[a-zA-Z0-9]+))/$', JobDashboardView.as_view(), name='job') But it did not work. Any suggestions and if this is even possible? -
Django - Full text search - Wildcard
Is it possible to use wildcards in Django Full text search ? https://docs.djangoproject.com/en/1.11/ref/contrib/postgres/search/ -
Securing a website using Python
I have some questions about how to use Python for security. So: -How to secure a website using Python? -I am a beginner in programming with Python, so are there some tutorials, books or some kind of a guide that can help me with securing my website using this programming language? -I've looked for an answer to my question everywhere and the web framework 'Django' always pops out, could it be the answer to my question? -
Using bootstrap phone input in a Django Form
I am trying to incorporate phone input from Bootstrap, as shown here: http://bootstrapformhelpers.com/phone/ I want to use it in my Django form, but it isn't working for some reason. Here is my relevant code: forms.py class InstructorForm(forms.ModelForm): home_phone = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control bfh-phone'}), max_length=128, label="Home Phone") work_phone = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control bfh-phone'}), max_length=128, label="Work Phone") cell_phone = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control bfh-phone'}), max_length=128, label="Cell Phone") fax = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control bfh-phone'}), max_length=128, required=False, label="Fax") add_new_instructor.html <form id="instructor_form" method="post" action="/schedule/add_new_instructor/"> {% csrf_token %} <div class="row"> {% for field in form %} <div class="col-gl-4 col-md-4"> <div class="form-group"> <strong>{{ field.errors }}</strong> {{ field.label_tag }} {{ field.help_text }} <br> {{ field }} <script></script> </div> </div> {% endfor %} </div> <button type="submit" name="submit">Add New Instructor</button> <button type="submit" name="submit">Reset</button> </form> {% endblock %} {% block custom_javascript %} <script> $(document).ready(function() { $('#id_home_phone').attr("data-format", "+1 (ddd) ddd-dddd"); $('#id_work_phone').attr("data-format", "+1 (ddd) ddd-dddd"); $('#id_cell_phone').attr("data-format", "+1 (ddd) ddd-dddd"); $('#id_fax').attr("data-format", "+1 (ddd) ddd-dddd"); } ); </script> {% endblock %} The form itself is showing, but for some reason, the phone number fields do not work the way they're supposed to in the link and instead treating like it's not even there. There's not even an error showing, and I'm positive that I have all the proper links and … -
Django: activate user-stored language after login
I'm using Python 3.6 and Django 1.11. I'm using Django class-based auth views and custom user model. My users have their language stored in database. I would like to retrieve this language after every login and activate it. I was hoping to do this through user_logged_in signal, but signals cannot affect response in any way, so this is not possible. Another way is to override default auth views, which is something I wanted to avoid. Is there any other way? Thank you. -
Django Rest Framework and Select Lists
Suppose that I have a contact form, in which one of the informations I want my users to supply is the department from a predefined list of values. Using the DRF, what is the best or the correct approach to implement such form? Let's say I'm using Vue or Angular on the front-end. When its time to present the HTML to the user, is it better to query the back-end for the available values, or can I just hardcode the values on the HTML? Although the second approach is the easiest, I think it is not the best, since it will be a lot of work when there's a need changing/adding/removing values from this list (assuming this same select list is used multiple times through the application).