Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to filter in prefetch_related columns?
I have this code, where I combine a list of articles to their (translated) descriptions: desc = models.ArticleDescription.objects.filter(lang__iexact=translation.get_language()) c = models.Article.objects.all().order_by('articleid').prefetch_related( Prefetch('articledescription_set', queryset=desc, to_attr='description_tr')) this works fine, but how can I now filter the descriptions? Let's say I only want the description "foo". I am looking for something like this: desc = models.ArticleDescription.objects.filter(lang__iexact=translation.get_language()) c = models.Article.objects.all().order_by('articleid').prefetch_related( Prefetch('articledescription_set', queryset=desc, to_attr='description_tr')). filter(description_tr__description="foo") But that doesn't work. How can I achieve this? -
CSRF verification failed. Request aborted. (Forbidden (403)) DJANGO
I'm trying to get POST from 2 diferents dropdown, I had get the parametres from the POST, but i get problems with the CSRF token .... index.html <form method="post" action="/getdata/">{% csrf_token %} <select name="Lista"> <option selected="selected" disabled>Objects on page:</option> <option value="10">10</option> <option value="20">20</option> <option value="30">30</option> <option value="40">40</option> <option value="50">50</option> </select> <select name="Lista2"> <option selected="selected" disabled>Objects on page:</option> <option value="10">10</option> <option value="20">20</option> <option value="30">30</option> <option value="40">40</option> <option value="50">50</option> </select> <input type="submit" value="Select"> </form> in spite of I use the csrf token in my html form, it didn't worked ... views.py from django.http import HttpResponse from django.template import loader from django.shortcuts import render from view.forms import * from django.shortcuts import render_to_response, redirect from view.models import * def index(request): if request.method == 'POST': Lista = request.POST.get('Lista') print "Lista 1 "+Lista Lista2 = request.POST.get('Lista2') print "Lista 2 "+Lista2 #FORMS form = FormsLista(request.POST) if form.is_valid(): newPost = Lista(num_lista_1=Lista, num_lista_2=Lista2) newPost.save() context = { 'Lista': Lista, 'Lista2': Lista2 } return render(request, 'showdata.html', context) else: template = loader.get_template('index.html') return HttpResponse(template.render()) models.py from django.db import models class Lista (models.Model): num_lista_1 = models.CharField(max_length=100, null=True) num_lista_2 = models.CharField(max_length=100, null=True) def __unicode__(self): return self.num_lista_1 I have the cookies activated by the way ... -
How save to model from a string as fieldname?
I'm trying to save some informations to my model, since my list of fieldname is dynamic I'd like to loop and save those informations to the fields rather than using conditions. models.py class Company(models.Model): name = ... email = ... phone = ... ... views.py text_fields = ['name', 'email', 'phone', 'organisation', 'address', 'website'] #dynamic list, might change depending the user's interaction. for index, json_dt in enumerate(data): #data consists of JSON texts = json_dt['texts'] for text in texts.values(): for field in text_fields: # <-- loop through the list of fieldnames if text['key'] == field: # if json key is equal to fieldname person.field = text['fields']['text'] # save the JSON key's value to the field # Doesn't work because field is a string. How can I achieve this ? -
Can't find my VM instance (Debian) in Google Compute Root user and Super user Password
In my VM instance I have username the same as my email address (without @gmail.com). It is created automatically, and I do not know the password for it. Also, another user which is a root user,and I do not know the root password. I need it because when I try to run fab secure it will ask me for the password whether I'm running it using a root user or another superuser. Please help. -
Check user permission in template (not request user)
Hello is there any way to check perms of custom user nit request user in template. Code example: {% for agency_user in users %} <tr> <td>{{ agency_user.username }}</td> <td>{{ agency_user.get_full_name }}</td> <td>{{ agency_user.groups.all.first.name }}</td> <td>{{ agency_user.min_price }}</td> <td>{{ agency_user.max_price }}</td> {% if agency_user|has_perm:'may_see_commerce_sell' %} #not working <td>some action</td> {% else %} <td>some action</td> {% endif %} <td> <a href="{% url 'user_edit' agency_user.id %}" class="edit icon"></a> <a user-id="{{ agency_user.id }}" class="trash icon" title="some action"></a> </td> </tr> {% empty %} <td style="text-align: center" colspan="11">some action</td> {% endfor %} Or I have to write custom model methods to each user permission? -
Where's the best place to transform snake-case api responses to javascript's camelcase properties
I have a django API which describes resources using snake_cased json. I also have a React app which consumes the API. I could map the snakecased properties in different locations, ex, in the API renderer, or at the component level. Is there a best practice on where to apply this transformation? -
how to use one for loop key with another for loop key in django template
i able to print values from below code in django views subMarks = [] for item in marks: for column in gridHeaderTableData: subMark = item[column['sub_exam_name']] subMarks.append(subMark) how to write above code in django templates -
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?