Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
utf8 chars in python django source code
I have some accents char in my python source code (comments, strings) Django gives me an error for those chars. I have to put this line at the top of the python file to make it work: # -*- coding: utf-8 -*- Is there a way to globaly allow utf8 in the whole project ? Thanks -
Django newbie - I can use {{ variables }} on one model, but not another?
Sorry for the bad title. When I use template variables for replacing fields from my Project model, like so {{ project.title }} and {{ project.featured_image }}. It works like a charm. But if I try to do something similar in the same HTML template for the MapData model {{ mapdata.location }} it doesn't get replaces with any value, it's just blank. With the possibility of becoming todays laughingstock. I have to ask. Why is that? I've been reading through the model and making queries section in the Django Docs. Does it require another technique because it's a ForeignKey? Clearly I'm missing something basic here, but I can't find out what it is on my own. Can someone explain to me how to "access" that MapData model? And I have added a few projects via the admin with correct data in every field in this models.py. >>> from projects.models import * >>> MapData.objects.all() <QuerySet [<MapData: MapData object>, <MapData: MapData object>]> >>> from projects.models import * >>> Project.objects.all() <QuerySet [<Project: Some title 1>, <Project: Some title 2>]> Where is the model: from django.db import models class Project(models.Model): title = models.CharField(max_length=200) text = models.TextField() date = models.DateField() featured_image = models.ImageField( upload_to='projects/featured', default=False) def … -
Edit django code in Windows 10 Linux Subsystem
How can i work with editors or IDEs on Django project if virtualenv created using bash on Ubuntu on Windows 10? PyCharm or any other tools installed on Windows doesn't gives intellisence if virtualenv in linux subsystem. -
Request.Get in url.py in django
I'm fairly new to Django and have used the tutorial videos of Sir Sentdex in youtube. I'm trying to integrate a search function in his example but I think he used a different approach in making his example. He didn't use the app's (Product) views.py but instead went straight to url.py url.py urlpatterns = [ url(r'^$', ListView.as_view(queryset=Product.objects.all(), template_name="product/product.html"))] I made a form with search in my header.html and then extends it in product.html . Here is the code of the form with search: <form class="navbar-form navbar-right" method='GET' action=''> <div class="form-group"> <input class="searchfield form-control" id="searchproduct" name="q" type="text" placeholder="Search" value='{{ request.GET.q }}'> <input type='submit' value='Search'> </div> </form> How can I make the url pattern in the app's url.py like: query = request.GET.get('q') <- I know this should be in a function. urlpatterns = [ url(r'^$', ListView.as_view(queryset=Product.objects.filter( Q(name__contains=query | desc__contains=query ) ), template_name="product/product.html"))] Thanks in advance. -
How to send data in bacthes from django
Hi i am trying to make a android application for which i uses django as backend. i have a listing page which shows me all product available on my application. suppose i have 2000 product available on my application so want to send these data in to batches of 10 or 20. So i am little bit confuses how can i send data into batches. provide me some sample code if possible. Thanks in advance @csrf_exempt def ShowProducts(request): pro_object = Product.objects.all() context = { 'product': pro_object, } return render(request, 'all-product.html',context) -
Common django templates parameter
I have 10 django routes which render 10 templates. Those 10 templates uses the same layout (extends). I want to send the same Context parameters for those 10 routes. Is there a way, in view.py, to set those parameters without duplicating code ? Thanks -
Django-style models without Django?
I have some experience with Django and I really enjoyed the models system. Now I'd like to use Django-style models in non-Django project. Is there a Python package doing that or any approach to configure DB and use django.db.models outside Django project? -
How to auto-populate fields using HtmlFormRenderer - DRF
I want to auto populate the first_name and last_name from the different model to the html form which renders fields from the Contailner model. class SnippetSerializer(serializers.ModelSerializer): class Meta: model = Snippet fields = ['first_name', 'last_name'] class ContainerSerializer(serializers.ModelSerializer): class Meta: model = Container fields = ['id', 'first_name', 'last_name', 'address', 'email',] In views.py file - class ContainerCreateView(TemplateView): template_name = 'test.html' def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context.update({'serializer': ContainerSerializer, 'style': {'renderer': HTMLFormRenderer()}}) return context In test.html- {% extends 'base.html' %} </script> {% endspaceless %}{% endblock %} {% block content %}{% spaceless %} <form id="con_create_form" action="{% block url %}{% url 'api:container-list' %}{% endblock %}" method="{% block method %}post{% endblock %}" enctype="multipart/form-data"> {% csrf_token %} <div class="row"> <div class="col-md-3" > {% render_field serializer.first_name style %} </div> </div> <div class="row"> <div class="col-md-3"> {% render_field serializer.last_name style %} </div> </div> <!-- {{ serializer }} --> <input type="submit" value="Save"> </form> {% endspaceless %}{% endblock %} Can anyone please take a look and help me on it? -
M2M Multiplechoice form with optional information
In the previous version of my app, I had a many-to-many relationship between Account and Club. In my AccountForm I used "club = forms.MultipleChoiceField(widget=CheckboxSelectMultiple)" to enable the user to select from the full listing of clubs. ▢ Football ▢ Hockey ▢ Tennis ▢ Swimming However, I now need to include an optional field where they can include their membership reference number if they have it. So something like ▢ Football ________ ▢ Hockey ________ ▢ Tennis ________ ▢ Swimming ________ I realise that I have to use a 'though' table, but am now struggling to replicate the multiple choice style layout I had before. a) I presume that I need to use an inline formset but based on the through table, so somehow I need to get a formset factory to create forms for each of the clubs. I'm not sure how to do that. Clues? b) Include a checkbox to reflect membership of that club. So presumably a boolean field with a hidden field indicating the id of the club and then some custom work clean and save functions. Does this seem right, or is there a simpler way? class Account(models.Model): name = models.CharField(max_length=20) address_street01 = models.CharField(max_length=50) address_pc = … -
Django Appending Slashes to Static File URLs and getting 404 errors
I've tried all solutions that has been provided there but no luck. I've added 'static' folder to the root. This is an old django app that I've transferred to Godaddy's VPS with CentOS 6. There is another non-python website on the server. /etc/httpd/conf/httpd.conf <VirtualHost *:80> ServerName familyfn.com ServerAlias www.familyfn.com # Note: Whether or not django can write to a directory is controlled by filesys$ # Apache's internal directory auth has to give the vhost access to the wsgi.py $ <Directory /home/familysu/public_html/wsgi> Options None AllowOverride None Order Deny,Allow Allow from all </Directory> # Apache's internal directory auth has to give the vhost access to directories $ <Directory /home/familysu/public_html/code/mediafiles> Options None AllowOverride None Order Deny,Allow Allow from all </Directory> <Directory /home/familysu/public_html/code/staticfiles> Options None AllowOverride None Order Deny,Allow Allow from all </Directory> <Directory /home/familysu/public_html/code/breakdown/static> Options None AllowOverride None Order Deny,Allow Allow from all </Directory> # Use the following to restrict access during review. You'll need to generate t$ #<Location "/"> # AuthName "familysu Review" # AuthType Basic # Require valid-user # AuthUserFile /home/familysu/public_html/reviewusers.htpasswd #</Location> # mod_wsgi works with the Alias directive such that aliased files and directori$ Alias /media/ /home/familysu/public_html/code/mediafiles/ Alias /static/ /home/familysu/public_html/code/staticfiles/ Alias /robots.txt /home/familysu/public_html/code/breakdown/static/robots.txt Alias /favicon.ico /home/familysu/public_html/code/breakdown/static/favicon.ico WSGIDaemonProcess www.familyfn.com processes=2 threads=15 … -
How to prevent data duplicacy in Django many-to-many relation?
I have a table Verticals, and I have a table Sources. There is another table Sources_Verticals which maps the many-to-many relationship of both table elements. Image of Database Sources_verticlas table This table shows the mapping. The table should not allow duplicacy of data like it has done it in: Paytm : Ecommerce, Hotel, Travel Paytm : Ecommerce, Travel Either it should not give option to map the pre-mapped elements under Paytm, or it should merge Hotel into previously existing record. -
How to retrieve files from Oracle BLOB field in Django?
I have existing oracle 11 db where in one of table there is BLOB field that stores files. Also I have Django application that should works with these files. What I need - coonect to this DB and try to read these files from BLOB field( then I want to produce these files as I need.) So my question ss: is it possible to do it using or not using (raw query) from python application? -
Django model: forbid states with particular values
I wonder if Django offers this feature some other web frameworks like Ruby on Rails do. I am talking about means to forbid certain states where the values of the attributes being saved, for example: model.active = False model.authorized = True model.save() # this should fail We can have a model where both active and authorized are either both True or False, but we cannot have any other combination. Sorry but I can't think of a better example right now, I hope the intent is understood. So, does Django have any means for handling these situations? Or implementing it ourselves when the method save is called is the only way? -
Error: Method Not Allowed (POST): "POST / HTTP/1.1" 405 0
I'm trying to make register possible on the homepage, so I don't have a seperate URL to handle registration. I'm trying to send the form through get_context_data, however it's not working. Here's my code: forms.py class UserRegistrationForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = [ 'username', 'password', ] views.py class BoxesView(ListView): template_name = 'polls.html' def get_context_data(self): context = super(BoxesView, self).get_context_data() # login if self.request.method == 'POST': form = UserRegistrationForm(self.request.POST or None) context['form'] = form if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = User.objects.create_user(username=username, password=password) user.save() return redirect('/') else: print(form.errors) #doesn't print anything print(form.non_field_errors()) #doesn't print anything print('Errors') #doesn't print anything else: form = UserRegistrationForm() context['form'] = form return context def get_queryset(self): pass base.html <form action="" enctype="multipart/form-data" method="post">{% csrf_token %} <div class="registerBox"> {{ form.username }} {{ form.password }} <input type="submit" value="register"/> </div> </form> So when I submit the form it gives this error: Method Not Allowed (POST): "POST / HTTP/1.1" 405 0 And it isn't creating a new User. Any idea what the problem is? -
Improve upload speed of Django form upload
In my web application i need to upload 100+ files using django forms.But this will taking a long time to complete upload.Can we improve the uploading speed using techniques like multithreading, multiprocessing. <input type="file" id="id_docfile" name="docfile" multiple> Please suggest an appropriate technique to reduce the uploading time. -
Unique_together M2M relationship
I have the following two models: class TournamentTeam(models.Model) profiles = models.ManyToManyField(Profile) # Profile is my user name = models.CharField(max_length=255) def __str__(self): return self.name class Tournament(models.Model): name = models.CharField(max_length=255, verbose_name='navn') description = models.TextField(verbose_name='beskrivelse') team_size = models.IntegerField() teams = models.ManyToManyField('TournamentTeam') def __str__(self): return self.name I would like to have the name and the tournament (autogenerated by django) on the TournamentTeam be unique_together. I've tried simply adding: class Meta: unique_together = (('name', 'tournament'),) Without success. I've also tried doing it on initialization, but also without success. def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._meta.unique_together = (('name', 'tournament'),) -
during migration on default_permissions i get ValueError: Cannot query "asset": Must be "ContentType" instance
unning migrations: Rendering model states... DONE Applying kpi.0004_default_permissions_1910...Traceback (most recent call last): File "manage.py", line 10, in execute_from_command_line(sys.argv) File "/home/bijay/Envs/kpi/local/lib/python2.7/site-packages/django/core/management/init.py", line 354, in execute_from_command_line utility.execute() File "/home/bijay/Envs/kpi/local/lib/python2.7/site-packages/django/core/management/init.py", line 346, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/bijay/Envs/kpi/local/lib/python2.7/site-packages/django/core/management/base.py", line 394, in run_from_argv self.execute(*args, **cmd_options) File "/home/bijay/Envs/kpi/local/lib/python2.7/site-packages/django/core/management/base.py", line 445, in execute output = self.handle(*args, **options) File "/home/bijay/Envs/kpi/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 222, in handle executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File "/home/bijay/Envs/kpi/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 110, in migrate self.apply_migration(states[migration], migration, fake=fake, fake_initial=fake_initial) File "/home/bijay/Envs/kpi/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 148, in apply_migration state = migration.apply(state, schema_editor) File "/home/bijay/Envs/kpi/local/lib/python2.7/site-packages/django/db/migrations/migration.py", line 115, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/home/bijay/Envs/kpi/local/lib/python2.7/site-packages/django/db/migrations/operations/special.py", line 183, in database_forwards self.code(from_state.apps, schema_editor) File "/home/bijay/work/naxa/dist-kobo-devel/src/kpi/kpi/migrations/0004_default_permissions_1910.py", line 43, in default_permissions_to_existing_users user, (Asset, Collection), permissions_manager) File "/home/bijay/work/naxa/dist-kobo-devel/src/kpi/kpi/model_utils.py", line 174, in grant_all_model_level_perms content_type__in=content_types) File "/home/bijay/Envs/kpi/local/lib/python2.7/site-packages/django/db/models/query.py", line 679, in filter return self._filter_or_exclude(False, *args, **kwargs) File "/home/bijay/Envs/kpi/local/lib/python2.7/site-packages/django/db/models/query.py", line 697, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "/home/bijay/Envs/kpi/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1310, in add_q clause, require_inner = self._add_q(where_part, self.used_aliases) File "/home/bijay/Envs/kpi/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1338, in _add_q allow_joins=allow_joins, split_subq=split_subq, File "/home/bijay/Envs/kpi/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1179, in build_filter self.check_related_objects(field, value, opts) File "/home/bijay/Envs/kpi/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1077, in check_related_objects self.check_query_object_type(v, opts) File "/home/bijay/Envs/kpi/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1058, in check_query_object_type (value, opts.object_name)) -
Django: Context processor error for anonymeous user
Hi I have a model which stores users actions. This model is used for showing notifications to logged in users. Now the issue is code works fine with logged in users, however if I open homepage of application after logout, following error appears. TypeError at / 'AnonymousUser' object is not iterable Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 1.10 Exception Type: TypeError Exception Value: **'AnonymousUser' object is not iterable** Exception Location: /Library/Python/2.7/site-packages/django/utils/functional.py in inner, line 235 Python Executable: /usr/bin/python Python Version: 2.7.10 I think the issue is because of template context processor I am using in my application. Please help on this. context code from models import notifications def activ_notification(request): active = notifications.objects.filter(to_user=request.user,viewed=False)[:10] return({'alert':active}) Settings TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'task.notification.activ_notification', ], }, }, ] -
Search choice field by the name in django - python
I have the below choice field in models. STATUS_REVIEW_RISK_ESTIMATE_CHOICES = ( (0, "High"), (1, "Medium"), (2, "Low"), ) class SiverifyProblemStatement(models.Model): risk_estimate = models.PositiveIntegerField(null=True, blank=True, choices=STATUS_REVIEW_RISK_ESTIMATE_CHOICES) When I try to render the values from db(eventually stored as integers(0,1,2). I'm using the following code which helps me to display the name of the choices(High, Medium and low). Render code: def render_risk_estimate(self, **kwargs): try: stmt = kwargs['row_obj'].revision_problem_statements.latest('id') except ObjectDoesNotExist: return None return (stmt and stmt.get_risk_estimate_display() or None) But when I try to establish the same for searching the field with choice names, I get an error stating get_risk_estimate_display() is not an attribute. However, when I tried this, I'm able to search the field with integer choices. Tried code: class ReviewWorklistDTView(GroupDTListView): columns = [{'data': 'risk_estimate','_get': 'id', 'title':'Risk Estimation', '_search':'revision_problem_statements__risk_estimate', '_type': 'char'},] This helps me in searching with the integer choices not with respect to the values in it. I did looked up at the following questions, but nothing seems to be helping my part. http://stackoverflow.com/questions/22043054/search-field-by-field-choice http://stackoverflow.com/questions/12626171/django-admin-choice-field https://github.com/sivaa/django-custom-search-filter/blob/master/app/admin.py -
NameError: name 'Test' is not defined Django model
from polls.models import * Test.objects.all() NameError: name 'Test' is not defined Even though i had imported the Test model. I had done a faking of the previous migration. So i staled the content-types for this model. So will it create a problem like this or please help. -
how to save the multiple fields in dictionary using django views
i am not able to save multiple fields in dictionary using django views here is my code promotions=Promotions.objects.filter(member=request.user) list11=[] dictt={} d=[] i=0 for q in promotions: c=customer_request.objects.filter(promotion=q) e=c.count() d.append(e) dictt[e]=e list11.append(c) print("counttttttttttttttt",dictt) -
What is the use of transaction.commit_unless_managed() python
What is the use of transaction.commit_unless_managed() in python?? I don't no more abound transaction. In my code saw a function transaction.commit_unless_managed() but i don't no what is the use of commit_unless_managed() transaction.commit_unless_managed() Please explain what is the use of commit_unless_managed()? and difference bet ween normal commit and commit_unless_managed() -
django form is invalid, but no error messages
I have the following form: class SkuForm(forms.Form): base_item = forms.ModelChoiceField(queryset=BaseItem.objects.none()) color_or_print = forms.ModelMultipleChoiceField(queryset=Color.objects.none()) material = forms.ModelMultipleChoiceField(queryset=Material.objects.none()) size_group = forms.ModelMultipleChoiceField(queryset=Size_Group.objects.none()) my view: def sku_builder(request): if request.method == "POST": user = request.user form = SkuForm(request.POST) if form.is_valid(): base_item = form.cleaned_data['base_item'] colors = filter(lambda t: t[0] in form.cleaned_data['color_or_print'], form.fields['color_or_print'].choices) materials = filter(lambda t: t[0] in form.cleaned_data['material'], form.fields['material'].choices) size_groups = filter(lambda t: t[0] in form.cleaned_data['size_group'], form.fields['size_group'].choices) return render(request, 'no_entiendo.html', {'colors': colors, }) else: return HttpResponse("form is not valid") user = request.user form = SkuForm() form.fields['base_item'].queryset = BaseItem.objects.filter(designer=user) form.fields['color_or_print'].queryset = Color.objects.filter(designer=user) form.fields['material'].queryset = Material.objects.filter(designer=user) form.fields['size_group'].queryset = Size_Group.objects.filter(designer=user) return render(request, 'Disenador/sku_builder.html', {'form': form,}) The problem is that Im only receiving the "form is not valid message" I have no idea why it is not valid as the Form is only made of choices, so no typo error. Also I have no feedback from the system to debug, or don't know where to search. *what happens after form.is_valid is not the complete code -
Django Rendering Error for Template
Issue: When running django startproject manage.py I receive the following error despite paths being correct when I print them to terminal: [Errno 22] Invalid argument: u'paths\projects\\demo\\demo\\:\\templates\\index.html' I'm not sure why there is a ':' in the middle of the path. I'm following this tutorial for reference here: What works: I can view admin. Background: I'm using a Microsoft windows 10 and using anaconda Using django and a virutal environment I have a django project in: projects/demo/ in demo I have the following folders: demo static template manage.py In templates I have the index.html file which I've checked using my browser and it loads. in projects/demo/demo I have settings.py, urls.py,views.py Here is the major edits I made that are related to the issue: in settings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': os.path.join(BASE_DIR,'demo\\template\\'), 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] The path is correct to the file. in urls.py: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^index/',views.index) ] In views.py def index(request): return render(request,'templates/index.html',{}) -
Why does select_related and prefetch_related not work with get queries?
This works: Model.objects.filter(pk=1).select_related('address').prefetch_related('residents') But this doesn't work: Model.objects.get(pk=1).select_related('address').prefetch_related('residents') >>> object has no attribute 'prefetch_related' Why don't these optimizations work when dealing with a single object rather than a list of objects? Am I forced to go back to the database two more times because of this?