Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ForeignKey model query filter
Using filter(), how do I get the foreign key property 'recipient' of the current authenticated user ? Models.py: class Message(models.Model): recipient = models.ForeignKey(CustomUser, on_delete = models.CASCADE,related_name = 'recipient',null = True) sender = models.ManyToManyField(CustomUser,related_name = 'messages') date = models.DateTimeField(auto_now_add=True, blank=True) subject = models.CharField(max_length = 1000, blank = True) message = models.TextField(blank=True, null=True) unread = models.BooleanField(default = True) class CustomUser(User): user_bio = models.TextField(blank=True, null=True) birth_date = models.DateField(null=True, blank=True) def __str__(self): return self.username Views.py: ### Inbox list class class InboxListView(ListView): ''' This view lets the user view all the messages created in a list ''' model = Message# [Message,SafeTransaction] # I want to be able to draw from two models/objects # template_name = "myInbox/inbox.html" paginate_by = 5 def get_context_data(self, **kwargs): context = super(InboxListView, self).get_context_data(**kwargs) context['message_list'] = Message.objects.filter(recipient=CustomUser.SOMETHING_idk)#INCORRECT FILTRATION, FIX ASAP!!!!!!!!!!!!!# context['now'] = timezone.now() context['safeTransaction_list'] = SafeTransaction.objects.all() return context Specifically this line is what I need puzzled out : context['message_list']=Message.objects.filter(recipient=CustomUser.SOMETHING_idk) What can I put as the filter parameter for a specific message recipient ? I tried something along the lines of CustomUser or CustomUser.pk, or request.authenticated_as_the_thing_I_want_specifically. etcetera. I seem to be a bit lost with it. any help at all is appreciated. -
django only allow to add new items to m2m field when update
I have a m2m field as - sizes = models.ManyToManyField(Size,blank=True,related_name='doto_sizes', default=5) I am using generic update view for updating model, but what I want is while updating sizes user is only able to add new sizes. He/she not allowed to remove initial sizes. To make it possible, I can define custom validations in clean method, but I am here because it is possible that django have built in method for that. I even don't want that user can remove initial sizes in update form, How can I make it possible ? -
Protect deletion of ForeignKey
Is it possible to ensure that ForeignKey can't be deleted? The best example is on UserProfile: class UserProfile(Model): user = models.OneToOneField('User',on_delete=models.CASCADE ...) And there is a signal which creates a UserProfile for given User right after User object is created. I want to be sure that nobody can delete UserProfile because every User has to have one UserProfile. I tried on_delete=models.PROTECT but it doesn't allow User to be deleted instead of UserProfile. -
Call a view from Django admin page
I want to call a view function from admin page. On clicking a button. How to add a button in admin so after click it's automatic call a view function ? -
Improperly Configured Django
I'm new to Django and Python. I try to create a project with the help of official tutorial on its website. Now I'm at the part 6 ("Customize your app’s look and feel") and I have a problem. When I run server (python manage.py runserver) everything is OK, I can even vote here http://127.0.0.1:8000/polls/1/results/, but when I try to go at http://localhost:8000/polls/ I have such problem enter image description here . May someone explain how can I solve this problem? What should I check in my code? I did everything the same as at the tutorial. Any help would be very appreciated! 1)...\mysite\polls\views.py from __future__ import unicode_literals from django.shortcuts import get_object_or_404, render from django.http import HttpResponseRedirect from django.urls import reverse from django.views import generic from django.utils import timezone from .models import Choice, Question class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_qeryset(self): """Return the last five published questions.""" return Question.objects.order_by('-pub_date')[:5] class DetailView(generic.DetailView): model = Question template_name = 'polls/detail.html' def get_queryset(self): """ Excludes any questions that are not published yet. """ return Question.objects.filter(pub_date__lte=timezone.now()) class ResultsView(generic.DetailView): model = Question template_name = 'polls/results.html' def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExis): return render(request, 'polls/detai.html', { 'question': … -
It is not loading or showing the picture in the Django first page and how to fix menu bar?
Django users! I need your help...please reply it when you know answer. I have two Questions First one is that it not showed pix in the first page. This is code which is in templates/home.html {% extends "base.html" %} {% block title %}home.html{% endblock %} {% load staticfiles %} {% block extrastyle %}{% static "css/home.css" %}{% endblock %} {% block content %} <div id="content_home"> <div id="homeimg"> <a href="/"><img src="{% static 'img/django_first_page.jpg' %}" style="height:256px;"/></a> <h4 style="margin: 0;">This is MEMI ABL LAB #Powered by Python#</h4> </div> It doesn't load the picture that i want And second question is: As you can see in the picture that I attached, how it shows the wrong way that I expect... Do you know how to fix it?! i want to make the yellow box -
using login view and UserCreationForm at the same time on the one page
I struggle with Django for a few days and the most unpeasant thing is that it actually hard to find answer on Internet. I'm practicing with login/register forms and authentication in general. Firstly, I had my own login and registration form but when I found out that Django has it's own built-in login system from django.contrib.auth.views, I tried to use one and stuck with the problem that login is the whole view and it ignores my registration form. So, simply it has to look like a block where I can switch to login or to register, depending on my needs but the only login form appears. I am looking for the solution which allows me to combine both forms on the one one page. urls.py: urlpatterns = [ url(r'^admin/', admin.site.urls), path('', login, {'template_name':'index.html'}), path('accounts/', views.account)] forms.py: class login_form(forms.Form): email = forms.EmailField(widget=forms.EmailInput( attrs={ 'class':'form-control', 'placeholder':'Enter email', } )) password = forms.CharField(widget=forms.PasswordInput( attrs={ 'class':'form-control', 'placeholder':'Enter password', } ) ) class register_form(UserCreationForm): username = forms.CharField(required=False, widget=forms.HiddenInput()) email = forms.EmailField(required=True, widget=forms.EmailInput( attrs={ 'class':'form-control', 'placeholder':'Enter email' } )) password1 = forms.CharField(required=True, widget=forms.PasswordInput( attrs={ 'class':'form-control', 'placeholder':'Enter password' } )) password2 = forms.CharField(required=True, widget=forms.PasswordInput( attrs={ 'class': 'form-control', 'placeholder': 'Confirm password' } )) class Meta: model = User … -
django zip unequal lists
I have 2 queries that you can find print results as below. <QuerySet [{'swtype': 1}, {'swtype': 2}]> <QuerySet ['201;203;205', '207;208']> I looked some commands at stackoverflow for pairing these lists as per below. pair = itertools.zip_longest(swtype, p_list) But the output is not as I was seeking. It's like 1:201 2:203 none:205 none:207 none:208 What I am after is to have: 1:201 none:203 none:205 2:207 none:208 Is that possible by zipping or should I create 2 seperate loops. If I create 2 seperate loops than I am having other problems. -
Django 2.0 Queryset annotate date
Is there a way to pass an F() expression to a function such as dateutil's relativedelta inside a database annotate call. Given the below scenario where it is intended that InterestLoan.objects.active_loans(start_date='2018-01-01', end_date='2019-01-01') will return a queryset a of active loans within the given period. The end_date needs to be annotated using the start_date + term. Instead I get TypeError: bad operand type for unary +: 'F' class InterestLoanSet(models.QuerySet): def add_end_date(self): return self.annotate(loan_end_date=ExpressionWrapper(F('start_date') + relativedelta(months=+F('term'), output_field=DateField()))) def active_loans(self, start_date, end_date): return self.exclude(start_date__gt=end_date).add_end_date().exclude(loan_end_date__lt=start_date) class InterestLoan(AbstractTransaction): objects = InterestLoanSet.as_manager() interest_nominal_code = models.ForeignKey(NominalCode, null=False, on_delete=models.PROTECT) balance_nominal_code = models.ForeignKey(NominalCode, null=False, on_delete=models.PROTECT, related_name='loans') principal = models.DecimalField(max_digits=10, decimal_places=2) term = models.PositiveIntegerField() interest_rate = models.DecimalField(max_digits=4, decimal_places=4) -
Django: How can I populate related database in django
After clicking submit in html site it should take me to site which is representing by class ListCurrencyView(ListView): and populate model RowModel(models.Model): 1st - How to return class in views. 2nd - How to populate model that is related to another model depending of name (name is equal to 'First') views.py def index(request): """Primary site""" if request.method == 'POST': form = forms.CurrencyForm(request.POST) if form.is_valid(): for data in a_data: for item in data['rates']: models.RowModel.objects.create(name=item['currency'], code=item['code'], average=item['mid']) return ListCurrencyView(ListView) return render(request, 'currency_app_SA/index.html') models.py class TableModel(models.Model): name = models.CharField(max_length=264, blank=True) description = models.CharField(max_length=264, blank=True) def __str__(self): return self.name class RowModel(models.Model): name = models.CharField(max_length=264, blank=True) code = models.CharField(max_length=264, blank=True) average = models.CharField(max_length=264, blank=True) table = models.ForeignKey(TableModel, related_name='row', on_delete=models.DO_NOTHING) def __str__(self): return self.name PS: It's my first ask(If i did somethong wrong in this ask, please tell me that) and I realy don't find any answer on youtube or stack -
Django-rest-auth and AWS - Error 401
In my DRF application I've used package Django-rest-auth for authentication by JWT. In local environment everything works: I'm logging in and obtaining a token. Token has added to request's header and data has got. But after deployment on AWS when I try to login and I get a correct token (I guess) when I add him into header I get an error 401. Somebody know how to repair it? views.py from django.db.models import Count from rest_framework.viewsets import ModelViewSet from rest_framework.permissions import IsAuthenticated from rest_framework.renderers import JSONRenderer from rest_framework.decorators import action from rest_framework.response import Response from .models import Task from .serializers import TaskSerializer, TaskCreateSerializer from .filters import TaskFilter class TaskViewSet(ModelViewSet): permission_classes = (IsAuthenticated, ) renderer_classes = (JSONRenderer,) filterset_class = TaskFilter def get_queryset(self): return Task.objects.all()\ .select_related('owner')\ .only('name', 'owner__username', 'content', 'finished', 'start') def perform_create(self, serializer): serializer.save(owner=self.request.user) def get_serializer_class(self): if self.request.method == 'POST': return TaskCreateSerializer else: return TaskSerializer @action(methods=['GET'], detail=False) def dates(self, request, *args, **kwargs): qs = self.get_queryset()\ .extra(select={'start': 'Date(start)'})\ .values('start')\ .annotate(tasks=Count('start')) return Response(qs, 200) settings.py """ Django settings for MyToDo project. Generated by 'django-admin startproject' using Django 2.0.7. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os import datetime # … -
My django project is n ot showing body background
I have a django project. I carried it to a new server. Then i made collectstatics. After that i served my django site on uwsgi. In my main page html code : body id="skin-blur-city" In project/static/css/style.css #skin-blur-city { background-image: url(../img/body/city.jpg); } statics directory id under my project directory, in django settings file ; STATIC_ROOT = os.path.join(BASE_DIR, "static/") style.css is in project/static/css/ Image file is in project/static/img/body/city.jpg But main page is not showing city.jpg background. When i look at the source code from browser after i open page, i see body id="skin-blur-city" is in the html code. But not showing in browser. -
Authenticate against AD without asking for credentials with ldap3
I am developing a web application at work using Django which first validates against AD by collecting AD information from the machine that they have logged in, as in collect AD information from the client machine and validate against AD. I'm able to connect to the AD server, validate by mentioning username and password explicitly with ldap3 and get all information of a particular user id. with Connection(Server("ldap://xxxxx.net", port=0000, use_ssl=True), auto_bind=AUTO_BIND_NO_TLS, read_only=True, check_names=True, user='username', password='password') as c: c.search(search_base='DC=abcd,DC=abcd,DC=abcd', search_filter='(&(sAMAccountName=' + u + '))', search_scope=SUBTREE, attributes=ALL_ATTRIBUTES, get_operational_attributes=True) print(c.response_to_json()) But I'm unable to find any article about fetching AD information from client machine. Is this even possible? Any references to articles or tutorials for this use case would be much appreciated. -
Django - Select field not showing Options
model.py from django.db import models from django import forms class CharApp(forms.Form): VAMPIRE = 'VP' DRAUGR = 'DR' BAELNORN = 'BN' LICH = 'LH' SHADOW = 'SW' RACE_CHOICES = ( ('VP', 'Vampire'), ('DR', 'Draugr'), ('BN', 'Baelnorn'), ('LH', 'Lich'), ('SW', 'Shadow'), ) app_id = models.AutoField(primary_key=True) char_name = models.CharField(max_length=80, verbose_name='Character Name') race = forms.Form(forms.ChoiceField( choices = RACE_CHOICES)) date_applied = models.DateTimeField(verbose_name='Date Applied') background = models.TextField(verbose_name='Background') account_id = models.IntegerField(default=1, verbose_name='Account ID') submitted = models.BooleanField(default=False) create.html <p><label for="race">Race:</label> <select name="{{ form.race.choices }}"> {% for choices in form.race.choices %} {{ form.race.choices }} {% endfor %} </select> For some reason the select section of the html doesn't loop at all and shows no value at all or the text. -
Deploying django app to heroku - can't find file
I have a problem running my django app on heroku. It has been deployed successfully but it has some problems finding various files. in news.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) url_path = BASE_DIR + '/marketdata/news/' which works locally but when I deploy it on heroku it says it can't find the file Exception Value: [Errno 2] No such file or directory: '/app/artemis/static/marketdata/news/bloomberg_news.csv' Exception Location: /app/artemis/static/marketdata/news.py in save_to_csv, line 16 and this is my project structure Any idea how this would be solved? Any tip would be greatly appreciated! -
How would I search individual words in a query using Django
The code i currently have is able to search by words and exact strings: def search(request): query = request.GET.get('q', '') if query: qset = ( Q(Topic_id__Name__icontains=query) | Q(Question_id__Statement__icontains=query) ) results = Response.objects.filter(qset).distinct() else: results = [] return render_to_response("app/search.html", { "results": results, "query": query }) What i want is if someone were to search "What are our security and data policies", the search will pick each word individually and search for them e.g. "what", "are", "our", "security", "and", "data". I tried implementing a for loop by splitting the string but my site crashes whenever i make a change. -
Browser uses cached old version of JavaScript/CSS files served by Django WhiteNoise Gunicorn
This is how I configured WhiteNoise(v3.3.1). settings.py ... MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ... STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' ... I'm running this in a Docker Container and uses jwilder/nginx-proxy as reverse proxy. FROM python:3.6-slim ENV PYTHONUNBUFFERED 1 ... CMD gunicorn -b 0.0.0.0:80 config.wsgi EXPOSE 80 With every new build I'm deleting the old static and collecting new. rm -rf staticfiles && python manage.py collectstatic --noinput After collecting the files looks like: staticfiles | core | | dist | | | main.021f3a033fb7.js | | | main.021f3a033fb7.js.gz | | | main.js | | | main.js.gz And this is how I load the static in template. {% load static %} <script src="{% static 'core/dist/main.js' %}"></script> Request header: Request URL: https://example.com/static/core/dist/main.021f3a033fb7.js Request Method: GET Status Code: 200 (from disk cache) Remote Address: 0.0.0.0:443 Referrer Policy: no-referrer-when-downgrade Response header: access-control-allow-origin: * cache-control: max-age=315360000, public, immutable content-encoding: gzip content-length: 158755 content-type: application/javascript; charset="utf-8" date: Mon, 23 Jul 2018 10:50:19 GMT last-modified: Mon, 23 Jul 2018 09:33:29 GMT server: nginx/1.13.12 status: 200 vary: Accept-Encoding I don't know what is going wrong. -
How do I store task results to DB from client code also?
I am trying hands on to get the hang of Celery. So far everything looks fine. I am just not able to figure out one thing: I want the task results being stored in DB to have states updated not only from workers, but from the client application too, when the message is being sent to broker. So currently I have the below two lines in my configuration: CELERY_RESULT_BACKEND = 'django-db' CELERY_TASK_TRACK_STARTED = True This updates all the states for tasks inside DB that are managed by worker, including the STARTED state. But what I want is to also have the states that are due to client side, like PENDING. So that the results in DB starts with PENDING as long as the worker doesn't get that task and then when the worker starts/gets that task, the states like STARTED, SUCCESS etc. are updated to database. Rationale behind is we want our database to have records for the tasks, even if they are in pending state (i.e. not yet picked by any workers). My question is: Is it possible? Because this way the task row in DB has to be created by client code and then worker when updating the … -
ngnix - django 2 -angular 6 / angular routing get 404 after reload page
its django and angular 6(use static file) project . i get 404 not found error when i refresh browser .. i had few search and according this answer i did same thing this time angular route in refresh work (dont get 404) but i get server error that say following error *please see my uploaded image : *angular static files are in static folder "Http failure during parsing for http://robinlearn.com/api/v1/store/view-global-discount/" name: "HttpErrorResponse" url.py: urlpatterns = [ url(r'^(?!ng/).*$', HomePageView.as_view(),name="angular_app") ] urlpatterns += static(base.STATIC_URL, document_root=base.STATIC_ROOT) + \ static(base.MEDIA_URL, document_root=base.MEDIA_ROOT) urlpatterns += static(base.ANGULAR_URL, document_root=base.STATIC_ROOT) view: class HomePageView(TemplateView): def get(self, request, **kwargs): return render(request, 'index.html', context=None) nginx config: listen 80; server_name robinlearn.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/bio/academy; } location / { include proxy_params; #proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://unix:/home/bio/academy/academy.sock; } } setting: PROJECT_ROOT = os.path.dirname(os.path.dirname((__file__))) #STATIC_ROOT = BASE_DIR+'/academy/staticfiles' STATIC_URL = '/static/' STATIC_ROOT = os.path.join((BASE_DIR),"static") #MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR),"media") SS_ROOT = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # Extra places for collectstatic to find static files. STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, 'static'), ) this is my index.html(in template folder) that load static angular {% load static %} <!DOCTYPE html> <html lang="fa" id="persain"> <head> <meta … -
Running Django development server from Git Bash gets stuck in windows 10
I'm new to Django and now getting stuck in running up the server. I've installed the following components on Windows 10: Python 3.7.0 Django 1.11.14 Geckodriver 0.21.0 I can successfully create a project using django-admin.py startproject {project_name} . but when I run python manage.py runserver, the Git Bash doesn't seem to make any progress and the process gets stuck there forever. $ python manage.py runserver | I'm supposed to get something like the following output though, Performing system checks... System check identified no issues (0 silenced). Django version 1.8.3, using settings 'projectname.settings' Starting >development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. I've also activated the virtualenv too. What could be the cause of this problem? -
Can not get access to django admin panel
I use bitnami on aws with edx platform, and try to get access to django admin panel. Bitnami logs gave me user login and user password, but django wrote it is invalid. What the problem and how to fix it? And I used ngrok to access my ec2 instance -
Understanding Django docs model db_table
The docs reads as follow: Oracle imposes a name length limit of 30 characters. To accommodate this, the backend truncates database identifiers to fit, replacing the final four characters of the truncated name with a repeatable MD5 hash value. Additionally, the backend turns database identifiers to all-uppercase. To prevent these transformations (this is usually required only when dealing with legacy databases or accessing tables which belong to other users), use a quoted name as the value for db_table: Quoted names can also be used with Django’s other supported database backends; except for Oracle, however, the quotes have no effect. After reading I get the sense that both paragraphs are contraction to each other , probably due to lack of my understanding of English language. How a MD5 hash accommodate 30 character limit when its "repeatable", (which should be equals to static suffix) To prevent these transformations use a quoted name and in later para except for Oracle, however, the quotes have no effect \_(',')_/. So why a para is dedicated when quotes have no effect ? Please explain the effects of quotes in the context of Oracle, and non oracle db with an example. -
How to make Django sessionId cookie as secure
I have tried adding the following attribute in settings.py file SESSION_COOKIE_SECURE = True It didn't work for me. Any alternative solution for this? -
get queryset values that fall in a list [duplicate]
This question already has an answer here: How to filter a django queryset using an array on a field like SQL's “IN”? 1 answer i have model data as: id | name 1 | abcd 2 | xyz ..... and a list as [1,5,8] now i want to retrieve all names whose id falls in the list using a queryset, how do i do that in django, do i have to use a loop, or is there a better way to do so in django, say model name is X qs=X.objects.filter(some custom filter here).values('name') i need the names where id is one in the list -
how to store data in database(django) from server(angular5)?
I create real time chat application using websocket which in pure python and frontend(angular5) and BackEnd(django). my messages send are receive properly, but it is a live data.. but i want to store that data in db so i can see the chat history. So, my question is how to store data(messages) in to db(Django) from angular. or i have to get data from websocket and store it into db?.. what is right way?