Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Runtime error when scaling up django app from free to basic app service
I am getting a runtime error when scaling up my django app from a free plan to a basic plan on azure. It appears to be a configuration problem. Here is what I have found: When visiting my site, I get this error: Server Error in '/' Application. Could not load file or assembly 'Microsoft.WindowsAzure.Diagnostics, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040) Some googling led me to believe that this is a bug with the auto generated config file created by Python Tools for Visual Studio. This issue is documented on the PTVS Github project. That issue references a potential workaround from the msdn blog. However, when I replace my config file with the one suggested on msdn (after changing references of python 3.5 to 2.7), I get an internal server error. This is my original config file. <?xml version="1.0"?> <!-- Generated web.config for Microsoft Azure. Remove this comment to prevent modifications being overwritten when publishing the project. --> <configuration> <system.diagnostics> <trace> <listeners> <add type="Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener, Microsoft.WindowsAzure.Diagnostics, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="AzureDiagnostics"> <filter type="" /> </add> </listeners> </trace> </system.diagnostics> <appSettings> <add key="WSGI_ALT_VIRTUALENV_HANDLER" value="django.core.wsgi.get_wsgi_application()" /> <add key="WSGI_ALT_VIRTUALENV_ACTIVATE_THIS" … -
Can I limit a page's used number of processes on an Apache server
I have a webpage that I would like to be limited to using just one process on an Apache server that has multiple processes. Can I limit that one webpage to using just one process while allowing the remaining pages on this server to use multiple processes? Would this be bad practice? -
Code should return min value but he don't return
I have django app (1.8) Here is part of my model: price_1 = models.DecimalField(max_digits=6, decimal_places=0, null=True, help_text='price_1') price_2 = models.DecimalField(max_digits=6, decimal_places=0, null=True, help_text='price_2') price_3 = models.DecimalField(max_digits=6, decimal_places=0, null=True, help_text='price_3') price_4 = models.DecimalField(max_digits=6, decimal_places=0, null=True, help_text='price_4') price_5 = models.DecimalField(max_digits=6, decimal_places=0, null=True, help_text='price_5') price_6 = models.DecimalField(max_digits=6, decimal_places=0, null=True, help_text='price_6') price_7 = models.DecimalField(max_digits=6, decimal_places=0, null=True, help_text='price_7') Here is my method in model: def min_prices(self): prices = [self.price_1, self.price_2, self.price_3, self.price_4, self.price_5, self.price_6, self.price_7] return min(['{0}'.format(i) for i in prices if i is not None]) My values in model: price 1: 4000 price 2: 2800 price 3: 1800 price 4: 900 My code should return 900 but I got 1800 and I do not why? -
Django Pillow Image Processing
I've created a custom 'save' function for my model to automatically rename, move to the correct folder, watermark and thumbnail uploaded images. It seems to be working mostly OK now, but there's a couple of issues / bugs I'd like some help with: First the big one - if a user edits a model record but doesn't upload a new image (they just keep the existing one), the save function re-watermarks the existing image, meaning the watermark gets less transparent on every save! I think there's a fairly easy solution to this by refactoring the function do the image processing before the renaming and moving, and checking that the image is stored in "/images/temp/" before doing any image processing, but I haven't been able to get this to work. For some reason the watermark is not applied to smaller images. It works fine on larger images, but the watermark appears to be a bit too small on my 640x960 test image and doesn't appear at all on my 200x237 test image! I'm guessing this is to do with the resizing process, but tweaking the numbers there hasn't resolved it. Obviously I've been pretty lazy in writing one long save function, … -
Django password hash on Angular2
I'm trying to make Django + Angular 2. Django as backend, angular as frontend. I already made authentication using rest api and JWT. PROBLEM Problem is that when I make new user, users password is not hashed. Maybe anyone can suggest me how to send and hash password in django side or send already hashed password to django side (even better). Because if use simple MD5 hash I can't login with that user, because django is using different encripter I guess. Also as I'm using rest api, I send authentication data (username, password) and I want to also hash password and in django side decrypt it. Would be great to get any suggestions or ideas what could help me. -
Limit execution time of python eval() function in Django
Hello I have table of employees and it has a column with expression that have to be executed for each employee each time user visits page. This expression is provided by admin for each employee and manipulates with some variables. Now I'm use python's eval function to evaluate this expression Now I need a protect from expressions like 10 ** 10000000000 or some of that kind. I'm tried to use threads and UNIX signals to abort execution, but python told me that signals can be used only in main thread. And I thing that spawning background process each time can be quite expensive. Can you help me with that? -
how to generate access token from refresh token django auth_2 provider toolkit
Blockquote what is the inbuilt url for generating access_token from refresh token in this package. how can i generate a fresh access token from my old refresh token is there any url available or i have to make it custom. Blockquote -
Django (>1.9): Integrated Password Validation with Custom Messages?
I'm going to implement django's new (>1.9) integrated password validation. I'm unable to find a way to customize the error messages. Is there a way to set custom error_messages in the settings (like: form fields errors) or do I need to write my own validators? -
Django - Cant align html tabs properly
I am trying to show a list of data based on tabs. So far I was able of take the data and show it. The problem is the html part. Some parts of the html should not repeat but they have to be at least once... [![<body class="bootstrap" > <!--#INCLUDE VIRTUAL="TopNavInclude.asp" --> <div class="container"> <div class="col-md-12"> <div class="panel panel-default panel-fade"> <div class="panel-heading"> <span class="panel-title"> <div class="pull-left"> <ul class="nav nav-tabs"> {% block content %} {% for s in data_seasons %} {% if s == 1 %} <li class="active"><a href="#tab{{s}}" data-toggle="tab" ><i class="glyphicon glyphicon-send"></i> Temporada {{s}}</a></li> {% else %} <li><a href="#tab{{s}}" data-toggle="tab" ><i class="glyphicon glyphicon-send"></i> Temporada {{s}}</a></li> {% endif %} {% endfor %} </ul> </div> <div class="btn-group pull-right"> <div class="btn-group"> <a href="#" class="btn dropdown-toggle" data-toggle="dropdown"> <span class="glyphicon glyphicon-cog"></span> </a> <ul class="dropdown-menu" role="menu"> <li><a href="#">Action 1</a></li> <li><a href="#">Action 2</a></li> <li class="divider"></li> <li><a href="#">Another Action</a></li> </ul> </div> </div> <div class="clearfix"></div> </span> </div> <div class="panel-body"> <div class="tab-content"> {% for s in data_seasons %} {% for ep in data_ep %} {% if s == ep.tve_season %} {% if s == 1 %} <div class="tab-pane fade in active" id="tab{{s}}"> <h3>Episodios</h3> <FORM ACTION="" METHOD="post"> <INPUT TYPE="hidden" NAME="FormName" VALUE="PrintLetters"> <TABLE class="table table-striped"> <THEAD> <TR><TH>Selecionar</TH><TH style="text-align:left">Nome do Episodio</TH><TH style="text-align:left">Duracao</TH><TH>Data/Horario</TH><TH>Sumario</TH></TR> </THEAD> … -
change the order celery workers executes tasks from queue
I am using celery with django. I have multiple producers which are pushing in one queue, there are multiple workers. Celery default execution order of a queue is FIFO. Sometimes it so happens that one of the producer produces lots of tasks, this makes other producers starve for execution till all the tasks of that producer are finished. Is there any way to have some kind of fairness in executing tasks for all producers? -
How to pre-select dropdown on Django?
I already tried other posts with similar problems but the code I'm dealing with was made by a third party and I'm having some small problems. I simply cannot define one of the forms with the initial value I want. How to proceed? models.py class Livro(models.Model): codigo = models.AutoField(primary_key=True) nome = models.CharField("Nome", max_length=50, unique = True) autor = models.CharField("Autor", max_length=50, unique = True) edicao = models.CharField("Edição", max_length=30, unique = True) disciplina = models.ForeignKey(Disciplina) tipo = models.CharField("Tipo", max_length=20, choices = Choices.tipo) ano = models.CharField("Ano", max_length=30, choices = Choices.ano) situacao = models.CharField("Situação", max_length=30, choices = Choices.situacao, blank = True, null = True) def __unicode__(self): return self.nome views.py def cadastrar_livro(request): form = LivroForm(request.POST or None) if form.is_valid(): salvo = form.save(commit=False) salvo.situacao = "Ativado" salvo.save() return HttpResponseRedirect('/principal') return render_to_response('cadastrar_livro.html', locals(), context_instance = RequestContext(request)) and on choices.py class Choices(models.Model): tipo = ( ('1', 'Seriado'), ('2', 'Único'), ) ano = ( ('1', '1º'), ('2', '2º'), ('3', '3º'), ('4', 'Único'), ) situacao = ( ('Ativado', 'Ativado'), ('Desativado', 'Desativado'), ) I just need situacao to pre select Ativado but can't find any solutions to it. Need help thanks. -
Django Model Methods To Get Instance Count
i am developing small messaging functionality in my project . I want to get the message count using the model methods here staff will have multiple messages by same admin, so i used to distinct() to get the single row with same admin_id and And now i want to show the count of unread message by using the field (is_read=False). is there any way to do this.Somebody please help me models.py class Message(models.Model): admin = models.ForeignKey("auth.User", related_name="admin_message") staff = models.ForeignKey("auth.User", related_name="staff_message") message = models.TextField() datetime = models.DateTimeField(auto_now_add=True) is_read = models.BooleanField(default=False) def get_message_count(self): return self.filter(is_read=False).count() views.py def messages(request): template = "staff/messages.html" context = {} context["messages"] = Message.objects.filter(staff=request.user).distinct("staff") return render(request, template, context) template {% for message in messages %} <div class="message_list row"> <div class="col-md-10"> <p>{{ message.message }}</p> <span class="badge"> {{ message.get_message_count }} # here i want to get the unread message count </span> </div> </div> {% endfor %} -
I want to convert my Django project to an .exe file?
I wrap my entire django project into one exe file and I have tried Pyinstaller and cx_freeze both of which do not seem to work. Is there any alternative or using Pyinstaller can I import modules that are not being imported.? -
Python django modify help file
I would like to modify -h command in django project. I created a project but when I use my own help command python manage.py my_help I get an error about not installed modules. And this is ok, because I would like to inform user which modules are needed to install before run a project. So, when I call python manage.py my_help or python manage.py -h I want to show info about additional modules which are needed and general info about project. Now I got only error messsages like (I'm using reportlab in project) from reportlab.lib.pagesizes import A4, letter ImportError: No module named 'reportlab' Is it possible to modify default -h option or do something with my own help command to show basic info instead of an error? -
makemigrations - App 'stock_market' could not be found. is it in INSTALLED_APPS?
Edit the project/settings.py file again, and change the INSTALLED_APPS setting to include the string 'polls'. So it’ll look like this: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'stock_market' ] When I run command python manage.py makemigrations stock_market/ it gives me that error -
Django duplicate queries after prefetch related
I'm working on a fairly simple library project in Django, here are my models, a book can have many copies and each copy can have many loans. class Author(models.Model): name = models.CharField(max_length=200, unique=True) class Book(TimeStampedModel): isbn = models.CharField(max_length=13, primary_key=True) title = models.CharField(max_length=200, db_index=True, unique=True) authors = models.ManyToManyField('Author', related_name='books') @property def is_available(self): """Returns True if the Book has any available copies""" return self.copies.exclude(loans__returned=False).exists() class BookCopy(models.Model): book = models.ForeignKey('Book', related_name='copies') class Loan(models.Model): start_date = models.DateField() end_date = models.DateField() returned = models.BooleanField(default=False) customer = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, related_name='loans') book_copy = models.ForeignKey( 'BookCopy', on_delete=models.CASCADE, related_name='loans') I have a fairly simple view containing a list of books def book_list(request): book_list = Book.objects.prefetch_related('authors', 'copies__loans') return render(request, 'books/book_list.html', {'books': books}) To figure out if a book is available I've written the property is_available inside the Book model. However when I call this property inside my template with the following: {% for book in books %} {% if not book.is_available %} -- Template stuff -- {% endif %} {% endfor %} According to Django Debug Toolbar I end up with a duplicate query for every Book in the queryset My impression was that the Book.objects.prefetch_related('authors', 'copies__loans') should fetch all copies related to each book, and all subsequent loans … -
ImproperlyConfigured middleware in Django project (error importing redis function)
I'm writing a middleware for a Django app of mine where I get a variable from request.session and then have to insert it into a redis sorted set. Fairly straight forward. I.e. import os os.environ.setdefault("DJANGO_SETTINGS_MODULE","myproject.settings") from myapp.redis_functions import set_whose_online class WhoseOnlineMiddleware(object): def process_request(self, request): if '_auth_user_id' in request.session: set_whose_online(request.session['_auth_user_id']) else: pass redis_functions.py contains all redis related functions in my app. The redis connection pool is instantiated there as well. But this is giving me an ImporperlyConfigured error at import. The full traceback is: Traceback (most recent call last): File "/usr/lib/python2.7/wsgiref/handlers.py", line 85, in run self.result = application(self.environ, self.start_response) File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/django/contrib/staticfiles/handlers.py", line 72, in __call__ return self.application(environ, start_response) File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/dj_static.py", line 83, in __call__ return self.application(environ, start_response) File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 236, in __call__ self.load_middleware() File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 53, in load_middleware raise exceptions.ImproperlyConfigured('Error importing middleware %s: "%s"' % (mw_module, e)) ImproperlyConfigured: Error importing middleware unconnectedreddit.middleware.WhoseOnline: "cannot import name add_filtered_post" It's perplexing because I'm not trying to import add_filtered_post, I'm trying to import set_whose_online. add_filtered_post is another function in redis_functions.py, used entirely elsewhere. What could be possibly going on, and how can I remedy this problem? Note: the middleware is added in settings.py, and is saved at myfolder/myproject/middleware/WhoseOnline.py -
Converting amount to lakhs and crores
I want to display amount in Crores and Lakhs in my template. ( Prefer using template tag for this purpose) For example, 120 Lakhs(12000000) should be displayed as 1.2 Crore from django import template register = template.Library() from property.models import Property @register.filter def lakh_to_crore(param): price = Property.objects.values('expected_price') try: if price > 100000: price = str(float(param) / 100000) price = "%s L" % price except ValueError: price = param return price This code didn't give me the expected result. Any advanced code for doing this? -
How to make authentication in mobile apps, if Django web app hash passwords?
I have Django web application, with authentication. Hash passwords with sha2. But now, we want to make Android/iOS application. How to make authentication in mobile apps, if Django hash/unhash passwords? -
Creating beanstalkd jobs on django model signals
I want to create beanstalkd jobs when a django model is saved. For this I am listening to the model's post_save signal and the associated handler is creating a beanstalkd job like below for example (in myapp/signals.py): @receiver(post_save, sender=MyModel) def create_job(sender, **kwargs): beanstalk = beanstalkc.Connection( host='example.com', port=11300 ) beanstalk.use('test') beanstalk.puts('job'); However I do not like the fact that I am creating a new connection each time I receive a signal. My questions are: Would that be good if I connected to beanstalkd outside the function, at the top of the module and reuse the connection instead? However If I reused the connection and the connection broke for some reasons, the entire process would suffer, right? So, what would be a better solution here? -
not able to create django superuser
Well I have custom django user model: class Customer(AbstractBaseUser, PermissionsMixin): firstName = models.CharField(_('first name'), max_length=100, blank=True) lastName = models.CharField(_('last name'), max_length=100, blank=True) email = models.EmailField(_('email address'), unique=True, blank=True, max_length=150) isStaff = models.BooleanField(_('staff status'), default=False, help_text=_('Designates whether the user can log into this admin ' 'site.')) isActive = models.BooleanField(_('active'), default=True, help_text=_('Designates whether this user should be treated as ' 'active. Unselect this instead of deleting accounts.')) dateJoined = models.DateTimeField(_('date joined'), default=timezone.now) birthDate = models.DateField(null=True, blank=True) personalId = models.CharField(max_length=100) mobileNumber = models.CharField(max_length=50) # widget = models.TextField(null=True, blank=True) isDisabled = models.BooleanField(default=False, help_text=_('Disable account manually. No automatic enabling')) activateDate = models.DateTimeField(null=True, help_text=_('Date when user was activated')) failedPasswordAttemptCount = models.IntegerField(default=0) isLocked = models.BooleanField(default=False) lastLockedDate = models.DateTimeField(null=True, blank=True) lastActivateUrlSendDate = models.DateTimeField(null=True, blank=True) lastActivateUrlExpireDate = models.DateTimeField(null=True, blank=True) lastResetPassUrlSendDate = models.DateTimeField(null=True, blank=True) lastResetPassUrlExpireDate = models.DateTimeField(null=True, blank=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] And I want to create superuser, but when I use command: python manage.py createsuperuser which asks me for email and password, I have an error saying TypeError: create_superuser() missing 1 required positional argument: 'username' I am not able to fix this code, because I do not understand why I get this error, I know that createsuperuser needs USERNAME_FIELD, and that field is email … -
Django Error: "Unknown column 'categorytree.id' in 'field list'"
When running the following command via the Django shell: from myApp.models import * print Categorytree.objects.all() I receive this error message: OperationalError: (1054, "Unknown column 'categorytree.id' in 'field list'") This is what my Model looks like: class Categorytree(models.Model): level = models.IntegerField(db_column='Level') # Field name made lowercase. categorynode_idcategorynode = models.ForeignKey(Categorynode, models.DO_NOTHING, db_column='CategoryNode_idCategoryNode') # Field name made lowercase. categorynode_idancestorcategorynode = models.ForeignKey(Categorynode, models.DO_NOTHING, db_column='CategoryNode_idAncestorCategoryNode', related_name='+') # Field name made lowercase. class Meta: managed = False db_table = 'categorytree' unique_together = (('categorynode_idcategorynode', 'categorynode_idancestorcategorynode'),) Note that it does not have a Primary Key and it shouldn't have, but Django seems to think there would be an Primary Key .id Field. -
How to get a property of a many to many relationship in python/django
I'm trying to get the theme slug as parameter in a url in my post_detail template. Post and Theme have a many-to-many relationship and in my post_detail page I'm showing one single post. The link I want to show on this page should link to a page showing all posts beloning to a theme. This page is already working and is called theme_posts_list. Views.py: class ThemesOverview(ListView): """ Overview of all themes """ model = Theme template_name = 'content/theme_list.html' class ThemePostsOverview(ListView): """ Overview of all posts within a theme """ model = Post template_name = 'content/theme_posts_list.html' # function to get the theme model based on the current theme by slug def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super(ThemePostsOverview, self).get_context_data(**kwargs) theme_slug = self.kwargs['slug'] context['theme'] = Theme.objects.get(slug=theme_slug) return context # function to get all posts belonging to a theme slug def get_queryset(self): slug = self.kwargs['slug'] self.theme = Theme.objects.get(slug=slug) return self.theme.post_set.all() class PostDetailview(DetailView): """ Detail view of a post """ model = Post template_name = 'content/post_detail.html' Models.py: class Post(Base, models.Model): header_image = FilerImageField(verbose_name=_('header afbeelding'), blank=True, null=True, on_delete=models.SET_NULL, help_text=_('Header afbeelding')) author = models.ForeignKey(Author, blank=True, null=True) title = models.CharField(max_length=200, blank=False) slug = models.SlugField(_('slug'), max_length=255, blank=False, unique=True, help_text=_('Laat leeg … -
Django Admin - 'ManyToManyField' object has no attribute 'through'
tl;dr Django throws an AttributeError when I try to render admin class with ManyToMany relation through custom form using fields or fieldsets attributes, apart from form attribute: AttributeError: 'ManyToManyField' object has no attribute 'through' Models: I have two models binded with ManyToMany relation: class Project(models.Model): title = models.CharField(max_length=200, unique=True) class Centre(models.Model): projects = models.ManyToManyField( Project, blank=True, related_name='centres', ) Form: Also, I've created a custom form for a Project model to add FilteredSelectMultiple field for Centre: class ProjectAdminForm(forms.ModelForm): centres = forms.ModelMultipleChoiceField( Centre.objects.all(), widget=admin.widgets.FilteredSelectMultiple('Centres', False), required=False, ) def __init__(self, *args, **kwargs): super(ProjectAdminForm, self).__init__(*args, **kwargs) if self.instance.pk: self.initial['centres'] = self.instance.centres.values_list( 'pk', flat=True ) def save(self, *args, **kwargs): instance = super(ProjectAdminForm, self).save(*args, **kwargs) if instance.pk: instance.centres.clear() instance.centres.add(*self.cleaned_data['centres']) return instance Admin: The thing is, when I define admin class like this: @admin.register(Project, site=admin_site) class ProjectAdmin(admin.ModelAdmin): form = ProjectAdminForm It works fine and renders a correct form for title and centres fields. However, If I define fields as such: @admin.register(Project, site=admin_site) class ProjectAdmin(admin.ModelAdmin): form = ProjectAdminForm fields = ('title', 'centres', ) This throws an AttributeError: AttributeError: 'ManyToManyField' object has no attribute 'through' I've tried setting through attribute on models.ManyToManyField in Project model, defining intermediary ProjectCentresModel, but I still can't understand what is going on inside Django … -
Getting " hudson.plugins.git.GitException: Command "git config remote.origin.url " in jenkins
I am trying to automate the git pull operation from gitlab on my production server. I am using digital ocean ubuntu server . I have followed the following tutorial "https://medium.com/@mondaini/assembling-a-continuous-integration-service-for-a-django-project-on-jenkins-5f979d4c4184#.q88mrsjy3" .But on build i am getting the "hudson.plugins.git.GitException: Command "git config remote.origin.url" error . Please help !! exception