Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModuleNotFoundError: No module named 'C:\\Program Files (x86)\\Python36-32\\Lib\\site-packages\\Django-1'
When I installed django it was working fine, when i restarted my system it is not working. I tried editing the path environment variable but still it doesn't work. django-admin.py file is in C:\Program Files (x86)\Python36-32\Lib\site-packages\Django-1.11.4-py3.6.egg\django\bin On mentioning this path in PATH environment variable, it is giving the above mentioned error....Any help ? -
Google Analytics not filtering internal traffic
I know there have been similar questions in the past but I have tried many solutions given online to no avail. I am just not able to hide internal traffic for Google Analytics on my Django site. I am setting the filter from Admin->View->Filters. Have tried Predefined and Custom both with fixed IP as well as a regex pattern. (Yes, I have double checked my IP from whatismyip.com and I am using the right one) I read somewhere that it takes time for the filters to come into effect, so even waited for 24 hours but I still see a lot of internal traffic. Google Tag Assistant is also tracking the pages when I access them from internal IP (not sure if its supposed to know about the filters) Not sure where could I be going wrong. -
Django Rest Framework: Output in JSON to the browser by default
I do not want to write ?format=JSON in the URL. It should return JSON by default with djangorestframework -
How to check name of Django url in view
say this is my url: url(r'^$', mainApp_views.homepage), Is it possible to check this text = "mainApp_views.homepage" in view and middleware ? Thanks in advance, -
Css grid very low performance in any browser but firefox
I'm really sorry for my english. Please, excuse me. The problem is - super laggy pages. I'm quite new in webdev and atm building some site, based on django 1.11. I chose css grid as layout system. Whole time i've been working in firefox and when almost finished my work i found a bug. Nothing works properly in any browsers but firefox. This is my sceleton page: {% load static %} <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <link rel="stylesheet" type="text/css" href="{% static 'main/css/main.css' %}"> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> {% block meta %}{% endblock %} <script src='https://rawgit.com/JulianLaval/canvas-particle-network/master/particle-network.min.js'></script> </head> <body> {# header block #} <div class="header"> {# particles #} <div id="particle-canvas" class="particle-canvas"></div> {# navbar #} <a href="{% url 'home' %}" class="btn home">home</a> <a href="{% url 'service' %}" class="btn service">service</a> <a href="{% url 'contacts' %}" class="btn contact">contacts</a> <a href="{% url 'news' %}" class="btn news">news</a> <a href="{% url 'tests' %}" class="tests">Tests</a> <a href="/admin" class="admin">Admin</a> </div> {% block content %}{% endblock %} {# footer block #} <div class="footer"> <div class="copy"><p>Copyrights, 2017</p></div> <div class="social"><p>Icon</p></div> <div class="contacts"><p>Phone: xxx-xxx-xxx</p> <p>Address: Lviv, ul. lvivskaya</p> </div> </div> <script src="{% static 'main/js/main.js' %}"></script> {% block script %}{% endblock %} … -
django 1.6 to 1.9 South.modelsintrospection
I upgrade my Django from 1.6 to 1.9 and I got an error with introspection defined by south.modelintrospector. I link you the problem. from south.modelsintrospector import introspector [... some code ...] args, kwargs = introspector(self) -
Django: use sudo to run server in virtual environment
I got Django set up on my server. I have activated my virtual environment and I'm able to run server successfully on port 8000: python manage.py runserver I would like to use port 80 so I'm able to access (test) my app from outside so I use: sudo python manage.py runserver But this gives me an error: Traceback (most recent call last): File "manage.py", line 17, in <module> "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Can someone please explain why? -
Django unexpectedly splitting queryset objects on spaces
I'm having a problem where Django, or a form, is splitting object list items on spaces. If the object_list is something like: ["picture"='image1.jpg "dir_as_title"='UnknownArtist', "picture"='image2.jpg' "dir_as_title"='Unknown Artist'] and I run it through the following: <div> {% for obj in object_list %} <div class="col-md-6" style="background:url({{obj.picture}}); background-size: 100% 100%; min-height: 260px; max-width: 480px;" > <form id="form" method="POST"> {% csrf_token %} <input type="submit" value={{ obj.dir_as_title }} name={{ obj.dir_as_title }} class="btn btn-primary btn-lg btn-block"/> </form> </div> {% endfor %} </div> The first item will be fine, displaying 'UnknownArtist' in the button, and passing 'UnknownArtist' as its input. The second item will display the button as 'Unknown', and appears to pass no value, resubmitting its current state. -
Django TransactionTestCase / Pending operation error (SQL Server)
I'm upgrading my Django project from: Django 1.5 / Python 2.7 → Django 1.11 / Python 3.5. The database used is MS SQL server, coupled with pyodbc + MS ODBC Driver 13. After upgrading, I am encountered a baffling error causing unit tests to fail that I just can't seem to find a solution for. The error encountered in tests using TransactionTestCase is: pyodbc.Error: ('4', '[42000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server] This operation conflicts with another pending operation on this transaction. The operation failed. (3970) (SQLExecDirectW)') My suspicion is that something to do with TransactionTestCase has changed between Django 1.5 and 1.11. However, despite by best efforts to look at the release notes and test various documented changes I cannot get my tests to pass on 1.11 as they were on Django 1.5. Nothing particularly significant, apart from the Django version, has changed. Any direction or help at all would be especially appreciated. -
Django send_mail fail silently
I am trying to send mail using django with gmail. This is my settings: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'chongwang1209' EMAIL_HOST_PASSWORD = '******' EMAIL_PORT = 587 DEFAULT_FROM_EMAIL = 'chongwang1209@gmail.com' Then I try to from django.core.mail import send_mail send_mail( 'Subject here', 'Here is the message.', 'chongwang1209@gmail.com', ['chongwang1209@gmail.com'], ) . I never got the mail. The real problem is, send_mail reports: Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: Subject here From: chongwang1209gmail.com To: chongwang1209@gmail.com Date: Fri, 04 Aug 2017 01:49:52 -0000 Message-ID: <20170804014952.25386.59@swift> Here is the message. ------------------------------------------------------------------------------- Out[5]: 1 , which means it delivers correctly, EVEN IF I USE A WRONG PASSWORD. What can I do to debug send_mail. -
sessionid cookie being removed after authentication
I've got a super weird issue regarding authentication with Django. Currently I have a multi-tenant site up and running at site.com and staging.site.com. When attempting to login on site.com, it all works correctly, the session is created in the database, and the cookie is set. When attempting to login on tenant.site.com, the session is created in the database, the cookie is set, but on subsequent page loads the cookie for sessionid is removed, therefore automatically logging the user out. Response headers are the same for both sites: content-encoding:gzip content-type:application/json date:Fri, 04 Aug 2017 00:15:07 GMT server:nginx/1.6.2 set-cookie:csrftoken=5VN5QvrQFUv6M8SN6MZTlqqQA8Tvjlki; expires=Fri, 03-Aug-2018 00:15:07 GMT; Max-Age=31449600; Path=/ set-cookie:sessionid=3f8t6p60u7fgoks0vw7sgay5j66xfuos; expires=Fri, 18-Aug-2017 00:15:07 GMT; httponly; Max-Age=1209600; Path=/ status:200 vary:Accept-Encoding vary:Cookie x-frame-options:SAMEORIGIN I've also got staging running at staging.site.com and tenant.staging.site.com, both of these work correctly. The same instance serves both site.com and tenant.site.com, there are no different configurations, the database it automatically selected via django-tenant-schemas. -
Django admin - strange redirect
When I go to the Django admin login form, I'm redirected from mysite.com/abc/admin/ to mysite.com/admin/login/?next=/admin/. However, I need to be redirected to mysite.com/abc/admin/login/?next=/admin/. How can I achieve that? -
passing variable from view to template django
I would like to know how can i pass the calculated variables in view to a template but grouping by room. I have four models, one for hotels, and one for rooms with a hotel foreign key. Another for stock where are listed the rates corresponding each room each day, and finally one model to promos with a hotel and room foreign key. The promos are listed by day for example day 1-01-2017 10% discount in room 1. i have for example two rooms I need to create a list with two list inside, each of one with dictionaries. I need this output but i have no idea where to start [ [ {'Room':1L, 'avg_rate': 743.80} ] , [ {'Room':2L, 'avg_rate': 954.21} ] ]. I am using append to a list (promotion)but with this i only get add value to the list but not grouping. in view.py hotel = Hotel.objects.get(id_hotel=id_hotel) rooms = Room.objects.filter(hotel=hotel) promotion = [] for room in rooms: date1 = check_in_day date2 = check_out_day day = datetime.timedelta(days=1) while date1 < date2: rate_diary = Stock.objects.get(room = room, date = date1) promo_room = promo_hotel.filter(room = room, from_date__lte=date1, to_date__gte=date1) if promo_room: for promo in promo_room: discounted_rate = rate_diary.rate - (promo.percent * … -
How to use variable in list of list django template
code in views.py. f is a list of lists. return render(request, 'site/blabla.html', {'f': f, 'n': 3}) code in blabla.html {% for pr in f %} #return empty <td>{{ pr.n }}</td> #return value from the list <td>{{ pr.1 }}</td> {% endfor %} How to make Django accept n as parameter? Or maybe there is another way to accomplish this? -
jQuery - changing colours based on numeric value and iterating through each item individually
Trying to replace the stroke colour of a percentage circle for each item rendered in django project. So far, I have only managed to change the colour to red. I suspect this is because it is changing them all based on the first/last record(percentage) retrieved. Is there a way to iterate through each item in jQuery so that the stroke colour will change per item? current code: $(function() { var score = ($("#percentage").text()); if (score <=40) { $("path").css("color", "red") } else if (score >=40) { $("path").css("color", "green") } }); -
Save Formset in DJANGO
I have a formset from a model, but when I try to save more than one formset I get the error: KeyError at /auditoria/auditoria_tab/ 'id_control' My view: @staff_member_required def AuditoriaView(request): class RequiredFormset(BaseFormSet): def __init__(self,*args,**kwargs): super(RequiredFormset,self).__init__(*args,**kwargs) for form in self.forms: form.empty_permitted = False auditoriaFormset = formset_factory(AuditoriaForm,max_num=31,formset=RequiredFormset) if request.method == 'POST': usuario = request.user accion = 'Registro nuevo Detalle de Auditoria' formset = auditoriaFormset(request.POST) for form in formset.forms: if formset.is_valid(): obj = form.save(commit=False) #obj.id_control = control obj.auditor = request.user obj.save() else: formset = auditoriaFormset() return render_to_response('audit_auditoria.html', {'formset':formset}, context_instance=RequestContext(request)) My form: class AuditoriaForm(forms.ModelForm): id_control = forms.ModelChoiceField(queryset=Control.objects.all().order_by('nombre'),\ required=True,label='Control', widget=forms.Select(attrs={'class':'form-control'})) id_analista = UserModelNameChoiceField(queryset=User.objects.filter(is_staff=False),\ required = True, label='Analista', widget=forms.Select(attrs={'class':'form-control'})) fecha = forms.DateField(widget=DateInputCustom()) id_tipoerror = forms.ModelChoiceField(queryset=TipoError.objects.all(),required=True, label='Tipo Falla', widget=forms.Select(attrs={'class':'form-control'})) id_sharepoint = forms.IntegerField(label='Sharepoint', widget=forms.NumberInput(attrs={'class':'form-control','style': 'width:80px'})) id_estado = forms.ModelChoiceField(queryset=Estado.objects.all(),required=True, label='Estado', widget=forms.Select(attrs={'class':'form-control'})) observaciones = forms.CharField(widget=forms.Textarea(attrs={'rows':5,'cols':30})) class Meta: model = DetalleAuditoria exclude = ('auditor',) def __init__(self,*args,**kwargs): super(AuditoriaForm,self).__init__(*args,**kwargs) self.helper = FormHelper(self) def clean(self): cleaned_data = super(AuditoriaForm,self).clean() idc = cleaned_data['id_control'] fechac = cleaned_data['fecha'] try: DetalleAuditoria.objects.get(id_control = idc,fecha = fechac ) raise forms.ValidationError('Esta Incidencia ya ha sido registrada') except DetalleAuditoria.DoesNotExist: pass return cleaned_data Template: <form id="form_audit" class="form" method="post" action="/auditoria/auditoria_tab/"> <table class="table table-responsive table-condensed table-bordered"> {{ formset.management_form }} {% for form in formset.forms %} <thead> <th class="info"colspan="6"> <label >{{ form.id_control.label|capfirst }} </label> {{ form.id_control }} … -
Image resize results in vertical bars (python & PIL)
This in being used in django view. Im trying to reduce the size of a incoming image to create an thumbnail. To simplify things, I made the resize width/height the same as the original image (i've tried making it smaller and the exact same problem occurred. basewidth = 350 baseheight = 467 img = Image.open(aobj.useravatar) img = img.convert('RGB') # suggestion found in stackoverflow img = img.resize((basewidth, baseheight), PIL.Image.ANTIALIAS) img.save(file, format='JPEG', quality=100) When downloaded, the file looks like this: Vertical Lines The original file (take from the server) looks like this: Original -
how to change behaviour in admin interface?
This is my models.py class Club(models.Model): date = models.DateField() class Party(models.Model): title = models.CharField(max_length=100) club = models.ForeignKey(Club, null=True) date = models.DateField() I want to be able to add data through the admin interface, and I implemented it successfully. Now, The problem is that I have 2 types of parties: parties that are related to a club, and parties that are not. So, in the admin's interface, when adding the data, I would like the party's date field to be automatically filled with the club's date if I choose a club from the dropdown list. Otherwise If no club is chosen, then the party's date field should be populated manually. How can I achieve this? -
How do I monetize a Django website? [on hold]
I'm new to developing web apps and websites in Django and I want to know how to monetize projects. Specifically, I want to know how to add advertisements on to a django website. If possible, can you please give me a procedure on how to do so? -
Why do values lists retain filters in Django?
Given the Model class below: from django.db import models class Users(models.Model): friends = models.ManyToManyField('self', symmetrical=False, blank=True) If I have a QuerySet of n Users, at least one of which has two friends, why is it that when I retrieve the User by filtering that QuerySet by a friends id and perform a .values_list() call on that QuerySet, like this: users = User.objects.all() user = User.objects.filter(friends=2) user.values_list('friends', flat=True) Results in output like so: >>> [2] But if I perform that same .values_list call on the object's friends field itself, like this: user.first().friends.values_list('id', flat=True) Results in an output of: >>> [2, 3] If these calls are being made on the same object, why is the output different? For reference, this is achieve using Django 1.10 and Python 3.5.2 -
how to associate existing parent with child in django multitable inheritance
I have an existing parent entity with many existing records: class Entity(models.Model): name = models.CharField('Name', max_length=64, db_index=True) I also have child objects that extend using django multi table inheritance: class Investor(Entity): investor_name = models.CharField(max_length=255) I want to create new Investor objects that maybe existing Entities. How do I associate and create Investors with existing Entities? -
how to get full path of media while using multipart/form-data in python/django?
This is html code <form method="post" enctype="multipart/form-data">{% csrf_token %}{{ form }} <div class="info"> <input type="submit" class="btn btn-default" value="Add a picture"> </div></form> now how to access info of image in python and upload it to imgur -
How to normalize email field value in Django REST Serializer?
I am new to Django in general so please do not judge me harshly. I have a custom User model and I use DRF for user profile creation. I normalize the email in the create_user (method of the BaseUserManager). I cannot find the way how to also normalize the value of an email field in the API Serializer. Basically, if I pass an email that already exists in the database, but just with capital letters in the domain, it will go through the Serializer's validation, however it will hit an Integrity Error after: duplicate key value violates unique constraint "accounts_user_email_key" DETAIL: Key (email)=(email@example.com) already exists. Here is a shortened version of my UserManager method: class UserManager(BaseUserManager): def create_user(self, email, first_name, last_name, password): #some validation logic #... user = self.model( email=self.normalize_email(email), first_name=first_name, last_name=last_name ) user.set_password(password) user.save() return user #other stuff... Here is a Serializer itself: class UserSerializer(serializers.ModelSerializer): class Meta: model = models.User fields = ('email', 'first_name', 'last_name', 'password') extra_kwargs = {k: {'write_only': True} for k in fields} #some password validation... def create(self, validated_data): user = models.User.objects.create_user( email=validated_data['email'], first_name=validated_data['first_name'], last_name=validated_data['last_name'], password=validated_data['password'] ) return user Here is the view: class UserCreate(generics.CreateAPIView): serializer_class = serializers.UserSerializer -
Block in django doesnt show the another views
I'am begginer in Django so please try to understand me. I have a problem with the blocks in my django project. I created the base.html like this {% include 'firmy/header.html' %} <html> <body> <h4>Ostatnio dodane</h4> {% block firmy %} {% endblock %} <h4>Kategorie</h4> {% block kategorie %} {% endblock %} </body> {% include 'firmy/footer.html' %} </html> and {%block firmy%} showing me every records what I want from another file but the {%block kategorie%} showing nothing. in views.py I have the code: from django.shortcuts import render from .models import Witryna, Kategorie from django.utils import timezone def widok_strony(request): firmy = Witryna.objects.filter(data_publikacji__lte=timezone.now()).order_by('data_publikacji') return render(request, 'firmy/widok_strony.html', {'firmy': firmy}) def widok_kategorii(request): kategorie = Kategorie.objects.all().order_by('glowna') return render(request, 'firmy/widok_kategorii.html', {'kategorie': kategorie}) and in urls.py i have the code : from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.widok_strony, name='widok_strony'), url(r'^$', views.widok_kategorii, name='widok_kategorii'), ] and on the end models.py from django.db import models from django.utils import timezone class Kategorie(models.Model): glowna = models.CharField(max_length=150, verbose_name='Kategoria') class Meta: verbose_name='Kategoria' verbose_name_plural='Kategorie' def __str__(self): return self.glowna class Witryna(models.Model): nazwa = models.CharField(default="", max_length=150, verbose_name = 'Nazwa strony') adres_www = models.CharField(max_length=70, verbose_name='Adres www') slug = models.SlugField(max_length=250, verbose_name='Przyjazny adres url') email = models.CharField(max_length=100, verbose_name='Adres e-mail') text = models.TextField(max_length=3000, verbose_name='Opis strony') kategoria = … -
Django - window.open inside template not working
Inside my html I have js code like window.open("file.html") which is triggered by clicking on div. if I open html directly everything works. But if I place template inside django, and open it through development server, nothing happens when I click on div. No 404, no errors in console. Why is it not working ?