Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django add a field in a queryset
I have a queryset that contains a field named 'foo' defined in a Bar model. result = Bar.objects.values('foo').distinct() I would like to return a queryset containing 'foo' and a slug version of 'foo'. How can I do that without creating a new field in my Bar model? -
Django Form Errors not showing, until put "print context['form']" to get_context_data
I was tried to show some errors after form validation, I have tried lots of solutions from topics and nothing helped me. Now I just put a "print context['form'] " into the get_context_data in class based view and errors are printed. It looks so strange and I wanted to ask for help. template.py {% extends "seffaf/adminblank.html" %} {{ form.media.css }} {% block content %} <style> #id_staff { width: 100% !important; } #id_doctor{`enter code here` width: 100% !important; } #id_address{ width: 100% !important; } </style> <section class="wrapper"> <div class="row mtbox"> <div class="col-lg-12 main-chart"> ### This block prints out success message### {% if messages %} <div class="alert alert-success"> {% for m in messages %} <li {% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ m }}</li> {% endfor %} </div> {% endif %} ####### ### This block tries to print out error messages and it fails ### {% if form.non_field_errors %} <ul> {{ form.non_field_errors.as_ul }} </ul> {% endif %} {% for field in form.visible_fields %} {% for err in field.errors %} {{ err }} {% endfor %} {% endfor %} {% if form.errors %} asdasdasdasdsadas {% for field in form %} {% for error in field.errors %} <p> {{ error}} </p> {% … -
Django: Using a variable as the URL namespace?
I'm trying to create a submenu for a sports site. Each sport would need its own submenu. The problem I'm having is I need the namespace itself to be dynamic in someway. SportListView returns the sport so I can then filter the news articles by the sport. Views: class SportListView(ListView): template_name="sports/sport-home.html" context_object_name='sport_list' def get_context_data(self, **kwargs): context = super(SportListView, self).get_context_data(**kwargs) context['sport_menu'] = get_object_or_404(Sport, sport_slug=self.kwargs['sport_slug']) return context Template: <nav class="navbar navbar-expand-lg main-nav"> <a href="{% url 'sports:sport-home' sport_menu.sport_slug %}"> {{sport_menu.name}}</a> <a href="{% url sport_menu.sport_slug 'monthly' %}">Monthly View</a> </nav> The first link in the submenu works fine. As you can see it effectively acts as a home button for each sport. The second link does not on the other hand. In the error message it returns the slug of the sport but I can't get that to act as the namespace. I do have an app and its URLs.py file configured correctly for the current sport as well by the way. So I know that isnt the problem. edit: Current error message I'm getting withi this configuration is: Reverse for 'cricket' not found. 'cricket' is not a valid view function or pattern name. -
Get average lifetime by subtracting nearest objects in QuerySet?
I've got models which is used to persist status change from prev_status to next_status to gather a statistics: class StatusStat(models.Model): class Status: ACTIVATED = 0 IN_RESERVE = 1 BANNED = 2 STOPPED = 3 DELETED = 4 owner = models.ForeignKey(... , related_name='status_stats') prev_status = models.IntegerField(blank=False, null=False) next_status = models.IntegerField(blank=False, null=False) created = models.DateTimeField(auto_now_add=True) I need to write a query to take average lifetime of an owner by calculating average duration of switching status from IN_RESERVE to ACTIVE then from ACTIVE to BANNED or DELETED among each status change. So I need to substract two "created" fields and find the average of this duration for each owner in one query. Is it possible to do that in one query using Subquery may be ? owner.aggregate(avg_lifetime=Avg(Subquery(...Substraction code ...))) -
Django request.user is anonymous in views without login_required decorator
I am working on a Django (v2.0) app with django-allauth as auth backend. I'll explain my problem in steps: User logs in -> user redirected to home page (can't access home page without login) In the home page (after logging in), several calls are made for a particular view in the server. Ex: https://mywebsite.com/api/getstuff/123 Problem: getstuff returns/prints data that is intended for a user who is NOT logged in. getstuff is defined in urls.py as: url(r'^api/getstuff/(?P<hash_code>[a-zA-Z0-9]{3})$', views.getstuff, name='getstuff') in views.py: (views.getstuff) @csrf_protect @ensure_csrf_cookie def getstuff(request,hash_code): if request.user.is_authenticated: #do stuff.... print('user is authenticated!') return HttpResponse(hash_code+'foo-auth') else: #do other stuff.. print('user is NOT authenticated') return HttpResponse(hash_code+'foo-un_auth') I only see user is NOT authenticated being printed in my case. Shouldn't the output be user is authenticated since the user is already logged in? the request.user object is an AnonymousUser object. All the requests I make are from https. few configurations from settings.py: CSRF_USE_SESSIONS = True CSRF_COOKIE_SECURE = True #tried removing this, still same result as above INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django_extensions', 'django.contrib.sitemaps', 'mysite.core', 'bootstrapform', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', 'allauth.socialaccount.providers.google', 'allauth.socialaccount.providers.github', 'allauth.socialaccount.providers.twitter', 'embed', 'channels', 'djcelery' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] AUTHENTICATION_BACKENDS … -
get_succes_url with arguments after creation
I have 2 sections, one for normal users and one for admins (not related to Django admin). I have, for example, a Product Model. In the Model I use get_absolute_url to set the detail url for normal users. The Product creation is in the Admin area and the succes_url, needs to go the newly created Product. I need to get the new pk and use it the get_succes_url. def get_success_url(self): return reverse_lazy('accounts:detail_company', kwargs={'pk': self.pk}) will give me the following error: 'AccountCompanyCreateView' object has no attribute 'pk' -
Django models renaming
What is the best way to rename a Django model which is a foreign key to other models? Say, Model A is a foreign key to model B and C. Rename model A to Base. Just renaming and migrating causes errors (running migrations throws error: psycopg2.IntegrityError: insert or update on table X violates foreign key constraint Y.) Tried using RenameModel in migration (with the AlterField for B and C in migration file), the models B and C, which has A as foreign_key, throws errors. Can the migration not include the AlterField for B and C (from to='A' to to='Base')? Would it still apply changes to B and C with ForeignKey now pointing to Base? -
how to use template tag in if condition django?
my template tag:- @register.filter("participants_count_in_sessions") def participants_count_in_sessions(session_id): class_session_participants_count = ClassJoin.objects.using('p5M').filter(classSession=session_id).count() return class_session_participants_count and how i am using it in my templates inside if:- {% for item in data_list %} <td class="text-center">{% if item.id | participants_count_in_sessions %}<a href="#">{% endif %}{{ item.id | participants_count_in_sessions }}</a></td> {% endfor%} and error i am getting by using this way:- TemplateSyntaxError at /session-on-the-basis-of-class/1/ Could not parse the remainder: '|' from '|' -
Select a valid choice error
Form renders on the template correctly and it gets the initial values for the hidden inputs and it shows the correct choices and the values for the choices. But when saving the form I get the Select a valid choice. That choices is not one of the available choice error. The error shows for the qanswermix_question line. When viewing the rendered page source, it shows the correct id for each question. If you have questions please ask. models.py class QuestionAnswerMix(models.Model): qanswermix_questionnaire = models.ForeignKey(Questionnaire, null=False, blank=False) qanswermix_question = models.ForeignKey(Question, null=False, blank=False) qanswermix_business_id = models.ForeignKey(Business, null=False, blank=False) qanswermix_answer = models.CharField(max_length=1, null=False, default=None, blank=False) def __str__(self): return self.qanswermix_answer forms.py class TimeAnswerForm(forms.ModelForm): class Meta: model = QuestionAnswerMix fields = '__all__' exclude = [] widgets = { few hidden inputs here 'qanswermix_question': HiddenInput, } views.py def mix_survey_page(request, questionnaire_pk): TimeAnswerFormSet = formset_factory(TimeAnswerForm, extra=0) time_questions = MixQuestion.objects.filter(question_questionnaire=questionnaire_pk).filter(question_type=1) name_questionnaire = Questionnaire.objects.get(id=questionnaire_pk) if request.method == 'POST': time_answer_formset = TimeAnswerFormSet(request.POST) if time_answer_formset.is_valid(): for time_answer_form in time_answer_formset: if time_answer_form.is_valid(): instance = time_answer_form.save(commit=False) instance.qanswermix_question = time_answer_form.cleaned_data.get('qanswermix_question') ... return redirect('main:mix_results') else: return redirect('main:home') else: business_id = request.session.get('business_id', '0000000000000000') qid = request.session.get('questionnaire_key', 0) time_question_initial = [{'qanswermix_question': question, 'qanswermix_business_id': business_id, 'qanswermix_questionnaire': qid} for question in time_questions] time_answer_formset = TimeAnswerFormSet(initial=time_question_initial) combined_time = zip(time_questions, time_answer_formset) context = … -
What is fit file
I want know to what is fit file.And how to use these files in python please provide me some information any links or any blogs I need information regarding python parsing fit file -
Purpose of admin.py file in app in Django project?
What is the purpose of admin.py file in django project? I created a app using: python manage.py startapp app This is the code found in admin.py file from django.contrib import admin from .models import Post admin.site.register(Post) # Register your models here. -
Python/django application not running with supervisord
I am trying to run Python Django app via supervisor with below configuration file. [program:test3] command=python manage.py runserver directory=/home/ubuntu/code/example/current/project/ stdout_logfile=/var/log/test3.log stderr_logfile=/var/log/test3.log user=ubuntu environment=PATH="/home/ubuntu/code/example/bin/",PROJECT_ENV="dev" autostart=true autorestart=true startsecs=10 stopwaitsecs=600e autorestart=true startsecs=10 stopwaitsecs=600 After running I was able to see there are 2 python process running at the moment. ubuntu 29853 0.1 2.0 354468 41196 ? Sl 11:33 0:00 python manage.py runserver ubuntu 29860 1.1 3.4 516944 69768 ? Sl 11:33 0:04 /home/ubuntu/code/analytics/bin/python manage.py runserver I have mentioned the log file under supervisord config file and was able to see the below error in "/var/log/test3.log". Error: ImportError: No module named pyspark.ml.evaluation I have already fulfilled all pip requirements in the directory. Any idea? -
reverse proxy nginx rewrite uwsgi redirect response of location
My configuration now is nginx + uwsgi + different django apps. My configuration for nginx is configure as follow: location /app1/ { uwsgi_pass app1; include /home/code/uwsgi_params; # the uwsgi_params file you installed } location /app2/ { uwsgi_pass app2; include /home/code/uwsgi_params; # the uwsgi_params file you installed } and I also set the mount point in uwsgi in order to make the reverse proxy works. something like this: mount = /app1=app1.wsgi:application manage-script-name = true because my app require login before access the content of the website. So when I type www.example.com/app1 Uwsgi will return a 302 redirection response back: < HTTP/1.1 302 Found < Server: nginx/1.10.3 (Ubuntu) < Date: Mon, 11 Dec 2017 10:30:47 GMT < Content-Type: text/html; charset=utf-8 < Content-Length: 0 < Connection: keep-alive < Location: /login/?next=/app1/ < X-Frame-Options: DENY < Vary: Cookie Nginx will follow the link in location, however, because this location is not /app1/login/?next=/app1/ so it is unable to send the request to uwsgi. Instead, it trys to find login/?next=/app1/ locally in its root. How can I rewrite the redirect response with correct prefix? Should configure on nginx side or on uwsgi side? -
How can I add a document on a StreamField in Wagtail CMS?
I've a question about Wagtail CMS. Recently I'm trying to import programmatically some documents in a StreamField of an instance of a Wagtail Page model. I've done some researches but without results. Currently I'm using: Wagtail 1.13 Django 1.11.6 Python 2.7 Here the model of the page in which I need to import the documents as attachments (see the homonym field): class EventPage(TranslatablePage, Page): # Database fields uuid = models.UUIDField(verbose_name='UUID', default=uuid.uuid4) start_date = models.DateField(verbose_name='Start date') end_date = models.DateField(verbose_name='End date') location = models.CharField(verbose_name='Place', max_length=255, null=True, blank=True) body = RichTextField(verbose_name='Body') attachments = StreamField(blocks.StreamBlock([ ('document', DocumentChooserBlock(label='Document', icon='doc-full-inverse')), ]), verbose_name='Attachments', null=True, blank=True) subscribe = models.BooleanField(verbose_name='Subscribe option', default=False) # Editor panels configuration content_panels = [ FieldPanel('title', classname='title'), MultiFieldPanel([ FieldRowPanel([ FieldPanel('start_date'), FieldPanel('end_date'), ]), ], heading='Period'), FieldPanel('location'), FieldPanel('body'), StreamFieldPanel('attachments'), ] promote_panels = Page.promote_panels + [ MultiFieldPanel([ FieldPanel('subscribe'), ], heading='Custom Settings'), ] settings_panels = TranslatablePage.settings_panels + [ MultiFieldPanel([ FieldPanel('uuid'), ], heading='Meta') ] parent_page_types = ["home.FolderPage"] subpage_types = [] On shell, I tried to apply the solution explained on this page but without success. event = EventPage.objects.get(pk=20) doc = Document.objects.get(pk=3) event.attachments = [ ('document', [ StreamValue.StreamChild( id = None, block = DocumentChooserBlock(), value = doc ) ] ) ] Python give me this error: AttributeError: 'list' object has no … -
AttributeError: module ... has no attribute 'CustomRegisterSerializer'
I am trying to use a custom register serializer with django-rest-auth. I followed the steps in this example rest-auth custom register serializer The name of the users app is myapp.users and the serializer file is in that app. in the serializers file I have class CustomRegisterSerializer(RegisterSerializer): ... in settings.py REST_AUTH_REGISTER_SERIALIZERS = { "REGISTER_SERIALIZER":'myapp.users.serializers.CustomRegisterSerializer', } But this error keeps coming AttributeError: module 'myapp.users.serializers.CustomRegisterSerializer' has no attribute 'CustomRegisterSerializer' What do you think I'm missing? -
Developping a dashboard with Django to monitor Vmware Esxi Infrastructure
i'm a CyberSecurity Engineering Student, Currently working on a project that consists of creating a virtual environment (IaaS) and securing it. We used Vmware ESXI to host our data Center and later on upgraded to vsphere. We were asked to develop a dashboard using python framework "Django" to monitor our infrastructure. All i'm asking from the community is to point me at the right direction. a simple advice or a link may be of a great help. Simple questions that cross my mind: - how to intercept data from the hypervisor ? - how to integrate the API/SDK of vsphere in the dashboard ? - Is Django that powerful in such situations ? - from where do i have to start ? Thank you in advance. -
CanvasJS and Django JSON Issue
I'm trying to do a very simple connection between a Django application (with sqlite) and a Canvas JS chart. Somehow I am tripping up on the Javascript Array / Object data into Cancas JS. view.py (access data from last 15 hours) def getLogs(request): time_threshold = datetime.now() - timedelta(hours=15) response = JsonResponse(dict(logs=list(Log.objects.values('datetime', 'value').filter(datetime__gt=time_threshold) ))) return response logs.html <script> var endpoint = '/api/data/' $.ajax({ method: "GET", url: endpoint, success: function(data) { var dataPoints = []; var chart = new CanvasJS.Chart("chartContainer", { // Other Chart Settings data: [{ dataPoints: dataPoints }] }); function addData(data) { for (var i in data) { dataPoints.push({ x: new Date(data[i].datetime), y: data[i].value }); } chart.render(); } addData(data.logs); }, error: function(error_data){ console.log("Error") console.log(error_data) }, }) </script> The issue appears to be around the the format of dataPoints. Is it JSON? Is it an object? Is it an array? Can CanvasJS read it? I simply end up with a blank chart (with a correct Y Axis) Any thoughts? Thanks! -
The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute
Before I ask this question, I have read this related post. In my settings.py: INSTALLED_APPS = [ ... 'corsheaders', ] CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST = ( 'http://103.200.30.76' ) My website frontend is use Apache listen 80 port, and I use python3 manage.py runserver 103.200.30.76:8001 But I still get the bellow error: Failed to load http://103.200.30.76:8001/api/website/websitemanage/footerreconmend/list/: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://103.200.30.76' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute. One of the request is like this: General: Request URL:http://103.200.30.76:8001/api/website/websitemanage/homepagefunctionshow/list/ Request Method:OPTIONS Status Code:200 OK Remote Address:103.200.30.76:8001 Referrer Policy:no-referrer-when-downgrade Response Headers Access-Control-Allow-Credentials:true Access-Control-Allow-Headers:accept, accept-encoding, authorization, content-type, dnt, origin, user-agent, x-csrftoken, x-requested-with Access-Control-Allow-Methods:DELETE, GET, OPTIONS, PATCH, POST, PUT Access-Control-Allow-Origin:http://103.200.30.76 Access-Control-Max-Age:86400 Content-Length:0 Content-Type:text/html; charset=utf-8 Date:Mon, 11 Dec 2017 02:44:12 GMT Server:WSGIServer/0.2 CPython/3.5.2 Vary:Origin X-Frame-Options:SAMEORIGIN Request Headers: Accept:*/* Accept-Encoding:gzip, deflate Accept-Language:zh-CN,zh;q=0.9,en;q=0.8 Access-Control-Request-Headers:access-control-allow-origin,x-requested-with Access-Control-Request-Method:GET Connection:keep-alive Host:103.200.30.76:8001 Origin:http://103.200.30.76 User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36 So, who can help me with this, please? -
OSMWidget / map in form template
I'm trying to display the OSMWidget in a form using generic CreateVIew and UpdateView by overwriting the defaults using a Meta class models.py class Building(models.Model): point = PointField('kort markør', null=True) country = models.CharField('land', max_length=100, blank=True, null=True, default='Danmark') city = models.CharField('by', max_length=100, blank=True, null=True) views.py from django.contrib.auth.mixins import LoginRequiredMixin from django.urls import reverse_lazy from django.views.generic import ListView, CreateView, UpdateView, DeleteView, DetailView from django.contrib.gis import forms from buildings.models import Building class BuildingCreateView(LoginRequiredMixin, CreateView): model = Building template_name = 'cms/building_form.html' fields = ['point', 'city', 'country'] class Meta: point = forms.PointField(widget= forms.OSMWidget(attrs={'map_width': 800, 'map_height': 500})) buildings_form.html {% block content %} <form enctype="multipart/form-data" method="post" action=""> {% csrf_token %} <ul> {{ form.as_ul }} </ul> <input type="submit" value="Submit"/> </form> {% endblock %} But the map don't show in the template, but it just shows up as an empty div. If I inspect the elements I can see this. <li> <label for="id_point">Kort markør:</label> <style type = "text/css"> # id_point_map { width: 600px; height: 400px; } # id_point_map .aligned label { float: inherit; } # id_point_div_map { position: relative; vertical-align: top; float: left; } # id_point { display: none; } </style> </li> I'm not quite sure where in Django docs I should be loooking. Not sure what I don't … -
Questions about the Internal of FormTools
To use FormPreview I should subclass it and use it as View(?). But FormPreview is not a view. How does this works? FormPreview has a lot of methods. Where are they called? For example post_post. It is never called in the FormPreview Class it is not called in not called by django. Or at least my grep -inRI post_post did not find its usage. How does that work? If I set some attribute like self.number = 42 in process_preview (subclassed and overridden method), then I can access this in the done-method. So I guess I am working on the same object. But I don't know how the Object life cycle works. Can someone explain? -
Getting data from multiple databases with same tablenames in django
I need to get data from different imported mysql-databases in django (Django 1.11.7, Python 3.5.2). I run manage.py inspectdb --database '<db>' and then use the models in django. Until now, I only had to access tables with different names. For this purpose, I used the using keyword in the queryset to specify the appropriate database and then concatenated the result, like this: from ..models.db1 import Members from ..models.db2 import Actor context['db1_data'] = Members.objects.using('db1').filter... context['db2_data'] = Actor.objects.using('db1').filter... context["member_list"] = list(chain( context["db1_data"], context["db2_data"], )) return context Now I have the problem that there are tables with the same model names in two databases. I get the following error when using the above-mentioned method (I substituted the names): RuntimeError: Conflicting '<table-name>' models in application '<app>': <class '<app>.<subfolder>.models.<db1>.<table-name>'> and <class '<app>.<subfolder>.models.<db2>.<table-name>'>. I already tried importing the model with a different name, like this: from ..models.db3 import Members as OtherMembers but the error still comes up. Shouldn't from ..models.db1 and from ..models.db2 be clear enough for django to spot the difference between the two models? One option would probably be to rename the models themselves, but that would mean to rename every database model with same names. Since I will use many more databases in … -
How to count more than one fields and grouping them using django orm
I am a newbie to Django and its ORM. Table User is having many users. I need to group active users and total users from the table and also I need to order them based on the year they have joined using Django ORM in sql, This could be like, select count('users'), count('users' where is_active is True as 'active_users') form user order by 'created_at' -
Is else necessary with a Django pre_save signal?
Model named Scorecard. Scorecard has a name CharField with unique. I save .csv files to media folder. I am trying to create a pre_save signal that gets the old name (because it may have changed) and checks for .csv file in media to delete it. When my signal code below is commented out and I create a new instance, a .csv is created in my media folder as-desired. When I uncomment my signal below, a .csv file is only outputted when I edit and save an existing instance but not when I create one. @receiver(pre_save, sender=Scorecard) def file_delete_handler(sender, instance, **kwargs): print('INSTANCE ID:', instance.pk) if instance.pk is not None: old = Scorecard.objects.get(pk=instance.pk) print(old.name) file_path = os.path.join(MEDIA_ROOT, ''.join([old.name, '.csv'])) if os.path.exists(file_path): os.remove(file_path) I suspect this has to do with the fact that this is an if statement without an else? I've tried else: return and else: pass. What am I not understanding? If instance is None, am I supposed to do something? Note: I realize going off of the name as the file name is probably poor practice. I'll probably fix that part later by slugifying it or something. -
Prefetch object and slice
I'm trying to do a slice inside a Prefetch object def get_queryset(self): qs = super().get_queryset() return qs.prefetch_related( Prefetch('products', queryset=Product.objects.order_by('-updated_at', '-created_at')[:3])) but I get the following error: Cannot filter a query once a slice has been taken. I found the following post about it: prefetch_related with limit but the solution, doesn't work in my case, using timedelta you don't know how many you get. Also the question is more than 3 years old, so I hope, in meantime some solutions, changes to Django occurred(something that support multiple databases) -
Adding Module Mapping in IIS 8 to run python 3.6.3 web services asks for .exe or .dll extensions
I am trying to run my python(3) web service using IIS 8 following the instruction provided here Everything is fine to the point where I try to add "FastCgi Module" in "Add Module Mapping" section. The problem is when I click on OK on "Add Module Mapping" window, the error pops up: The specified executable for the handler must be .dll or .exe file. If the path to the script processor (only in the case of a .exe file) has spaces, use " marks to specify the executable. I suppose there has to be a FastCgi.dll? Is there a better way to achieve that? P.S: I have read an ample of instructions regarding running python 2.6 web services on IIS using ISAPI_WSGI Handler and there are warnings regarding using it on later python versions, I wonder if that instructions hold up using python 3.3.6.