Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use django paginator page range for displaying the first 10 numbers not all?
I want to change the blow script to show just the first 10 page numbers. Now it shows all page numbers. Could you please tell me how to change it? I tried several ways but it didn't work. Any help will be appreciated! {% if forloop.counter|divisibleby:"3" or forloop.last %} </div> {% endif %} {% endfor %} {% if is_paginated %} <div class="row"> <ul class="pagination pagination-md "> {% if page_obj.has_previous %} <li><a href="?page={{ page_obj.previous_page_number }}">«</a></li> {% endif %} {% for i in paginator.page_range %} {% if page_obj.number == i %} <li class="active"><span>{{ i }}</span></li> {% else %} <li><a href="?page={{ i }}{% if currentCategory %}&category={{ currentCategory }} {% endif %}">{{ i }}</a></li> {% endif %} {% endfor %} {% if page_obj.has_next %} <li><a href="?page={{ page_obj.next_page_number }}">»</a></li> {% else %} <li class="disabled"><span>»</span></li> {% endif %} </ul> </div> {% endif %} </div> -
pass array with urls into template
Here I got the right URLs from django.http import HttpResponse from django.shortcuts import render import requests def main(request): return render(request,'main.html') req = requests.get('https://d3.ru/api/posts').json() arr = [] for data in req['posts']: urls = data['main_image_url'] if urls != None: arr.append(urls) print('urls',arr) How can i pass array arr into my template main.html into <img class> {% extends "wrapper.html" %} {% block title %} <div class="container"> <img class = "col-12 ml-auto col-12 mr-auto" src=///arr???> </div> {% endblock %} -
Django, getting time from django.utils.timezone
I am writing a django app where i have and event model with event_time field, event_date field, so my problem is i want to check if and event has begin and on going, so i will explain the logic i want my code to do, If the date scheduled for the event is equal to the date of today and the time scheduled for the event is less than equal to the time now it means the event has started else it has not here is my code context['is_ongoing'] = context['event'][0].event_date == datetime.now().date() and timezone.now().time() >= context['event'][0].event_time i get true even if event_time is greater than time now whereas i want false any help -
IntegrityError at /cregister/ "Column 'user_customer_id' cannot be null"
models.py from django.db import models from accounts.models import User # Create your models here. class Customer(models.Model): user_customer = models.OneToOneField(User) customer_name = models.CharField(max_length=100,blank=True) phone_no = models.CharField(max_length=100,blank=True) inserted = models.DateTimeField(auto_now_add=True,null=True,blank=True) created = models.DateTimeField(auto_now=True,) views.py from django.shortcuts import render,redirect from django.views.generic.edit import CreateView from accounts.models import User from accounts.forms import RegisterForm from .forms import CustomerRegistration from .models import Customer def CustomerSignupView(request): r_form = RegisterForm(request.POST or None) c_form = CustomerRegistration(request.POST or None) context = { "r_form":r_form , "c_form":c_form , } if r_form.is_valid() and c_form.is_valid(): instance = r_form.save(commit=False) instance.is_customer = True instance.save() c_form.save() return redirect("/") return render(request,"customerregister.html",context) forms.py from django import forms from .models import Customer class CustomerRegistration(forms.ModelForm): class Meta: model = Customer fields = ('customer_name','phone_no',) I have two separate forms - RegisterationForm(RF) and CustomerRegistrationForm(CRF). CRF inherits RF, I want to save two forms in single view i.e.CustomerSignupView. While submitting the forms Intergrity error pops up, and the data saved is only from RegistrationForm. How do I save both forms in thier respective table with integrity maintained. Thanks. -
python migrate ou makemigrations not running
I'm new to django. I still can not migrate to mysql I have caught up with the versions can anybody help me? Windows 10 django-admin.py --version 2.0.6 Python 3.7.0b5 Now I have the following error: **enter code here** C:\Users\rlpro\mysite>python manage.py runserver Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\rlpro\appData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\rlpro\appData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 317, in execute settings.INSTALLED_APPS File "C:\Users\rlpro\appData\Local\Programs\Python\Python37\lib\site-packages\django\conf\__init__.py", line 56, in __getattr__ self._setup(name) File "C:\Users\rlpro\appData\Local\Programs\Python\Python37\lib\site-packages\django\conf\__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "C:\Users\rlpro\appData\Local\Programs\Python\Python37\lib\site-packages\django\conf\__init__.py", line 106, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\rlpro\appData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 724, in exec_module File "<frozen importlib._bootstrap_external>", line 860, in get_code File "<frozen importlib._bootstrap_external>", line 791, in source_to_code File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\rlpro\mysite\mysite\settings.py", line 81 'USER': 'root', ^ SyntaxError: invalid syntax -
How to change URLs based on a column data from the Database
I tried a lot but I am just not able to reach the exact solution. I want to change the URLs of the list which is being generated by a for loop in HTML. Here is my code for that view in views.py file: class DashboardHomeViewClass(View): def get(self, request, *args, **kwargs): device_objects = device_user_data.objects.filter(User_Name = request.user.username) device_list = [] for device in device_objects: device_list.append(device.Device_Alias_Data) context_logged = {'device_list': device_list} return render(request, "dashboardhometemplate.html", context_logged) Here is the code where this context is being used in the HTML template: {%for item in device_list%} <li> <a href="#" aria-expanded="false"><i class="fa fa-bar-chart"></i><span class="hide-menu">{{item}}</span></a> {% endfor %} Now what I need exactly is: Different links should open on clicking different list view items based on device_Alias_Data. eg : http://127.0.0.1:8000/dashboard/{{Device_Alias_Data}} where Device_Alias_Data is character varying field in a table named device_user_data in my database. Here is my urls.py file : from django.conf.urls import url from django.contrib import admin from dashboardhome.views import DashboardHomeViewClass from dashboardhome.views import login_view from django.contrib.auth.views import login urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^login/$', login ,{'template_name': 'login_template.html'}), url(r'^dashboard/$', DashboardHomeViewClass.as_view()), ] -
multiple upload image Django 2.0
I should upload more images at the same time, but I can not find a solution, you could help me to understand where I'm wrong. Thank you models: class GalleriaFotografica(models.Model): user_galleria = models.ForeignKey(User, on_delete=models.CASCADE, related_name="utente_galleria") data_inserimento = models.DateTimeField(auto_now_add=True) titolo= models.CharField(max_length=250, blank=True, null=True ) foto=models.ImageField(blank=True, null=True, upload_to = 'gallery/') class Meta: permissions = ( ("Azienda", "Azienda"), ) verbose_name="GalleriaFotografica" verbose_name_plural="GalleriaFotografica" def __str__(self): return self.titolo Form: class Form_multimmagine(forms.Form): foto = forms.ImageField() Views: def foto(request): userid=request.user.pk if request.method=="POST" and 'caricafoto' in request.POST: form=Form_multimmagine(request.POST, request.FILES) if form.is_valid(): for each in form.cleaned_data['foto']: GalleriaFotografica.objects.create(foto=each) return HttpResponseRedirect("foto") -
social_core.exceptions.MissingBackend: Missing backend "facebook" entry
my settings.py INSTALLED_APPS = [ *** 'social_django', *** ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ *** 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] AUTHENTICATION_BACKENDS = ( 'social_core.backends.open_id.OpenIdAuth', # for Google authentication 'social_core.backends.google.GoogleOpenId', # for Google authentication 'social_core.backends.google.GoogleOAuth2', # for Google authentication 'social_core.backends.facebook.FacebookOAuth2', # for Facebook authentication ) SOCIAL_AUTH_FACEBOOK_KEY = 'my key' SOCIAL_AUTH_FACEBOOK_SECRET = 'my secret' SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = 'my key' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'my secret' my urls.py url(r'^account/auth/', include('social_django.urls', namespace='social')), And done all facebook and google apps settings. Use this guide But when I test it I have next errors Page Not Found Traceback (most recent call last): File "/home/kolas/work/env/lib/python3.5/site-packages/social_core/backends/utils.py", line 50, in get_backend return BACKENDSCACHE[name] KeyError: 'facebook' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/kolas/work/env/lib/python3.5/site-packages/social_core/backends/utils.py", line 55, in get_backend return BACKENDSCACHE[name] KeyError: 'facebook' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/kolas/work/env/lib/python3.5/site-packages/social_django/utils.py", line 46, in wrapper backend, uri) File "/home/kolas/work/env/lib/python3.5/site-packages/social_django/utils.py", line 27, in load_backend Backend = get_backend(BACKENDS, name) File "/home/kolas/work/env/lib/python3.5/site-packages/social_core/backends/utils.py", line 57, in get_backend raise MissingBackend(name) social_core.exceptions.MissingBackend: Missing backend "facebook" entry During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/kolas/work/env/lib/python3.5/site-packages/django/core/handlers/exception.py", line 35, … -
Why doesn't my React-Django app detect static files?
I have created a working React + Django REST project and it works fine on my development machine. I have used the following method to make it work on my CentOS 7 server. I created the build directory using npm run build and copied that to the Django project root folder. I added the build directory on TEMPLATES list in Django settings to identify the index.html file. I added build/static folder in STATICFILES_DIRS. I added url(r'^.*', TemplateView.as_view(template_name='index.html')), line to the root URLS file to capture all url patterns and load the index file in build folder that contains the React app. I run manage.py collectstatic to create a staticfiles folder with all static files. I added the staticfiles folder to the Nginx conf file like following: location /static/ { root /home/michel/project/staticfiles; } I have restarted the nginx server. I am using the Django server to load the index.html file and I expect that the staticfiles folder will contain necessary static files to load my React app. However, when I visit www.mydomain.com it loads the index.html file, but does NOT load the React app on <div id='root'></div>. I know this because the footer of the index is shown, but the css … -
django-rest-framework custom viewset retrive with multiple lookup args
I have two models say A and B. models look like class A(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=1000) slug = models.CharField(max_length=100) class B(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=1000) slug = models.CharField(max_length=100) A = models.foreignkey(A, models.SET_NULL, blank=true) serializers Class ASerializer(serializers.HyperlinkedModelSerializer): class Meta: model = A fields = '__all__' lookup_field = 'slug' extra_kwargs = {'url': {'lookup_field': 'slug'}} Class BSerializer(serializers.ModelSerializer): class Meta: model = B fields = '__all__' model viewset from rest_framework import viewsets, permissions from rest_framework.response import Response from rest_framework.decorators import action from .models import (A, B) from .serializers import (ASerializer, BSerializer) Class AViewSet(viewsets.ModelViewSet): queryset = A.objects.all() serializer_class = ASerializer permission_classes = (permissions.DjangoModelPermissionsOrAnonReadOnly, ) lookup_field = 'slug' def retrieve(self, request, *args, **kwargs): instance = self.get_object() bs = B.objects.filter(A=instance.id) serializer = BSerializer(bs, many=True) return Response(serializer.data) I want to access a url something like Url: ^A/<slug>/B/slug>/$ I go through Django Restframework documention and found that we can add custom url like ( drf-custom-rounting. I don't get how to make access url pattern above. How to customize like that? -
How to left outer join with extra condition in Django
I have these three models: class Track(models.Model): title = models.TextField() artist = models.TextField() class Tag(models.Model): name = models.CharField(max_length=50) class TrackHasTag(models.Model): track = models.ForeignKey('Track', on_delete=models.CASCADE) tag = models.ForeignKey('Tag', on_delete=models.PROTECT) And I want to retrieve all Tracks that are not tagged with a specific tag. This gets me what I want: Track.objects.exclude(trackhastag__name='new_release').only('id') but it's very slow when the tables grow. This is what I get when printing .query of the queryset: SELECT "track"."id" FROM "track" WHERE NOT ( "track"."id" IN (SELECT U1."track_id" AS Col1 FROM "trackhastag" U1 WHERE U1."tag_id" = 1) ) I would like Django to send this query instead: SELECT "track"."id" FROM "track" LEFT OUTER JOIN "trackhastag" ON "track"."id" = "trackhastag"."track_id" AND "trackhastag"."tag_id" = 1 WHERE "trackhastag"."id" IS NULL; But haven't found a way to do so. Using a Raw Query is not really an option as I have to filter the resulting queryset very often. The cleanest workaround I have found is to create a view in the database and a model TrackHasTagFoo with managed = False that I use to query like: Track.objects.filter(trackhastagfoo__isnull=True). I don't think this is an elegant nor sustainable solution as it involves adding Raw SQL to my migrations to mantain said view. This is … -
Model name not translated to chinese
I am going to translate django models from English to Chinese. I have translated the App Name to chinese, but model name not working class DiseaseType(models.Model): diseasetype = models.CharField(_('diseasetype'), max_length=DEFAULT_LENGTH,blank=True) class Meta: verbose_name = _('disease type') verbose_name_plural = _('disease types') def __str__(self): return str(self.diseasetype) -
Deploy Django under a sub url on apache2
Django Version 2.0, Apache 2, python 3.5 I have to host a Django app running on an apache server at localhost:8080 via url www.server.com/myapp behind a reverse proxy. The question is how to make the urls in my response pages to have a prefix of "/myapp" so that the apache can direct them correctly to myapp. E.g., the urls in a page like "/foo/bar" ought to be changed to "/myapp/foo/bar" to allow apache proxy to myapp. What is the right apache configure to use to achieve this? Apache reverse proxy config: .... ProxyPass / http://10.5.20.214:8080/ ProxyPassReverse / http://10.5.20.214:8080/ .... -
Extract on date : django.db.utils.OperationalError: near "None": syntax error
I try to format the date in a query, but I got an error whentrying to extract the year, the month... This occurs on sqlLite and Postgres. Django version : 1.11.4 >>> users = User.objects.all() >>> users.annotate(year=Cast(ExtractYear('date_joined'), CharField())) return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: near "None": syntax error -
In Python/Django what steps are necessary to sanatize/escape characters of user inputted e-mails?
I have a Django project with a form for users to send e-mails. It works fine so far. But I want to be sure, that users can't (accidentally) insert malicious text. I use the django integrated email system. (django.core.mail.EmailMessage) Users can: Set subject and body text Select some recipients from a database recipients from the database are constructed like this: recipients_list = ['{} <{}>'.format(r[0], r[1]) for r in recipients] I am worried that the names in the database contain some bad characters like commas and causing some trouble. Also I don't know if there are more things to keep in mind. Django documentation states that header-injection will be prevented. But is that all I need to worry about? -
Django Model Reverse querying
I have 4 models, 1) Item: describes the name and the value of the item. I can register new items completely independently. 2)A Line Item consists basically in one Item and the quantity of that specific item. 3)Inventory: Inventory is a bunch LineItems. 4) Survivor is just a user who owns the Inventory. I not able to filter backwards the inventory. Example: I want to get all the itens that the "x" user´s inventory has on it. Survivor is my user. Sorry for my bad english. class Itens(models.Model): item_name = models.CharField(max_length=50) points_value = models.FloatField(default=0) def __str__(self): return self.item_name class LineItem(models.Model): itemln = models.ForeignKey(Itens,on_delete=models.CASCADE,related_name='itens_contidos') quantity = models.IntegerField(default=0) inventory_ln = models.ForeignKey("Inventory",on_delete=models.CASCADE) class Inventory(models.Model): survivor_inventory = models.OneToOneField(Survivor,on_delete=models.CASCADE) def __str__(self): return self.survivor_inventory.name +' s inventory' class Survivor(models.Model): #id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) age = models.PositiveIntegerField(default=0) ... -
Deleted Django Migrations Folder
I accidentally deleted my migrations folders for all my apps including __init__.py. Is there any way to reset or retrieve these? Thank you! -
Custom command and possibilty to import from many sources
I am working on import in django 1.8. I would like to have possibilty to import data from two sources - one and two. If I put in command argument one (python manage.py import_data one) - I import data from one, and the same with two - two in command - from source two (python manage.py import_data two). But for now, when I want to run python manage.py import_data two in handle I recived one instead of two. class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('one', type=str, nargs='?', default='one') parser.add_argument('two', type=str, nargs='?', default='two') def handle(self, *args, **options): if options['one']: print('one') return if options['two']: print('two') return -
Django: Dynamically adding formset - ['ManagementForm data is missing or has been tampered with']
I get the "['ManagementForm data is missing or has been tampered with']" ValidationError when I try to update/edit an existing object using combined form and formset (with dynamic addtion of extra formset using JS): Can someone please help me answering what I am doing wrong? Thanks a lot! forms.py: IngredientModelFormset = inlineformset_factory( Recipe, Ingredient, fields=('name',), extra=1, widgets={ 'name': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Add an ingredient...', }) } ) views.py: def recipe_update(request, id=None): instance = get_object_or_404(Recipe, id=id, user=request.user) form = RecipeForm(request.POST, request.FILES or None, instance=instance) formset = IngredientModelFormset(request.POST, instance=instance) if form.is_valid() and formset.is_valid(): recipe = form.save() recipe.user = request.user recipe.save() for forms in formset: ingredient = forms.save(commit=False) ingredient.recipe = recipe ingredient.save() return redirect(recipe.get_absolute_url()) context = { "instance": instance, "form": form, 'formset': formset, } return render(request, "recipes/recipe_form.html", context) javascript: <script type="text/javascript"> function updateElementIndex(el, prefix, ndx) { var id_regex = new RegExp('(' + prefix + '-\\d+)'); var replacement = prefix + '-' + ndx; if ($(el).attr("for")) $(el).attr("for", $(el).attr("for").replace(id_regex, replacement)); if (el.id) el.id = el.id.replace(id_regex, replacement); if (el.name) el.name = el.name.replace(id_regex,replacement); } function cloneMore(selector, prefix) { var newElement = $(selector).clone(true); var total = $('#id_' + prefix + '-TOTAL_FORMS').val(); newElement.find(':input').each(function () { var name = $(this).attr('name') if(name) { name = name.replace('-' + (total - 1) … -
URL shortening using UUID while serving files nginx django
Using Django2 and nginx, users can upload files (mainly pic,vids) and I want to serve those files by masking the full url path. This is the example structure I expect to see but I don't want users to know about this structure or even the image filename. domain.com/media/user/pictures/Y/M/D/image1.jpg I want the user to see the above image through a url like this and the random UUID number changes for each file and that number can point to any type of file. domain.com/media/23kj23l9ak3 When the file is uploaded the original name, permissions assigned (public, friends, private), file path and the UUID that is generated stored in the database) but the file is stored on the filesystem or remote location. I've never got to this point before and I would like to know what the modern way of doing it would be or let me know what technology/features of django/nginx can help me solve it. -
Can't retrieve field from my model
I need to show fields title and text in separate text area in my template. I can't access them cause I am new in django here are my models.py class Banner(models.Model): title = models.CharField(max_length=100) text = models.CharField(max_length=500) def __str__(self): return self.title and views.py def home(request): context = {} return render(request, 'home/home.html', context) -
django form_valid() vs save()
In django forms, for saving other data I usually use form_valid() but as I can also use save() method of formclass. Today I override save() instead of form_valid(), I got problem with my manytomanyfield, the values of manytomanyfield are not saved but when I use form_valid() they start saving, can anybody tell me the reason and what are the differences between both, which is the most convenient method ? -
MYSQL - Client does not support authentication protocol requested by server;
I want to run a Django server and i get this error: django.db.utils.OperationalError: (1251, 'Client does not support authentication protocol requested by server; consider upgrading MySQL client'). I'm on Windows and i have installed MySQL 8.0, the server status is running (i checked in windows services) and everything seems to be ok. What could i try ? Thanks -
Displaying Django Admin Navigation on non model template?
IDK if above title will justify below problem but I will try to explain it. I have made an HTML form(with only HTML's form tag, not Django) which I have put inside {% block content %} for Django to display. {% extends "admin/base_site.html" %} {# mainapp/templates/VideoTracker.html #} {% block content_title %} {{ 'Execution Status' }} {% endblock %} {% block content %} <form> <table> <br> <tr> <td> <div> <input type="checkbox" name="adhocexec", value="Adhoc" checked/> Adhoc Request </div> </td> <td> <div> <input type="checkbox" name="periodicexec", value="Periodic" checked> Periodic Request </div> </td> </tr> <tr> <td> <div> Start : <input type="date" name="frdt"> </div> </td> <td> <div> End : <input type="date" name="todt"> </div> </td> </tr> </table> <br> <div> <button type="submit" class="btn btn-primary"> <span class="glyphicon glyphicon-search"></span> Search Reports </button> </div> <br> <input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search in results..." title="Type Here"> <table id="myTable"> <tr class="header"> <th>BOX ID</th> <th>MSO ID</th> <th>Execution Type</th> <th>Channel ID</th> <th>Execution Date Time</th> <th>Result</th> <th>Detailed Report</th> </tr> {% for queue in results %} <tr> <td>{{ queue.box_id }}</td> <td>{{ queue.mso_id }}</td> <td>{{ queue.exec_type }}</td> <td>{{ queue.channel_id }}</td> <td>{{ queue.exec_time }}</td> <td>{{ queue.result_status }}</td> <td>{{ queue.result_link }}</td> </tr> {% endfor %} </table> <script> function myFunction() { var input, filter, table, tr, td, i; input = document.getElementById("myInput"); filter … -
When Django admin is loaded on a mobile device to hide some of the items
as I am loading my page using django_admin. Can somebody tell me how to disable loading some of the items for mobile? I've searched the web but cannot find anything.