Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Foreign Key Lookup in QuerySet
I am writing an app for a sports league. I have models for Teams and the Schedule. When a user selects a Team, they can see that team's wins, losses, ties. I'd like to show all the games from that team. Models.py class Teams(models.Model): team = models.AutoField(primary_key=True) team_name = models.CharField(max_length=225, blank=True, null=True) sport_id = models.ForeignKey(Sports, models.DO_NOTHING, blank=True, null=True) division = models.CharField(max_length=225, blank=True, null=True) school = models.ForeignKey(School, models.DO_NOTHING, blank=True, null=True) win = models.IntegerField(blank=True, null=True, default=0) loss = models.IntegerField(blank=True, null=True, default=0) tie = models.IntegerField(blank=True, null=True, default=0) class Meta: managed = True db_table = 'teams' def __str__(self): return self.team_name class Schedule(models.Model): match = models.AutoField(primary_key=True) match_date = models.DateField(blank=True, null=True) home = models.ForeignKey(Teams, related_name='home_set', blank=True, null=True) away = models.ForeignKey(Teams, related_name='away_set', blank=True, null=True) home_score = models.IntegerField(blank=True, null=True) away_score = models.IntegerField(blank=True, null=True) class Meta: managed = True db_table = 'schedule' def __str__(self): return '%s at %s' % (self.away, self.home) And my relevant views: class TeamView(generic.TemplateView): template_name = "teamsports/teamview.html" def get_context_data(self, **kwargs): context = super(TeamView, self).get_context_data(**kwargs) q = self.request.GET.get('team_name') context['team'] = Teams.objects.get(team=q) context['game_list']=Schedule.objects.filter(home=q).values() | Schedule.objects.filter(away=q).values() return context The Template: {% extends 'base.html' %} {% block content %} <h1>Team Name: {{ team }}</h1> <h1>Wins: {{ team.win }}</h1> <h1>Losses: {{ team.loss }}</h1> <h1>Results: </h1> <h1>{% for game_list in game_list|dictsort:"match_date" %}</h1> … -
Print key-value in JSON object in HTML with Django
I have a JSON object in string that looks like '{"key1":"value1", "key2": "value2", "key3": "value3"}' I can use json.loads to make that into a JSON object, but when I try to print it in HTML, it prints the entire JSON object like {"key1":"value1", "key2": "value2", "key3": "value3"} my function looks like: def jsonPretty(json_string): return json.loads(json_string) and in HTML/Django: {{kvpair|jsonLoadsPretty}} However I want it to print key1 value1 key2 value2 key3 value3 The format can vary a little, but I want each key-value pair to separate by a \n, and the brackets should be removed. What would be the best way of doing this? -
How do I make this working code validate, in this HTML file?
Error generated by validator The actual code looks like this in validator: Code as it appears in validator -
django queryset for active user based on foreign key and m2m field
I have these models: class Entry(models.Model): ... terms = models.ManyToManyField(Term) source = models.ForeignKey(Source) class User_Filter(models.Model): user = models.ForeignKey(User) source = models.ForeignKey(Source, null=True) terms = models.ManyToManyField(Term, blank=True) Users can specify which sources they want to follow and what terms (from that source) they are interested in. My goal is to create a view where only entries fitting active user filter will be displayed. What would the best way to tackle this? Is it possible to achieve in a single query? Any kind of help is highly appreciated. -
URLconf not matching URL patterns
Python/Django beginner here. I'm running into this error: Using the URLconf defined in learning_log.urls, Django tried these URL patterns, in this order: ^admin/ ^$ [name='index'] ^topics/$ [name='topics'] ^topics/(?P\d+)/$ [name='topic'] The current URL, topics/% url 'learning_logs:topic' topic.id %}, didn't match any of these. When I am trying to load my topic template. Here is my template: {% extends 'learning_logs/base.html' %} {% block content %} <p>Topic: {{ topic }}</p> <p>Entries:</p> <ul> {% for entry in entries %} <li> <p>{{ entry.date_added|date:'M d, Y H:i' }} </p> <p>{{ entry.text|linebreaks }}</p> </li> {% empty %} <li> There are no entries for this topic yet. </li> {% endfor %} </ul> {% endblock content %} This is my views.py: from django.shortcuts import render from .models import Topic def index(request): '''The home page for Learning Log''' return render(request, 'learning_logs/index.html') def topics(request): '''Show all topics.''' topics = Topic.objects.order_by('date_added') context = {'topics': topics} return render(request, 'learning_logs/topics.html', context) def topic(request, topic_id): '''Show a single topic and all its entries.''' topic = Topic.objects.get(id=topic_id) entries = topic.entry_set.order_by('-date_added') context = {'topic': topic, 'entries': entries} return render(request, 'learning_logs/topic.html', context) And this is my urls.py code: '''Defines URL patterns for learning_logs.''' from django.conf.urls import url from . import views urlpatterns = [ # Home page url(r'^$', … -
how django upload files in different subfolder
I have many files under a folder(for example, 'datasets') and these files are separated in many different sub–dictionaries. I want to let user specify the folder 'dataset' in a form and upload all the files in django. After uoload, The django view function will extract some pieces information from each files and save into database. how can I do this. Thanks.Eric The following is the structure of my files: datasets - subfolder 1 - file1 - file2 - subfolder 1a - file3 - subfolder 2 - file4 - file5 -
Django DDS/Celery/Redis in multi server environment
I use Django-DDS with Celery/Redis for scrape items in a single server environment just fine. I want to move to a multi server environment for more scrape power. My idea is to use a Postgre DB with Redis server on Master server and add records with DDS/Celery to Redis only from there. Slave servers ll run Scrapyd and only consume records from master Redis server and update master Postgre DB. Anyone have idea how i can implement this scenario or is there a different/better one? -
TastyPie - Upload image file on worker and simply set the path
I have a worker that takes in a video and generates a thumbnail of that video. The worker then uploads the thumbnail to S3. What I want to do is upon completion hit a TastyPie resource and save the path that the image was uploaded to. But I'm having trouble because TastyPie is expecting a File to be sent and I'm sending just the path. Is there a way to fake upload this file? class Video(models.Model): thumbnail = models.ImageField(blank=True, null=True) class VideoResource(NamespacedModelResource): thumbnail = fields.FileField(null=True, blank=True) def hydrate_thumbnail(self, bundle): # The following is obviously wrong. # bundle.data['thumbnail'] is set to the path that the image is already stored from django.core.files import File return File(bundle.data['thumbnail']) -
Django - Limit the number of instances of a model for every user
I want to limit the number of instances of a specific class. I already have limited it by using some HTML, but if someone sneaky reuses the link to the form, one can make another instance. So in my views.py, I make a query qry_models = Model.objects.filter(owner=request.user) In my HTML-template, I already made the adjustments to prevent multiple instances. If there is none, one is redirected to the ModelForm to create an instance. If there is a model in the query, it is displayed/usable. {% for model in qry_models %} {{ model }} {% empty %} <a href="{% url 'app:model_new' %}">Make a new instance</a> {% endfor %} But if someone reuses the link one is redirected to in the first place, he can create another instance. That shall be prevented. I want to have one instance for each user account. If I follow Limit number of model instances to be created, I always get a MultipleObjectsReturned error since it queries all instances from all account and not only the instances from the active/logged in account. -
Get fullname of user from django user model
I am trying to get the data from django's user model and print the full name of a user from it. view.py from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User def Showfullname (request): fullname = request.user.get_full_name() context = {'fullname':fullname} return render(request, 'main/base.html', context) the line for it from urls.py url(r'^name$', views.Showfullname, name='Showfullname'), and then the div that is the target in my main files, where I already have a is authenticated check in a parent template. <div class="form-group has-feedback"> <input type="text" class="form-control" placeholder="{% url 'main:Showfullname' %}" readonly /> <i class="glyphicons glyphicons-car form-control-feedback"></i> </div> Right now it prints / in the input when it should be printing dan dan or admin admin -
How can I change the django-behave test runner's test file discovery pattern?
I have a Django project with behave features and unittest tests. The unittest tests are organized like so: theproject/ theapp/ tests/ tests_one.py tests_other.py ... It is irritating to have to prefix test files, which are already clearly identified as such by being in the tests directory, with "tests_". If I rename all the test files without "tests_" and change my test runner to TEST_RUNNER = 'django.test.runner.DiscoverRunner' in settings.py and do python manage.py test -p '*.py' all of my unittest tests run, but not my behave features. When I have TEST_RUNNER = 'django_behave.runner.DjangoBehaveTestSuiteRunner' in settings.py and do python manage.py test my features run but not my unittest tests. The django-behave runner doesn't have a -p flag or an equivalent that I can see. How can I get the django-behave runner to discover tests in files whose names don't begin with "tests_"? -
Django form - key error
I have a form implemented in a ListView. However I get a key error when i try to submit the form: File "C:\Users\John\Desktop\website\app\views.py", line 124, in form_valid id = self.kwargs['id'] KeyError: 'id' [14/Dec/2016 21:42:09] "POST /car/ HTTP/1.1" 500 99346 This is the main code: `class CarListFormView(FormView): form_class = CarListForm def form_valid(self, form): id = self.kwargs['id'] obj = Car.objects.get(pk=id) form = CarListForm(instance=obj) car = form.save(commit=False) if self.request.user.is_staff: car.agency = Agency.objects.get(agency_id=9000) else: car.agency = self.request.user.agency car.save() return redirect('car_list')` What causes this key error? Thanks! -
generate and calling boolean field forms in django template
I want to generate django boolean form(checkbox) by for loop(of django Templates) and call it(to views) to delete checked data. I writed some codes: (but it don't work at if request.POST['id_checkbox{}'.format(b.id)]: in views) my codes: libra_book.html (template) <form role="form" method="post"> {% csrf_token %} {% render_field form.action %} <button type="submit" class="btn btn-default">Submit</button> <table class="table table-striped text-right nimargin"> <tr> <th class="text-right"> </th> <th class="text-right">row</th> <th class="text-right">title</th> <th class="text-right">سال چاپ</th> </tr> {% for b in obj %} <tr> <td><input type="checkbox" name="id_checkbox_{{ b.id }}"></td> <td>{{ b.id }}</td> <td>{{ b.title }}</td> <td>{{ b.publication_date }}</td> </tr> {% endfor %} </table> </form> views class book_showForm(forms.Form): action = forms.ChoiceField(label='go:', choices=(('1', '----'), ('2', 'delete'), )) selection = forms.BooleanField(required=False, ) def libra_book(request): if request.method == 'POST': sbform = book_showForm(request.POST) if sbform.is_valid(): for b in Book.objects.all(): if request.POST['id_checkbox{}'.format(b.id)]: Book.objects.filter(id=b.id).delete() else: continue else: sbform = book_showForm() return render(request, 'libra_book.html', {'obj': Book.objects.all(), 'form': sbform}) model class Book(models.Model): title = models.CharField(max_length=100) authors = models.CharField(max_length=20) publication_date = models.DateField() -
docker-compose: run some db initialization exactly once?
I am trying to get docker-compose to deploy a Django app, that uses a 'web' container (with gunicorn) and a 'worker' container (with celery). I want to be able to use the scale command from docker-compose to scale out the web and worker groups (I need to figure out a load balancer for the web part, but that's for another day!). However, there are some Django management commands I want to run when the service is first deployed, once, to create some seed data. The worker container uses dockerize to wait for the web container to be responding, so it will always be a web container that needs to do this, but only the first one after the database migrations are initially applied. python ./manage.py app_initialise --full-demo python ./manage.py collectstatic -v0 --no-input echo "from my.apps.core.models import User; User.objects.create_superuser('admin', 'admin@example.com', 'password')" | python manage.py shell Is there a way to do this in docker-compose, or should I be wrapping my management commands in "if exists" type logic? What is the best practice? (alternatively, I guess - is there a hook for django to do this?) -
Django unittest with legacy databsae connection
I have a Django project that pulls data from legacy database (read only connection) into its own database, and when I run integration tests, it tries to read from test_account on legacy connection. (1049, "Unknown database 'test_account'") Is there a way to tell Django to leave the legacy connection alone for preparing the test database? -
Pile Django update query into one big query instead of looping queryset?
Is it possible to get this into one big update query instead of looping over the queryset? foos = Foo.objects.all() for f in foos: f.bar = Bar.objects.filter(created__lt=f.foo_field)).first() f.save() I have tried this which I thought might work but unfortunately it throws a FieldError: Foo.objects.all().update(bar=Bar.objects.filter(created__lt=F('foo_field')).first()) -
Pass a variable from custom settings into a Django view
I know how to access the settings module (as detailed here) but I have a number of custom settings modules that extend settings.py and I'm not sure how to access it in my view. It's available in my template but I can't find any information on how to access it in the settings. os.environ["DJANGO_SETTINGS_MODULE"] correctly returns the string of my intended settings module, but since it's just a string it doesn't have my variables on it. -
Throttling. Differnet rates for same user
Thottling can be configured with this: REST_FRAMEWORK = { 'DEFAULT_THROTTLE_CLASSES': ( 'rest_framework.throttling.AnonRateThrottle', 'rest_framework.throttling.UserRateThrottle' ), 'DEFAULT_THROTTLE_RATES': { 'anon': '10/second', 'user': '100/second' } } But I would like to have different throttling rates for same user. something like this: 'DEFAULT_THROTTLE_RATES': { 'anon': '10/second', 'anon': '100/day', 'anon': '100/whatever' } Is it possible? Do I have to use a different approach/library in order to achieve this? -
custom template tag library is not getting loaded when placed in a directory with undescore in name
I created a custom tag library file inside a directory name template_tags. I was not getting loaded and was throwing error - 'custom_template_tags' is not a registered tag library. Must be one of: admin_list admin_modify admin_static admin_urls cache future i18n l10n log static staticfiles tz I have __init__.py in folder. I followed all tricks from SO but none worked until I renamed my directory to templatetags. I also tried moving template library outside the folder in app's directory but this also didn't worked. So I have these questions here 1. Why tag library was not loaded without a directory? 2. When I placed tag library inside directory, why it needed name of directory without underscore in it. Is it done knowingly in django? -
Django fastcgi namespace cleanup
When you're running a Django app as a fastcgi application, how does Django or fastcgi ensure that the process namespace is cleaned up between requests. For example, if a function in Django views.py checks for the existence of some object, will the fact that Django just served a previous request with that view (where that object was created for that request) mean that my "does this exist" test will return TRUE when I expect it to return FALSE? The documentation on fcgi and Django is not clear on this. -
Changing lookup_type in Django 1.10+
In older versions of Django, you could change the lookup on the fly and have access to the value being looked up. For example, let's assume we're storing country by its ISO 2-letter abbreviation, but we want to allow searching by the name of a country. from .data import COUNTRIES class CountryField(…): def get_prep_lookup(self, lookup_type, value): if lookup_type == 'icontains': matching_codes = [ country.code for country in COUNTRIES if value in country.name.lower() ] lookup_type = "in" values = matching_codes # ... perform similar for contains, startswith, endswith, etc. lookups return super(CountryField, self).get_prep_lookup(lookup_type, value) As of Django 1.10, get_prep_lookup is deprecated within the Field object. They recommend subclassing Lookup classes and defining get_prep_lookup. The problem is, as far as I can tell, the implementation for Lookup.get_prep_lookup does not let you change the lookup, and the method also does not receive the lookup value. -
Forcing Windows Authentication to use HTTPS on IIS
Running a Django app on IIS, URL Rewrite set up on IIS and SECURE_SSL_REDIRECT = True in settings.py. My problem is that it appears that the log-in window is asking for credentials over HTTP before redirecting to HTTPS despite everything else on the site redirecting properly. Am I mistaken and the sign-in occurs over HTTPS despite the address bar initially coming up as HTTP, or is there another way to force the sign-in over HTTPS? Or is this just a limitation of Windows Authentication? We're a Windows shop here, so logging in with our Windows credentials is huge, and I'd like to handle this with IIS if possible. I do remember stumbling across some Django/Python packages that can plug into AD and do the authorization that way (which should fix the HTTP issue if there's no workaround), so I'm not opposed to a little extra work - just want to make sure we're secure :) Let me know if I need to provide any more info/clarification, and advice or feedback is greatly appreciated. -
Android Studio 500 code from Volley POST
I'm having trouble connecting to a Django api I set up. I am able to POST json via outside sources (such as requestmaker.com) and the api does what it's supposed to do. However using volley, I keep getting a 500 error code back. The api doesn't seem to be the problem, so I was wondering if I went somewhere wrong with the volley setup My Code: public void onClick(View v){ if(titleEdit.getText().toString().trim().length() != 0 && descriptionEdit.getText().toString().trim().length() != 0) { String issueTitle = titleEdit.getText().toString(); String issueDesc = descriptionEdit.getText().toString(); issueQueue = Volley.newRequestQueue(this); JSONObject jsObj = new JSONObject(); try { jsObj.put("title", issueTitle); jsObj.put("description", issueDesc); } catch (JSONException e) { e.printStackTrace(); } JsonObjectRequest jsObjRequest = new JsonObjectRequest (Request.Method.POST, "http://hurst.pythonanywhere.com/supportal/api", new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { System.out.println(response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); } }); // add the request object to the queue to be executed issueQueue.add(jsObjRequest); } Is it possible that I need to include headers with this? Or perhaps there is a better alternative to this than volley. I'm not really sure what could be wrong, so any help would be much appreciated. -
Django view not returning model to template
Please note that I'm new to Django. I created a simple Configuration model, that I want to use to set some global settings on my site. For right now I created just a theme switching setting that replaces the main css file, but I can't get it to load on my login template. Works fine on the index though. Please assist! Views: def get_theme(): theme_name = Configuration.objects.only('theme_name').get().theme_name context = {'theme_name': theme_name} return context def login_view(request): form = LoginForm(request.POST or None) if request.POST and form.is_valid(): user = form.login(request) if user: login(request, user) return HttpResponseRedirect('index') # Redirect to a success page. theme_name = get_theme() return render(request, 'registration/login.html', {'login_form': form}, theme_name) def logout_user(request): logout(request) return HttpResponseRedirect('registration/login.html') @login_required(login_url='login/') def index(request): theme_name = get_theme() return render(request, 'base.html', theme_name) Template on Login.html: {% compress css %} <link href="{% static 'base/css/style-'%}{{ theme_name }}.css" rel="stylesheet" type="text/css"> {% endcompress %} Template on Base.html (Working): {% compress css %} <link href="{% static 'base/css/style-'%}{{ theme_name }}.css" rel="stylesheet" type="text/css"> <link href="{% static 'base/css/sidebar-menu.css' %}" rel="stylesheet" type="text/css"> {% endcompress %} As a note: I'm not loading the Base.html on my login page, because the user will need to login before seeing anything on the base.html. If I'm doing this the wrong way, please … -
Django Not Finding Pages When Mapping App to Index
I am currently working on a project with two applications: stack and users, and wanted to map my views.stack.index to the index of the site (ie: 127.0.0.1:8000). As suck I have changed my main urls.py to look like this: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', include('stack.urls')), # The url in question url(r'^u/', include('users.urls')), ] and my urls.py in my stack application folder looks like this: urlpatterns = [ url(r'^$', views.index), url(r'^create-a-stack/', views.create_stack), ] When I go to http://127.0.0.1:8000/ I see my index page from stack.views.index, however if I try to go to http://127.0.0.1:8000/create-a-stack I get a page not found error. Any ideas on where I am going wrong? Thanks