Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
HTML/JS Hide select option by value based on another select value
I'm running a filter for my object on a django-run website. I have two select fields, with dropdowns based on related models to my model that i'd like to sort. The problem is that some options are incompatible with each another and i'd like to hide the options of the second picklist based on what the user has selected on the first one. I feel like i am going to use some JS but i've never used it before. 1st picklist: tasks <option value = task_id> 2nd picklist: crafts <option value = craft_id> I have prepared a dictionnary that holds all the compatible values of any option selected on the first picklist, if that can help ! useful_dictionnary = { first_task_id = [list_of_compatible_craft_ids] ... last_task_id = [list_of_compatible_craft_ids] } How can i get JS to look at the task_id selected on the first picklist, and hide the options from the second picklist that are not in this list ? Would be great! Thanks ! -
Using Datatables with jQuery and ajax for gathering data gives a strange URL
So i'm working on a project where I have been able to fetch data out from the database to a JSON endpoint on my server, looking simular to this: http://some.com/api/herearejson. I then want to load the data into a table and keep refreshing this table every once in a while. I'm using Django as by backend and I have come across a javascript library called Datatables (https://datatables.net) and have been setting it up properly. To sum up what I have done is to create a table in the HTML with the top-row-naming of the table. I then use Datatables-framework in javascript to get the data from the JSON file using an ajax-call provided by the framework, to the endpoint of my app. This is based on the example as shown in the documentation (https://datatables.net/examples/ajax/simple.html): $(document).ready(function() { $('#example').DataTable( { "ajax": "data/arrays.txt" } ); } ); This part works like a charm, however after digging into what is really going on I discovered that whenever I do an Ajax-call the following GET-command is sent XHR finished loading: GET "https://some.com/api/herearejson?_=1492196827012". jquery-1.12.4.js:10254 The same message can be shown in the console when loading the example above. I was wondering if someone can tell me … -
Are there any other reason which can cause 403 error except absence of csrf token in ajax request + django?
The main reason of django + ajax 403 error is absence of csrf token, but in my case it's present and almost the same ajax function works fine. I'll also attach backend view function handling the response using djangorestframework. $.ajax({ url: '/authsteptwo/', type:'POST', dataType: 'json', data: { phone_number : phone_number, email : email, csrfmiddlewaretoken: "{{ csrf_token }}" }, success: function () { // alert('succes'); setTimeout( function() { alert('fine'); }, 0); }, error : function() { alert('fck'); } }) view @api_view(['POST', ]) def auth_step_two(request): if request.method == 'POST': phone_number = request.data['phone_number'] email = request.data['email'] # user = request.user.UserProfile # user.email = email # user.phone_number = phone_number # user.save() else: print("WTF") return Response(request.data) console: Failed to load resource: the server responded with a status of 403 (FORBIDDEN) Are there any other reason which can cause 403 error ? -
Django bootstrap modal forms ajax alternative
I have form in bootstrap modal in django.I want to be able to display form errors wihout having to reload page because this would close modal. I have been asking for solution for this before, and i got AJAX as an answer. Unfortunately this was not successful because i dont really know how to set up ajax, nd just didnt end up liking it. I want to know if there is any ajax "alternative" to display error message without refreshing? I was thinking about json, but dont really know what it is. views.py: SUJECTS = ["subject1", "subject3", "subject55",] @login_required def create_exam(request, letnik_id, classes_id, subject_id): response_data = {} if subject_id in SUBJECTS: path = letnik_id + '/' + classes_id + '/' + subject_id form = ExamForm(request.POST or None, request.FILES or None) if form.is_valid(): exam = form.save(commit=False) exam.exam_user = request.user exam.exam_path = path exam.exam_file = request.FILES['exam_file'] file_type = exam.exam_file.url.split('.')[-1] file_type = file_type.lower() if file_type not in IMAGE_FILE_TYPES: context = { 'error_message': 'File must be PNG, JPG ali JPEG', } return ?? if Exam.objects.filter(exam_path=path, exam_number=exam.exam_number): context = { 'form': form, 'error_message': 'Exam already exists!', } ??return?? exam.save() return redirect('subject_id', letnik_id=letnik_id, classes_id=classes_id, subject_id=subject_id) context = { "form": form } return render(request, 'exam_form.html', context) raise … -
Django: getting related model values through foreign keyfield and print those in the template
I am struggling getting the foreign key values and print them in my template. I know there are a lot of questions that may be similar but I have read those and could not figure out a solution. models.py: class Fixture(models.Model): league = models.ForeignKey('League', blank=True, null=True, related_name="league") starting_time = models.DateTimeField(blank=True, null=True) home_team = models.TextField(blank=True, null=True) away_team = models.TextField(blank=True, null=True) fixture_round = models.TextField(blank=True, null=True) class Meta: db_table = 'fixture' class Score(models.Model): fixture = models.ForeignKey(Fixture, related_name="score") period = models.IntegerField(blank=True, null=True) home_team_score = models.IntegerField(blank=True, null=True) away_team_score = models.IntegerField(blank=True, null=True) class Meta: db_table = 'score' views.py: @method_decorator(login_required, name='dispatch') class InsertedResultsListView(ListView): template_name = 'gamestream/results_list.html' model = Fixture fixtures = Fixture.objects.filter( ).values().order_by( '-starting_time') def get_context_data(self, **kwargs): fixtures = Fixture.objects.filter( ).values().order_by( '-starting_time') context = super(InsertedResultsListView, self).get_context_data(**kwargs) context['fixtures'] = {'fixtures': fixtures[:25]} return context template: {% for fixture in fixtures.fixtures %} {{ fixture.score }} {{ fixture.score_set.all }} {% endfor %} Shouldn't my template code give me access to the foreign key field and its values? What am I doing wrong? Both code lines in the template do not produce anything. Thanks, Vittorio -
How to set up urls in django when there are multiple apps within the same project?
I am new to django. I am trying to setup the URLs. I have 2 apps under a project 'mysite'. In the urls.py for mysite, I have included the urls from the 2 apps (called 'login' and 'org') mysite/urls.py urlpatterns = [ url(r'^login/', include('login.urls')), url(r'^org/', include('org.urls')), ] login/urls.py app_name = 'login' urlpatterns = [ url(r'^signup/$', login_views.signup, name='signup'), ] org/urls.py app_name = 'org' urlpatterns = [ url(r'^organizations/add/$', views.addorg, name='addorg'), ] Having set it up this way, my site URLs become the following: site.com/login/login/signup site.com/org/organizations/add I would like the URLs so that they are like the following. site.com/login/signup site.com/organizations/add How do get the 'includes' to work? Will it work if I change mysite/urls.py to the following? urlpatterns = [ url(r'^$', include('login.urls')), url(r'^$', include('org.urls')), ] Is there a better way to setting up the URLs when there are multiple apps? Thanks -
Django - Filtering objects using ajax post call data returns nothing
I have the following Ajax POST call: $.ajax({ type: "POST", url: "{% url 'meds:prescription' %}", data: {selected:'selected' , csrfmiddlewaretoken: "{{ csrf_token }}"}, success: function(result) { window.location = "{% url 'meds:prescription' %}"; } }); Where selected is an array of ids for example [5, 9, 17] And the following view: class PrescriptionView(generic.ListView): template_name = 'meds/prescription.html' context_object_name = 'meds' model = Medicament def post(self, request, **kwargs): selected_ids = self.request.POST.getlist('selected[]') meds = self.get_queryset().filter(id__in=selected_ids) return render(request, self.template_name, {'meds': meds}) def get_queryset(self): ids = self.request.POST.getlist('selected[]') return Medicament.objects.filter(id__in=ids) def get_context_data(self, **kwargs): ids = self.request.POST.getlist('selected[]') context = super(PrescriptionView, self).get_context_data(**kwargs) context.update({ 'meds': Medicament.objects.filter(id__in=ids), 'date': datetime.now() }) return context What I'm trying to do is just to be redirected to the prescription template with the objects filtered using the data from the post call, but instead my template is just empty, I'm not sure what I'm doing wrong.. -
How to create mysqldb in django in windows 7
Give me the commands in the windows and after installing it how to open the project again and again without any problem -
How to redirect a user if it is superuser one site and if another is active? After login Page not found (404)
do you know how to do this function? I used LOGIN_REDIRECT_URL but now I have two types of users and the two in different views how to redirect them to the corresponding view? Thanks in advance! And I deal with this way in the view: from django.contrib.auth.views import login def my_login(request, user): if request.user.is_superuser: #your logic here return HttpResponseRedirect('/solicitar/home/') if request.user.is_active: #your logic here return redirect("/dashboard/")# or your url name and url global: urlpatterns = [ # Examples: url(r'^solicitar/', include(urls, namespace="usuario")), url(r'^admin/', include(admin.site.urls)), url(r'^grappelli /',include('grappelli.urls')), url(r'^grappelli /',include('grappelli.urls')), url(r'^$', my_login, {'template_name':'login.html'}, name="login"), url(r'^logout/', logout_then_login, name="logout"), But I throw the error: Page not found (404) Request Method: GET Request URL: http://sgi-hrr.herokuapp.com/accounts/profile I should redirect myself to the 'home'. my template login.html: ... <img src=""> <form method="post"> {% csrf_token %} <div class="row"> <div class="col-md-6 col-md-offset-3"> <div class="form-group"> <label for="username">Usuario:</label> <input class="form-control" type="text" name="username" required> </div> </div> </div> <div class="row"> <div class="col-md-6 col-md-offset-3"> <div class="form-group"> <label for="username">Contraseña:</label> <input class="form-control" type="password" name="password" required> </div> </div> </div> <div class="row"> <div class="col-md-6 col-md-offset-3"> <div class="form-group"> <input class="btn btn-primary" type="submit" value="Ingresar"> </div> </div> </div> Help me please! Thanks in advance... -
Creating .env file on the root of the project
I am trying to download a Django project from github and one of the requirements is:"As the project uses python-decouple you will need to create a file named .env on the root of the project with three values, as following: DEBUG=True SECRET_KEY='mys3cr3tk3y' DATABASE_URL='postgres://u_bootcamp:p4ssw0rd@localhost:5432/bootcamp " 1.What(where) is the root part of the project, is it part of the project where are settings? 2.What kind of file should .env be?(python package I suppose) 3.Should name of the file be simply .env(or something.env)? 4.Is .env file going to be imported in settings file? -
Django : how to delete file record after user close his page?
I'm making a simple file resizer with Django, there are 3 fields, email, size, image. After the user arrives to a the last view where he can download what he resized, I'd like Django to erase the image of the ImageField to save space on my Django project whenever an user close his window with the final view page. I do want to keep the email and the size as it is, so these are the only things that shouldn't be deleted. I have no idea where to search, I looked into StackOverflows posts and in Django google groups articles but I could not find something to help me, any suggestion on how this can be done ? -
Django - Defining a child class inside a TestCase
I am packaging an Django app that I would like to reuse (and hopefully can be used by others), and I would like to create a test case that mimics defining a child class when the app is used in different contexts. I found this solution to do something similar in a Python test case, however, I am getting the following error for my Django test case. RuntimeError: Model class tests.test_unit_health.Heart doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. Below is similar to what I have setup that is generating this error: models.py from django.db import models class HealthTest(models.Model): # some attributes... # some methods... def get_score(self, **kwargs): score = self.score(**kwargs) # more logic test_unit_health.py from django.test import TestCase from health.models import HealthTest class HealthTestCase(TestCase): def setUp(self): class Heart(HealthTest): def score(self, heartrate): if heartrate > 90: return 2 else: return 1 The full error looks like this: ====================================================================== ERROR: tests.test_unit_health (unittest.loader.ModuleImportFailure) ---------------------------------------------------------------------- ImportError: Failed to import test module: tests.test_unit_health Traceback (most recent call last): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/loader.py", line 254, in _find_tests module = self._get_module_from_name(name) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/loader.py", line 232, in _get_module_from_name __import__(name) File ".../test_unit_health.py", line 8, in <module> class Heart(HealthTest): File ".../env/lib/python2.7/site-packages/django/db/models/base.py", line 118, in __new__ "INSTALLED_APPS." % … -
How to pass the values from the template as an argument to the function in views?
I want the input entered by user in the template to pass it as arguments to the function which is imported to views.py ..this is the part of that template. <form action="#" method="post"> {% csrf_token %} Ratings: <input type="number" name="rate" step="0.1" min="1" max="5"><br> <input type="submit" value="Submit" name="mybtn"> </form> This is the function I have used to import the function and pass the values as arguments. def request_page(request): users_id = request.user.id + 671 if (request.POST.post('mybtn')): updater.rate_movie(672, 6251, float(request.POST.post('rate'))) -
Celery task running on main thread instead of in celery
I'm trying to run a celery task in a new project. The function process_request always runs on the main thread so the browser always waits for the task to finish and never even touches celery. I'm sure i'm missing something quite simple here. Here's the code i think is important ######## settings.py ###### INSTALLED_APPS += ['myapp.taskapp.celery.CeleryConfig'] CELERY_RESULT_BACKEND = 'amqp://me:password@localhost:5672//' ######### celery.py ####### app = Celery('monitoring') class CeleryConfig(AppConfig): name = 'monitoring.taskapp' verbose_name = 'Celery Config' def ready(self): # Using a string here means the worker will not have to # pickle the object when using Windows. app.config_from_object('django.conf:settings') installed_apps = [app_config.name for app_config in apps.get_app_configs()] app.autodiscover_tasks(lambda: installed_apps, force=True) @app.task def process_request(): url = "http://www.google.com" sleep(5) response = requests.get(url) print response.status_code ######### views.py ###### def test(request): process_request.delay() return HttpResponse("done") -
html bootstrap dropdown menu getting reset
I have dropdown menu in 'index.html` like <div id="navbar" class="navbar-collapse collapse"> <form class="navbar-form navbar-right"> <div class="dropdown"> <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Menu <span class="caret"></span></button> <ul class="dropdown-menu"> <li><a href="{% url 'item1' %}">Item1</a></li> <li><a href="{% url 'item2' %}">Item2</a></li> </ul> </div> </form> </div><!--/.navbar-collapse --> And when I click on Item2 dropdown menu brifely sets to Item2 and then back to Menu. In my item2.html I am calling index.html like {% extends 'index.html' %} {% block content %} ... {% endblock %} I think after clicking on item2 href it rightly calls item2.html but also calls index.html when then renders dropdown menu again with value Menu, how can I keep dropdown value set to selected one? -
Unable to convert unicode to float in django POST
I have a simple form form action="#" method="post" name="rate_movie"> {% csrf_token %} Ratings: <input type="number" name="rate" step="0.1" min="1" max="5"><br> <input type="submit" value="Submit" name="mybtn"> </form> I am able to grab the value from the input using v = request.POST.get('rate') in my views.py but the type of 'v' is unicode and unable to convert it to float where i use it to store the ratings. TIA -
Sending out a csv attachment with Django Email, is forcing the COLUMN_HEADERS into the next row
Steps to reproduce: 1) Get a LONG line of comma separated values (mine starts balking at 998 characters). 2) Send that out through Django Email: message.attach('some.csv', csv_file, 'text/csv') 3) Open file in email, and notice that your values have been written to the second row, instead of staying all on one row. Input/Output Input: csv_file = 'FIELD_1,FIELD_2,FIELD_3,...,FIELD_998, FIELD_999' Expected Output (all on one row): FIELD_1 | FIELD_2 | FIELD_3 | ... | FIELD_998 | FIELD_999 Actual Output: FIELD_1 | FIELD_2 | FIELD_3 | ... | FIELD_ 998 | FIELD_999 (Please note this is an example, it starts to balk at 998 char's not specifically strings) -
Serving GAE Django project static files another bucket, not defoult bucket
I am developing Django project on GAE(Google App Engine). python2.7 Django1.8 I want to upload image file from my django app to Google Storage Bucket.So I create a buccket on Google and added these configurations to settings.py DEFAULT_FILE_STORAGE = 'storages.backends.gs.GSBotoStorage' GS_ACCESS_KEY_ID = 'YourID' GS_SECRET_ACCESS_KEY = 'YourKEY' GS_BUCKET_NAME = 'YourBucket' STATICFILES_STORAGE = 'storages.backends.gs.GSBotoStorage' When I run python manage.py collectstatic Django collect all static files and send to my GS bucket and when project is running on local machine, Django can find static files. When I deploy this project to GAE project works but Django can't find static files. There is a conflict. GAE can serve static files in its private bucket so, Django(on GAE) search static files in its private bucket, not mybucket. I think, I must modify app.yaml file in project. But documentation an tutorials are not enough about Django on GAE. i'd appreciate it if anybody help -
How to add custom User model to Registrationform in Django?
I have done a lot of research these days but just dont get how it is done. So I have the basic User model and Profile model as shown below: class Profile(models.Model): user = models.OneToOneField(User, null=True) address= models.CharField(max_length=100) posts = models.IntegerField(max_length=100) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() my forms.py class RegistrationForm(UserCreationForm): class Meta: model = User fields = {'username','email', 'password1', 'password2', 'first_name', 'last_name'} class UserProfileForm(forms.ModelForm): class Meta: model = Profile views.py def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): user = form.save(commit=False) username = form.cleaned_data['username'] user.save() user = authenticate(username=username) return redirect('/home') else: form = RegistrationForm() args = {'form' : form} return render(request, 'home/reg_form.html', args) How can I make a registrationform with the fields of User + the fields of Profile model? Thanks for your help in advance -
Unable to add additional scope params to access youtube data using django-allauth?
I am unable to generate oauth token in django-allauth to access youtube. According to the docs, here are my current additional parameters SOCIALACCOUNT_PROVIDERS = { "google": { "scope":[ 'profile', 'email' 'youtube' ], "AUTH_PARAMS":{ 'access_type':'online', } }, } Profile and email are working fine, but i get the following error { "error": { "errors": [ { "domain": "global", "reason": "insufficientPermissions", "message": "Insufficient Permission" } ], "code": 403, "message": "Insufficient Permission" } } When i make a call to list out all channels owned by that user. Where am i going wrong with this ? Reference Reference for google scope Docs for channel api call -
Django - How to access list by forloop.parentloop.counter in template
I have this code {% for time in listOfTimes%} {% for booking in someOtherList.forloop.parentloop.counter0 %} {{booking}} {% endfor%} {% endfor %} The booking variable does not get printed. I think this was because I cannot access someOtherList by using the forloop counter. How would I get the 'booking' value? -
How to get files stored in Elastic Beanstalk instance?
I have a django (1.10) app running in Elastic Beanstalk. I want to dump some apps data to fixtures and download these fixtures to my local machine (to replicate in my local database). So far, I've eb ssh'ed into my instance and dumped the data to ~/myapp_current.json. But I can not find a way to copy the file to my local machine. There is no eb scp command. -
Django URL Case issue
I'm using the following regex to build my urls as follows: ...templates/file url(r'^(?P<slug>[\w-]+)/$', views.template_type, name="template"), url(r'^(?P<template>[\w-]+)/(?P<slug>[\w-]+)/$', views.template_file, name="file"), The first line in here works fine pulling the slug field from the template model. It's the second line where I have the problem. In the second line the slug is pulled from a File Model field template is pulled from a Foreign Key field in the File Model of the Template Model Although everything is working almost fine. The Foreign Key pulls the title rather than the slug from the Template Model making the url case insensitive. eg website.com/template - works fine but then goes to website.com/Template/file that also works, but if a user deleted the file from the url to try to go back to website.com/Template they would get a 404 error. I hope that makes sense. I've tried making the urls case insensitive with (?i) but that has not worked. Thanks -
django.apps get_model() method usage
How to use django.apps.get_model() in a django project. When I try to use it, it is giving me an error : Models aren't loaded yet What should I do to to properly use it. Note: I know that I can use import or something else, but I want to know how to fully use apps.get_model() Thanks in advance -
Why is the stack trace when using Jinja2 templates with Django not as specific as with the default Django template engine?
I have installed the latest version of the django-jinja plugin and followed the instructions so that my templates are processed with Jinja instead of the defulat Django Templating Language on my fresh install of Django 1.11. The first thing I noticed is the stack traces that appear when there is an error are very unspecific compared to the DTL templates, and even compared to my flask projects (that default to Jinja). With the default template engines, the stack trace is short and sweet and pinpoints right where the error happened, even mentioning the file name and line number. With the Jinja templates in django, I can usually dig some usable information out of the several lines it spits out running through a couple dozen functions of my installed packages, which is time consuming to pick through and decipher. Is there something that prevents the Jinja override from having the ability to interpret the stack trace as 'human friendly' as the django/flask default engines? Any fix for this?