Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is this appropriate technology stack to make SPA with Python
I'm going to build a simple project and I wonder, if a technology stack which I've choosen is appropriate with this kind of tasks. About project: Single-page application where I could make basic analysis with stock markets data. Main goals is to get ticker quotes, display real-time chart which would automaticly update, portfolio section and some news feed. This should be main shape of this app. If this would work I'll update it with some other features. Back-end: Python 3.6 with Django Framework (ver. 2.0) Django REST Framework AlphaVantage API Front-end: HTML, CSS, plain JS D3.js Bootstrap Is this suitable or I miss something? The 'path' I've imagined is like that: Get quotes and data (AlphaVantage API) => Django + REST framework would manage all and push it as JSON to users client => D3.js would display charts Is this possible to make it the way I mentioned? If not what I have to change? (not Python, I really want to make this app using it). My purpose: This will be my first bigger project with everything stacked together. In past I've made some data analytics and visualisation with Python (anaconda package), very simple blog backend with django and some … -
Django: Not able to access prefetch_related values in template
First website. Firs time using Django. I am using this Query right now in view: visitingQuerySet = ClinicDoctor.objects.filter(doctor_id = doctor_id).prefetch_related('clinicDoctor_dayShift').all() Then in template I want to have something like this: {% for vis in visitinghours %} <tr> <td> {{ vis.doctor.full_name }} </td> <td> {{ vis.clinic.name }} </td> <td> {{ vis.clinicdoctordayshift.id }} </td> </tr> I can get first two `<td>` but not others if I try to get values from other models. My models are: class User(AbstractUser): full_name = models.CharField(max_length=200) clinics = models.ManyToManyField(Clinic, through='ClinicDoctor', related_name='doctors') class ClinicDoctor(models.Model): doctor = models.ForeignKey('User', related_name='doctorsF') clinic = models.ForeignKey(Clinic, related_name='clinicsF') class Day(models.Model): day = models.CharField(max_length=20) class Shift(models.Model): shift = models.CharField(max_length=20) days = models.ManyToManyField(Day, through='DayShift', related_name='day_shift') class DayShift(models.Model): time = models.TimeField() day = models.ForeignKey(Day, related_name='to_day') shift = models.ForeignKey(Shift, related_name='to_shift') clinics_doctors = models.ManyToManyField(ClinicDoctor, through='ClinicDoctorDayShift', related_name='clinicDoctor_dayShift') class ClinicDoctorDayShift(models.Model): clinic_doctor = models.ForeignKey(ClinicDoctor, related_name='to_clinicDoctor') day_shift = models.ForeignKey(DayShift, related_name='to_dayShift') I want to be able to be able to get Day.day, Shift.shift and DayShift.time as well. Is my prefetch_related wrong? Is it Ok to have this in view after that prefetch_related: if visitingQuerySet: I mean will this cause any extra DB hits or this will be the first point where it will be actually evaluated? Currently I can see these two queries being … -
How to be able to edit field in Django admin panel
I do not see edit icon in django admin panel in the detail page of my model. It looks like this: Thus normally it should have add icon and edit icon, something like this: But the edit icon is missing. My model is as follows: class BusinessUnit(models.Model): name = models.CharField(max_length=255) brands = models.ManyToManyField(to=Brand) site_picture = models.ImageField(upload_to=settings.MEDIA_ROOT, blank=True, null=True) address = models.ForeignKey(to=Address) def __unicode__(self): return self.name And in admin.py i have the code as follows: class BusinessUnitAdmin(admin.ModelAdmin): search_fields = ('name',) list_display = ('name', 'address', ) admin.site.register(BusinessUnit, BusinessUnitAdmin) Any ideas what is wrong? -
Can I get cookies value or session value inside the has_permission method of django rest framework?
I am working on a project where i have to check the user whether they belong the company or not.i am already put check while login user. how i can use company id inside the has_permission() method? class IsCompanyEmployee(permissions.BasePermission): message = 'You are unauthorized to perform any action on this company.' def has_permission(self, request, view): if request.user.is_authenticated(): if request.user.is_superuser: return True else: #company_id = request.COOKIES["company_id"] #or #company_id = request.session["company_id"] return request.user.companyemployee_set.filter(company__id=company_id).exists() else: return False -
Django forms - looping through form choice fields, how to assign the ID?
I am looping through some form choice fields in my template, but when I post, the form is not valid as it is missing required field "subnets" however I have manually created the subnet checkboxes. The reason I believe it is failing is because the manually created objects do not have an id, is this right? and how do I assign the id? template: {% for value, text in form.subnets.field.choices %} <div class="checkbox"> <label> <input type="checkbox" id="subnets" value="{{ value }}" />{{ text }} </label> </div> {% if forloop.counter|divisibleby:4 %} </div> <div class="col-xs-3"> {% endif %} {% endfor %} error: subnets This field is required. -
How to retrieve Json meta-data from endpoint using django-rest-framework
I'm using Django rest framework to retrieve data from server. Now I create a view: class Snipped(APIView): authentication_classes = (authentication.SessionAuthentication,) permission_classes = (permissions.AllowAny,) #@ensure_csrf_cookie def get(self, request, format=None): request.session["active"] = True snippets = Snippet.objects.all() serializer = SnippetSerializer(snippets, many=True) return JsonResponse(serializer.data, safe=False) def post(self, request, format=None): serializer = SnippetSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) the model is this: # Create your models here. class Snippet(models.Model): created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, blank=True, default='') code = models.TextField() def __str__(self): return self.title so at this point I'd like to know metadata of data passed to this endpoint, I 've found http://www.django-rest-framework.org/api-guide/metadata/ but if a send OPTION I don't obtain informations about data but only this json answer { "name": "Snipped", "description": "", "renders": [ "application/json", "text/html" ], "parses": [ "application/json", "application/x-www-form-urlencoded", "multipart/form-data" ], } without (see list at http://www.django-rest-framework.org/api-guide/metadata/) "parses": [ "application/json", "application/x-www-form-urlencoded", "multipart/form-data" ], "actions": { "POST": { "note": { "type": "string", "required": false, "read_only": false, "label": "title", "max_length": 100 } } } any idea how can achieve above results with an APIView ? -
Django: how to find out that the request to update rows in the database was completed
The essence of the problem is that while I'm not able to execute my select need update in the postgres for the time being, for example, the update does not happen, but the view is already in progress, ie I make an update request, it went into the database for execution, and my form is executed further, so long as it really refreshes my rows in DB, I did not continue my view. Thanks! -
Django Models - insert foreign key values using Shell
I am trying to save values for my Models through Django Shell . I am beginner in Django. I have crated three models. I inserted values in models one by one.i created Dept first and inserted all Dept Values.Created Student and inserted all student related values. Now i am trying to insert values in course which contains two foreign key studentId and dept id . How to insert values for Student model using Django Shell. # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models # Create your models here. from django.db import models from django.utils import timezone class Student(models.Model): studentId = models.AutoField(primary_key=True) firstname = models.CharField(max_length=50) middlename = models.CharField(max_length=1) lastname = models.CharField(max_length=50) city = models.CharField(max_length=200) registe_dt = models.DateTimeField(default=timezone.now()) def __str__(self): return '%s %s %s' % (self.studentId, self.firstname,self.city) class Dept(models.Model): deptId = models.AutoField(primary_key=True) deptName = models.CharField(max_length=200) def __str__(self): return '%s %s' % (self.deptId, self.deptName) class Course(models.Model): courseId=models.AutoField(primary_key=True) courseName=models.CharField(max_length=100) student = models.ManyToManyField(Student) dept = models.ForeignKey(Dept,on_delete=models.CASCADE) def __str__(self): return '%s %s %s %s' % (self.courseId, self.courseName,self.student.primary_key,self.dept.primary_key) Thank you for helping Jordan -
Django api performance improvement
I have a Django API which is fetching records( on an avg 30000 records) from MSSQL database using stored procedures. This API is consumed in an Angular4 web app which is used for downloading in excel format. It is taking an average of 10 seconds for the procedure to execute and approximately 47 seconds for API to fetch it. Let me know the areas where performance can be improved. -
Django url slash matching
my url pattern in apps like: urlpatterns = [ url(r'^show/(?P<arg1>[\w\d_\.]+)$', views.view_1), url(r'^show/(?P<arg1>[\w\d_\.]+)/(?P<arg2>[\w\d_\.]+)$', views.view_2), url(r'^show/(?P<arg1>[\w\d_\.]+)/(?P<arg2>[\w\d_\.]+)/(?P<arg3>[\w\d_\.]+)$', views.view_3), ] the url : /show/in_arg1/in_arg2%2F_this_is_arg2 match to view_3 but I want to let the url match view_2 I try to change urlpatterns like urlpatterns = [ url(r'^show/(?P<arg1>[\w\d_\.]+)$', views.view_1), url(r'^show/(?P<arg1>[\w\d_\.]+)/(?P<arg2>[\w\d_\.\/]+)$', views.view_2), url(r'^show/(?P<arg1>[\w\d_\.]+)/(?P<arg2>[\w\d_\.\/]+)/(?P<arg3>[\w\d_\.]+)$', views.view_3), ] the url : /show/in_arg1/in_arg2%2F_this_is_arg2 works well but the url /show/in_arg1/in_arg2/in_arg3 will match to view_2, not what I want It seems django decode %2F to / before url matching Can I let django do url matching without decode %2F ? Or some way to solve my problem thanks -
Python Unit Test: mock the function wrapping other function? [duplicate]
This question already has an answer here: Python Mocking a function from an imported module 2 answers Here is what I want to test: test.py class MyTest(TestCase) def test1(self): data = crawl_data() Check data lengh and current data in DB... function2() Again, Check data lengh and current data in DB... And program code: a.py def crawl_data(): """ crawl data from web """ . . return web_crawled_data b.py from a import crawl_data def function2(): """ crawl data and store new data in database """ . . result = crawl_data() . . update data and update Database . . What I want to do is testing function2(). Problem is though function2() call crawl_data() inside. I don't want crawl_data() to crawl data from web in the test, So I tried mocking this function. @patch("a.crawl_data") def test1(self, crawl_data): crawl_data.return_value = [("112233", "ABCDEF"), ("222233", "EFGHIJ")] data = crawl_data() Check data length and current data in DB function2() Check the database whether new data stored in DB When I run the test, function2() still crawl data from the web in real! The reason that I don't want to mock function2 is that, when I start the test, test framework use virtual database (provided by django)! So, … -
Getting CSRF error when sending POST Request using Postman [LOGIN PAGE]
While the site loads smoothly through the browser,but when i send a POST request via postman or a REST API client, i am getting a csrf error. "CSRF cookie not set." IS THERE A WAY TO SEND A REQUEST SKIPPING CSRF? -
Raise 404 instead of 403 DRF permission
Is it possible to customize response status of a permission to ruturn other than 403? Docs say: When the permissions checks fail either a "403 Forbidden" or a "401 Unauthorized" response will be returned -
Where are django console output sent
My prod django server runs with command /bin/python manage.py runfcgi host=127.0.0.1 port=8003 where can I find standard console log messages which come on console while running server manually with runfcgi option. [07/Feb/2018 15:48:47] "GET /cms/content HTTP/1.1" 200 48502 │2018-02-07 16:08:02,386 INFO done in 0.02 seconds [07/Feb/2018 15:48:47] "GET /2.2/static/css/sidebar.css HTTP/1.1" 200 1207 │2018-02-07 16:10:02,404 INFO ------------------------------------------------------------------------ [07/Feb/2018 15:48:47] "GET /2.2/static/css/ie.css HTTP/1.1" 200 263 │2018-02-07 16:10:02,434 INFO [07/Feb/2018 15:48:47] "GET /2.2/static/css/responsive.css HTTP/1.1" 200 22106 │2018-02-07 16:10:02,435 INFO 0 sent; 0 deferred; [07/Feb/2018 15:48:47] "GET /2.2/static/css/dataportal.css HTTP/1.1" 200 13054 In settings Log path is defined but it only logs logger.info messages. I am having a new thread for a sending emails but it abrubtly stops in between with no trace of any error messages. -
How to display records belongs only for user instead for all users
I have a little problem. I want to to display in list only records belongs to user whos add it. In my app when I'am login as 'user' and I want to add new records incude records from list, I see all records in db from ForeignKey. How to make it correctly? In 'Strona www' when I expand the list I see all records, not only records added by user personally. My view for it is: @login_required def new_keyword(request): if request.method == "POST": new_keyword = KeywordForm(request.POST) if new_keyword.is_valid(): new_keyword=new_keyword.save(commit=False) new_keyword.user = request.user new_keyword.save() messages.success(request, 'Pomyślnie dodano słowo kluczowe') return render(request, 'konto/new_keyword_ok.html') else: new_keyword = WebsiteForm() return render(request, 'konto/new_keyword.html', {'new_keyword':new_keyword}) in forms.py I have: class KeywordForm(forms.ModelForm): class Meta: model = Keyword fields = ('www', 'keyword') models.py class Keyword(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Użytkownik") www = models.ForeignKey(Website, on_delete=models.CASCADE, verbose_name="Strona www") keyword = models.CharField(max_length=250, verbose_name="Słowo kluczowe", unique=False) urls.py path('new-keyword/', new_keyword, name='new_keyword'), and html for display the form is: {% if request.user.is_authenticated %} <form action="." method="post"> {{ new_keyword.as_p }} {% csrf_token %} <p><input type="submit" value="Dodaj nowe słowo kluczowe" ></p> <a href="{% url 'dashboard' %}">Powrót do monitoringu</a> </form> {% endif %} -
how can I truncate text and remove html tags in django template
I've used truncatechars but if text contains a html tag, it will show the tag for me. {{content.text|safe|normal_text|truncatechars:140}} for example displays something like this: <p>hi</p> I want to remove p tag. -
Django filter by first letter of model
I have a problem and i dont know how to solve it. I got this template generating /list/a,b,c, etc. And i want to show in this a,b,c url only model with the same letter. list template <div class="panel-body anime-list text-center"> <div class="btn-group btn-group-xs"> {% for i in alphabet %} <a href="{{i}}" class="btn">{{i}}</a> {%endfor%} </div> </div> model's class Anime(models.Model): title = models.CharField(max_length=300, unique=True) ongoing = models.BooleanField(default=True) add_date = models.DateTimeField('date published') How can i filter that in another desired template -
Is it a good idea to use django and postgres only for authentication along with mongo engine?
I am currently working with mongoengine along with Django. The authentication happens with the Django authentication backend with PostgreSQL. The rest application data is stored in MongoDB. Is it a good idea to use a structure like this in a stable app? -
Django 1.11 how to resolve list_filter duplicates
In my Model, a __str__(self) that derives the quarter and year from the DateTimeField of when Response was created. Models.py class Response(models.Model): created = models.DateTimeField(auto_now_add=True) def __str__(self): msg = u"Q%d %d" %(((self.created.month-1)//3)+1, self.created.year) return msg In Admin, I want to be able to filter records based on the Quarter in which they were submitted (actually, I want to filter by who hasn't submitted a Response for a particular quarter, which I think I can achieve with a well placed tilde later), so I have the following: Admin.py class UserAdmin(admin.ModelAdmin): list_display = ('username', 'latest_response') list_filter = ('response__created', 'response') def latest_response(self, obj): return obj.response_set.latest('created') I have submitted four responses so far in testing (through the def __str__ I have 2 x "Q1 2018", and 2 x " - "), and the result looks like this: Any ideas why I am getting 3 x "Q1 2018" and 1 x " - "? I want Only 1 x "Q1 2018" in the filter list Bonus question - any idea how to set a limit to the number of items listed in the filter_list (by response)? I want to limit them to the latest 4 which, might be problematic as I'm using a string. EDIT … -
Edit foreign key value in Django admin
I have model an Django model as follows: class BusinessUnit(models.Model): name = models.CharField(max_length=255) address = models.ForeignKey(to=Address) vat_number = models.CharField(max_length=50) telephone = models.CharField(max_length=50) email = models.CharField(max_length=50) manager = models.ForeignKey(to=User, null=True) def __unicode__(self): return self.name How can I change address directly from BusinessUnit in Django admin? Now I can only select the address, but I cant change it. I need to go to Address model and change it there, but I want to be able to change it directly in BusinessUnit model. Any idea how can I do that? -
How come the field value on the related object isn't updated after saving?
I have a one-to-many relationship in django. (one Author is to many Books) The problem is that when I update a field of an Author through a Book, I get the old value for the Author's field when retrieving the Book again. >>> book1 = Book.objects.get(pk=1) >>> book1.author.name u'Old Author' >>> book1.author.pk 1 >>> book1.author.name = "New Author" >>> book1.author.save() >>> book1.author.name u'New Author' >>> author1 = Author.objects.get(pk=1) >>> author1.name u'New Author' >>> book2 = Book.objects.get(pk=1) >>> book2.author.pk 1 >>> book2.author.name u'Old Author' # I'm expecting this to be u'New Author' What am I missing here? -
validating a form using get method in django
I am new to programming, I hope my question is not very basic. Here I am trying to taking the input and showing output on the same page. I went through an article that said I should use GET method to do so. my view def calc(request): if request.method == 'GET': form = CalculationForm(request.GET) if form.is_valid(): number1 = form.cleaned_data.get('first_number') number2 = form.cleaned_data.get('second_number') sum = number1 + number2 sum.save() return render(request, 'calculation\calculator.html', {'sum': sum}) else: form = CalculationForm() return render(request, 'calculation\calculator.html', {'form': form}) my HTML <body> <form method="get" action=".">{% csrf_token %} {{ form }} <input type="submit" name="Register" value="Submit" /> {{sum}} </body> Here I am showing the user simple form user input numbers in two fields Add the numbers showing it back to the user on the same page My form is getting rendered and the fields are displaying I am able to enter the number in the field but when I click submit I get an error. Anyone -
Django MTPP display recursive hierarchical category in REST API
I am trying to display my recursive category model in my Django REST API list view. This is how it is now: "results": [ { "pk": 3, "title": "Test", "category": 7, }, ... ]} I want to achieve something like this: "results": [ { "pk": 3, "title": "Test", "category": [ { "id": 5, "name": "Cat", "slug": "cat", "child": [ { "id": 7, "name": "Parser", "slug": "parser", } ] } ], }, ... ]} I am currently using Django MPTT to create a hierarchical Model. This is the Category in models.py: class Category(MPTTModel): name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True, on_delete=models.SET_NULL) slug = models.SlugField() class MPTTMeta: order_insertion_by = ['name'] class Meta: unique_together = (('parent', 'slug',)) verbose_name = "Category" verbose_name_plural = "Categories" def get_slug_list(self): try: ancestors = self.get_ancestors(include_self=True) except: ancestors = [] else: ancestors = [i.slug for i in ancestors] slugs = [] for i in range(len(ancestors)): slugs.append('/'.join(ancestors[:i + 1])) return slugs def __str__(self): return self.name I am using generic views from Django Rest Framework to create the view. In views.py: class CaseListCreateView(generics.ListCreateAPIView): serializer_class = CaseSerializer def get_queryset(self): qs = Case.objects.filter(active=True) query = self.request.GET.get("search") if query is not None: qs = qs.filter(Q(title__contains=query) | Q(text__contains=query)).distinct() return qs def perform_create(self, … -
unable to complete django installation
I downloaded the necessary files from the link https://github.com/django/django.git and pasted them in to my virtual env directory After setting up and activating the virtualenv, when I run the following command: $ pip install -e django/ It produces this error: (ENV) C:\WINDOWS\system32>pip install -e django/ django/ should either be a path to a local project or a VCS url beginning with svn+, git+, hg+, or bzr+ I am a Windows user. I think the command is for bash not for cmd. Is it necessary to use this git tool to finally work with django ? As instructed on the Django website : -
using Filtered Count in django over joined tables retuns wrong values
To keep it simple I have four tables(A, B, Category and Relation), Relation table stores the Intensity of A in B and Category stores the type of B. A <--- Relation ---> B ---> Category (So the relation between A and B is n to n, where the relation between B and Category is n to 1) What I need is to calculate the occurrence rate of A in Category which is obtained using: A.objects.values( 'id', 'relation_set__B__Category_id' ).annotate( ANum = Count('id', distinct=False) ) Please notice that If I use 'distinct=True' instead every and each 'Anum' would be equal to 1 which is not the desired outcome. The problem is that I have to filter the calculation based on the dates that B has been occurred on(and some other fields in B table), I am using django 2.0's feature which makes using filter as an argument in aggregation possible. Let's assume: kwargs= {} kwargs['relation_set__B____BDate__gte'] = the_start_limit I could use it in my code like: A.objects.values( 'id', 'relation_set__B__Category_id' ).annotate( Anum = Count('id', distinct=False, filter=Q(**kwargs)) ) However the result I get is duplicated due to the table joins and I cannot use distinct=True as I explained. (querying A is also a must since …