Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
the model in Django-autocomplete-light
I want to have an autocomplete dropdownlist but the problem is when i use it for "raste" which is a foriegn key of "stocksname" table it doesnt work, but when use it for "user" which is the foreign key of "user" table , it works properly. Is there any problem whith my "stocksname" model ? models.py : class StocksName(models.Model): checking= ((_('pending'),_('pending')), (_('reject'),_('reject')), (_('approved'),_('approved')), (_('expired'),_('expired')), ) name=models.CharField(max_length=128,verbose_name=_('stockname'),unique="True") confirm=models.CharField(choices=checking,max_length=12,verbose_name=_('confirmation'), default=_('pending')) def __str__(self): return str(self.name) class Meta: verbose_name=_('StocksName') verbose_name_plural=_('StocksNames') ordering = ('name',) #For sorting alphabetically class Stocks(models.Model): user=models.ForeignKey(User, null=True,related_name='stockdetails') raste=models.ForeignKey(StocksName, null=True) stname=models.CharField(max_length=128,blank=True, null=True,verbose_name=_('stockname')) mark=models.CharField(max_length=128,blank=True, null=True,verbose_name=_('mark')) pic=models.ImageField(blank=True,null=True,verbose_name=_('pic'),upload_to = 'stocks', default = 'stocks/nopic.jpg') car=models.ForeignKey(Cars,blank=True,null=True,verbose_name=_('car'),on_delete=models.SET_NULL ,to_field='carname') description=models.CharField(blank=True,null=True,max_length=264,verbose_name=_('description')) price=models.PositiveIntegerField(blank=True,null=True,verbose_name=_('price')) date=models.DateTimeField(auto_now_add = True,verbose_name=_('date')) checking= ((_('pending'),_('pending')), (_('reject'),_('reject')), (_('approved'),_('approved')), (_('expired'),_('expired')), ) confirm=models.CharField(choices=checking,max_length=12,verbose_name=_('confirmation'), default=_('pending')) def __str__(self): return str(self.id) class Meta: verbose_name=_('Stock') verbose_name_plural=_('Stocks') def get_absolute_url(self): return reverse('BallbearingSite:mystocks' ) Forms.py : (for user replace "raste" with "user" in the widgets ) class StocksForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(StocksForm, self).__init__(*args, **kwargs) for field_name, field in self.fields.items(): field.widget.attrs['class'] = 'form-control' field.widget.attrs['style']= 'width:60%' class Meta(): model=Stocks fields=('user','raste','stname','mark','description','pic','price') widgets = { 'raste': autocomplete.Select2(url='BallbearingSite:stock_autocomplete'), } Views.py : (for user , which works properly) class StocksAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): if not self.request.user.is_authenticated(): return User.objects.none() qs = User.objects.all() if self.q: qs = qs.filter(username__istartswith=self.q) return qs def has_add_permission(self, request): return True Views.py … -
django database query log linenumber
I am logging my database queries in Django along with the pathname and linenumber. Right now i am getting these logs: 07/Dec/2018 14:25:00 DEBUG django.db.backends utils **/Users/XXXXX/.idea/lib/python2.7/site-packages/django/db/backends/utils.py:89** (0.340) SELECT "metadata"."metaname", "metadata"."description", "metadata"."attributes" FROM "metadata" WHERE "metadata"."metaname" = 'date_type'; args=('date_type',) For all queries, I am getting the same path and line number. Is there any way I can capture the line number from my main application instead of the one from utils. Current logging Implementation: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'color' }, }, 'loggers': { 'django.db.backends': { 'handlers': ['console'], 'level': 'DEBUG', 'propogate': True, } } } Using python 2.7 and django 1.9 -
Config multiple Django API endpoints On One domain with different Url Path Using Nginx
I want to serve multiple django projects (actually django rest API apps) On one domain but serve each of them on seperated url. like this: http://test.com/app1/... http://test.com/app2/... and so on. I will be using nginx to config it. But i'm facing some problems that wants your helps: These apps should have different cookie for each other. cause they have different auth system. so token and cookie in one is not valid for another. How to handle this? What nginx configs you recommend. I don't want full detail cause i know concepts. just some hints and usefull commands will do. -
Django - filter with week_day causes: user-defined function raised exception
Django Version: 2.1.1 Exception Type: OperationalError Exception Value: user-defined function raised exception I got the above issue when I try to filter books for a day of the week. print(Book.objects.filter(date_created__week_day=1)) Is it because I use sqlite database? How can I fix it? -
Apache + Django ImportError no module named math
I want to deploy a django project using apache and wsgi, Here is my .conf file : <VirtualHost *:80> WSGIDaemonProcess mysite.com python-home=/home/my.site.com/venv python-path=/home/mysite.com WSGIProcessGroup mysite.com WSGIScriptAlias / /home/mysite.com/mysite/wsgi.py process-group=mysite.com etc ... ( media and static alias are working normally ) And I've got the following error in the error.log : ImportError: No module named 'math' Would you have any idea how to solve that ? Thank you -
Django authenticaion by using phone no with otp
I'm new to django. I need to create custom phone no with otp authentication. for that I found a library (app) in github Here's the link: https://github.com/wejhink/django-phone-login I installed that app by using pip install django-phone-login and configured everything in the setting.py file... When I'm going to migrate an error appears Here's the error ERRORS: <class 'phone_login.admin.PhoneTokenAdmin'>: (admin.E108) The value of 'list_display[0]' refers to 'phone_number', which is not a callable, an attribute of 'PhoneTokenAdmin', or an attribute or method on 'phone_login.PhoneToken'. Please help anyone thank you. -
Get data from custom middleware in django views
I've followed this link to create a custom middleware. The main idea is I want to show the page rendering time on my index.html page. My middleware object: class StatsMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): return self.get_response(request) def process_request(self, request): request.start_time = time.time() def process_response(self, request, response): duration = time.time() - request.start_time response["render_time"] = int(duration * 1000) return response How can I process this response object via my class-based views? -
Django filter many to many
If I have products that only can be sold is some regions. Also a customer can belong to several regions. Example: class Customer(models.Model): firstname = models.CharField(max_length=100, default="") class Product(models.Model): productname = models.CharField(max_length=100, default="") class Region(models.Model): regionname = models.CharField(max_length=100, default="") class CustomerRegionLink(models.Model): customer = models.ForeignKey(Customer) region = models.ForeignKey(Region) class ProductRegionLink(models.Model): product = models.ForeignKey(Product) region = models.ForeignKey(Region) If I now have a Customer object. How can I filter out which products can be ordered? I have tried versions of: thecustomer = Customer.objects.get(id=1) prods = ProductRegionLink.object.filter(region__in=thecustomer.customerregionlink.all()) This errors like: ValueError: Cannot use QuerySet for "CustomerRegionLink": Use a QuerySet for "Region". -
Model layout for a video timeline project
I have a project which involves writing a list of timestamps for video lessons. Each lesson has a document created similar to the following format: 00:01:30 Introduction 00:05:00 Discussion on topics PART 1 HEADING Section heading 00:07:25 First item 00:15:40 Second item 00:12:30 ...Sub-item 00:30:10 Another marker Section 2 heading 00:44:00 Another item There are several "sections" which may or may not have a heading, each with one or more (or even no) timestamp entries. I am currently saving this raw file (written in Apple Pages and also exported to PDF for users) to text format and then using a Python script to translate it (using Gelatin) into a JSON file for another system to process (this gives a clickable table of contents alongside the video). This JSON has the following format (with added meta-data, and ignoring the sub-item indentation): { "course": "Test Course", "tutor": "Mr Test", "lesson": "1", "date": "2018-12-07", "description": "", "timeline": [ { "times": [ { "time": "00:01:30", "label": "Introduction" }, { "time": "00:05:00", "label": "Discussion on topics" } ] }, { "section": "PART 1 Heading" }, { "section": "Section heading", "times": [ { "time": "00:07:25", "label": "First item" }, { "time": "00:15:40", "label": "Second item" }, … -
Deleting a django model class object without foreignkey warning
I have two tables in MySql created with django models.One is Students model, other is Attendance model. class Attendance(BaseModel): stu = models.ForeignKey(Students, verbose_name=_("Student")) I did't put "on_delete=models.PROTECT" to stu in Attendance class, because i need to able to delete a Student object without protection warning, if this Student is defined in Attendance as foreignkey from Students class. Now when i delete a Students objects, the foreignkey connected records in Attendance are also deleted. The thing i want to do is, i want to delete Students objects without warning. But i want connected foreignkey records in Attendance should stay there for historical reports. The Students objects will be deleted without warning, and foreignkey related rows in Attendance will not be deleted. -
django favorite button
I'd like to implement a bookmarker (favorites button) for the end user of the site, so that they can store their favourite adventures. models.py class Favorit(models.Model): related_adventure = models.ForeignKey(Adventure, on_delete=models.CASCADE, related_name='favorit') user = models.ForeignKey(User, on_delete=models.CASCADE) def __unicode__(self): return '%s %s'%(self.related_adventure.name, self.user.username) in the views.py @login_required def favorit_adventure(request,adventure_pk): user = request.user adventure = Adventure.objects.get(pk=adventure_pk) if(Favorit.objects.get(user = request.user and related_adventure == adventure_pk)): print ('geht') # If no new bookmark has been created, # Then we believe that the request was to delete the bookmark messages.success("Erfolgreich") if not created: favorit.delete() return HttpResponseRedirect(request.META.get('HTTP_REFERER')) and .html so .html The idea is to write a def and to add the adventure from the current template, giving the pk(primary key). The problem is to give the appropriate adventure to the view. Then a new instance favorite should be created. My problem is that no action happens when clicking the button. What is there to do? Thanks in advance -
How to query Haystack to get similar items [Python, Haystack, ElasticSearch]
I am trying to ge similar posts when a post ID is sent as a payload to an endpoint (RESTful API) using Haystack and ElasticSearch: original_post = Article.objects.get(id=pk) #pk is 2 for example related_items = SearchQuerySet().more_like_this(original_post.title) result = related_items[0].object.title print(result) This throws an Error: AttributeError: 'str' object has no attribute '_meta' I am new to Elastic Search. What am I doing wrong? -
Django form csv
I have a form that I want to use for predictions but when a user submits the form I want it to be in stored in a variable in a csv fomrat so I can perform Xgboost prediction on every form and after it outputs the prediction. from django.db import models from django import forms from django.core.validators import MaxValueValidator, MinValueValidator # Create your models here. type_loan=(("Cash loan","Cash loan"), ("Revolving loan","Revolving Loan")) Gender=(("Male","Male"), ("Female","Female")) Yes_NO=(("YES","YES"),("NO","NO")) status=(("Single","Single"), ("Married","Married"), ("Widow","Widow"), ("Seprated","Divorce")) Highest_Education=(("Secondary","Secondary"), ("Incomplete Higher","Incomplete Higher"), ("Lower Secondary","Lower Secondary"), ("Academic Degree","Academic Degree")) Income_type=(("Working","Working Class"), ("State Servant","Civil Servant"), ("Commercial Associate","Commercial Associate"), ("Pensioner","Pensioner"), ("Student","Student"), ("Businessman","Business Owner")) class Applicant(models.Model): name=models.CharField(default="Jon Samuel",max_length=50,null="True") Birth_date=models.DateField(default="2018-03-12",blank=False, null=True) Status=models.CharField(choices=status,max_length=50) Children=models.IntegerField(default=0,validators=[MinValueValidator(0),MaxValueValidator(17)]) Highest_Education=models.CharField(choices=Highest_Education,max_length=50) Gender=models.CharField(choices=Gender, max_length=50) loan_type=models.CharField(choices=type_loan, max_length=50) own_a_car=models.CharField(choices=Yes_NO,max_length=50) own_a_house=models.CharField(choices=Yes_NO,max_length=50) def __str__(self): return self.name -
Django 1.11 annotation GROUP BY is wrong
With model relations like this Risk <-- RiskGroup --> Group I am trying to achieve a query resembling this SELECT risk.id, ( SELECT array_agg(bg.name) as names FROM hazards_riskgroup rgroup JOIN (SELECT * FROM base_group ORDER BY name) as bg on rgroup.group_id = bg.id WHERE risk_id = risk.id GROUP BY risk_id ORDER BY risk_id ) AS conf FROM hazards_risk risk ORDER BY conf NULLS LAST ; And I have gotten as far as group_names = ( RiskGroup.objects .filter(risk_id=OuterRef('pk')) .annotate(names=ArrayAgg('group__name')) .order_by() .order_by("group__name") .values('names') ) qs = Risk.objects.annotate( conf=Subquery(group_names) ).order_by() But that wil produce something along the lines of this query SELECT risk.id, (SELECT ARRAY_AGG(U2."name") AS "names" FROM "hazards_riskgroup" U0 INNER JOIN "base_group" U2 ON (U0."group_id" = U2."id") WHERE U0."risk_id" = (risk.id) GROUP BY U0."id", U2."name" ORDER BY U2."name" ASC) AS "conf" FROM hazards_risk risk ORDER BY conf NULLS LAST Notice that the generated GROUP BY becomes GROUP BY U0."id", U2."name", where I want just GROUP BY U2."name". Best I've been able to gather, is that it is related to some default ordering on models, but as you can tell, I've already accounted for that by inserting .order_by(). So I'm a little lost. I tried annotating with Raw sql instead, but in that … -
Django - How to get a custom user model with get_object_or_404
I'd like to retrieve an instance of my User class, which extends AbstractBaseUser . I'd also like to filter my users by a primary key using the django get_object_or_404 shortcut, but this won't work: from django.shortcuts import get_object_or_404 from django.conf import settings user = get_object_or_404(settings.AUTH_USER_MODEL, pk=pk) The following exception is raised: "ValueError at /v1/users/24c47b4a-920e-47c7-902c-80c64c0dd657/ First argument to get_object_or_404() must be a Model, Manager, or QuerySet, not 'str'. In my settings.py, this is what my AUTH_USER_MODEL looks like: AUTH_USER_MODEL = 'users.User' Is there a way to achieve this? -
Get list inside the annotate in django ORM
I have 3 tables:- class Profile(models.Model): id = models.AutoField(primary_key=True) name = models.CharField() ..... #some more field ..... class ProfileTestMapping(models.Model): id = models.AutoField(primary_key=True) profile = models.ForeignKey(Profile) test = models.ForeignKey(Test) ..... #some more field .... class Test(models.Model): id = models.AutoField(primary_key=True) name = models.CharField() ..... #some more field .... 1 profile has many tests. So I want to get the data like this:- This is a raw array I am writing for the example purpose. profileList = [ { profileName: 'any-name', ...... otherProfileDetails ....... testList: [ { name: testName, id: 463743 }, { name: testName2, id: 463743 } ] } ] I am getting the count of test mapped with the profile using annotate but not getting the details of the test which are mapped with the profile. -
Django when tried to Like a post, value is changing but also gives error NoReverseMatch at /something/something/
I am working on a project on django app, where user can like or dislike a post. Like and dislike buttons are working fine, also value is saved in database. But when button "Like" is clicked it shows this error: NoReverseMatch at /gallery/likes/ Reverse for 'detail' with keyword arguments '{'pk': 9}' not found. 1 pattern(s) tried: ['gallery\/(?P[^/]+)$'] but i don't want this error. model.py class Album(models.Model): caption = models.TextField() photo = models.FileField() uploader=models.ForeignKey(User,on_delete=models.CASCADE,default=None) likes = models.ManyToManyField(User, related_name='likes',blank=True) def __str__(self): return self.caption def get_absolute_url(self): return reverse('gallery:detail', kwargs={"pk": self.pk}) url.py app_name = 'gallery' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<album_id>',views.detail, name='detail'), path('likes/',views.like_post, name='like_post'), path('album<pk>/delete',views.AlbumDelete.as_view(), name='album-delete'), ] views.py def detail(request,album_id): album = get_object_or_404(Album, pk=album_id) is_liked = False if album.likes.filter(id=request.user.id).exists(): is_liked = True context = { 'album' : album, 'is_liked' : is_liked, } return render(request, 'gallery/detail.html', context) def like_post(request): album = get_object_or_404(Album, id=request.POST.get('album_id')) is_liked = False if album.likes.filter(id=request.user.id).exists(): album.likes.remove(request.user) is_liked = False else: album.likes.add(request.user) is_liked = True return HttpResponseRedirect(album.get_absolute_url()) detail.html <form action="{% url 'gallery:like_post' %}" method="post" > {% csrf_token %} {% if is_liked %} <button type="submit" name="album_id" value="{{album.id}}" class="btn btn-danger">DisLike</button> {% else %} <button type="submit" name="album_id" value="{{album.id}}" class="btn btn-primary">Like</button> {% endif %} </form> I'm new to django so I'm unable to understand what's the … -
Django form.isValid() always return false in custom user model
I have a custom user model in django following this tutorial. But when I update a user, I receive the error message "User with this Email address already exists.". As my model extends AbstractBaseUser, does this isn't handled by django itself? My view: @login_required def user_add_edit(request, pk=None): user = get_user_model() if request.method == 'POST': if pk: form = UserChangeForm(request.POST) else: form = UserCreationForm(request.POST) if form.is_valid(): user = form.save(commit=False) msg = '' if len(user.last_name) > 0: user.last_name = user.last_name.title() if len(user.first_name) > 0: user.first_name = user.first_name.title() user.password(user.set_password(request.POST['password2'])) user.save() messages.add_message(request, messages.SUCCESS, 'User updated with success. %s' % msg) data = {'valid': True} return JsonResponse(data) else: data = {'valid': False, 'formMsg': [v for k, v in form.errors.items()]} return JsonResponse(data) else: if pk: selected_user = get_object_or_404(user, pk=pk) form = UserChangeForm(request.POST or None, instance=selected_user) else: selected_user = get_user_model() form = UserCreationForm(request.POST or None, instance=selected_user, initial={'password1': "", 'password2': "", 'first_name': "", 'last_name': "", 'email': ""}) return render(request, 'users/add_edit.html', {'form': form, 'selectedUser': selected_user}) -
Django Rest Framework resource doesn't respond to request with invalid token
I have Django project with ViewSet model inherited from Django Rest Framework models.GenericViewSet At the top of the ViewSet I've set up authentication with permission_classes = (permissions.IsAuthenticated,) When I make a request with an existing token, it works as expected. But if the token doesn't exist, the server seems to never respond. How can I debug this behavior? Or probably do I need something else for this permission class to properly process invalid tokens? I need the server to respond with something about wrong credentials. For example, 401 and some custom message (if there is no better alternative). -
How to display recent items for personalization in a web app?
In GitHub, you will notice that when you want to reference existing issues or mark an issue under projects GitHub intelligently will show you the most recent items that you visited recently first. I’m using django to build a web app and i like to incorporate the same feature. Do i have one giant table that stores all the items that all users visit? If so how do I then join that back with the main table I am supposed to search on to produce the sort correctly? I cannot obviously add a new date time column called “visited” to the main table as that will mean there is no personalization What am I missing in terms of understanding? -
Django Page not found using simple path
Im using django version 2.1.4. Created app 'main' inside my project and trying to get to its urls.py to show sentence "text" under the admin/main/test/ However while admin/ and admin/main/ are working, admin/main/test/ gives error Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/admin/main/test Using the URLconf defined in statystyki.urls, Django tried these URL patterns, in this order: main/ admin/ [name='index'] admin/ login/ [name='login'] admin/ logout/ [name='logout'] admin/ password_change/ [name='password_change'] admin/ password_change/done/ [name='password_change_done'] admin/ jsi18n/ [name='jsi18n'] admin/ r/<int:content_type_id>/<path:object_id>/ [name='view_on_site'] admin/ auth/group/ admin/ auth/user/ admin/ main/movie/ admin/ ^(?P<app_label>auth|main)/$ [name='app_list'] The current path, admin/main/test, didn't match any of these. My files: statystyki/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('main/', include('main.urls')), path('admin/', admin.site.urls), ] main/urls.py from django.urls import path from .views import test_response urlpatterns = [ path('test/', test_response), ] views.py from django.shortcuts import render from django.http import HttpResponse def test_response(request): return HttpResponse('test') Could you help me to find the issue which is causing this? I already added 'main' to installed apps in settings.py -
Multiple auth backends for django auth - how to set it through the entire app
The django auth backend conflicts with social_auth backend and raises the multiple auth backends in calling login() but the login() is being called through LoginView.as_view(). So how can I set it through the entire app or to pass the backend to LoginView.as_view()? path('login/', django.contrib.auth.views.LoginView.as_view ( template_name='login.html', ), name='login'), -
Getting database info and sending it as XML file in django
I'm working on a django webservice which needs to handle database information from a SQL-server database. My database structure looks like this: As you can see I've got a table which holds orders Data_Orders which is refrenced by the Data_Models tablewhich stores the relation between each order and the corresponding models. This table also refrences Data_ModelColors where an ID is stored used to determine the name of the color in the Data_Color table. last, there is a Data_ModelSizes table which holds the information i'm most intrested in, the ammount. Whith this setup I am able to specify the amount of models to add to the orders for each color and size. Now I have to convert information from this database to XML files to send in a HttpResponse in django. As you can see each order also specifies a company to send it to(bottom left of the diagram). I need to generate XML files with orders for each company whenever I get a request from said company. I've created a function that is able to send an XML file in a HttpResponse like this: def index(request): template = loader.get_template('orders/testTemplate.xml') tpcontext = {'orderinfo': 'testordername'} return HttpResponse(template.render(tpcontext, request)) I'm currently using a … -
problem in class-based views in django SyntaxError: invalid syntax
I'm following django 2.1 tutorial, based on this link https://docs.djangoproject.com/en/2.1/topics/class-based-views/ Here is my Code for books/urls.py from django.urls import path, re_path from . import views from book.views import BookListView app_name = 'book' urlpatterns = [ path('', views.index, name = 'index') path('list/', BookListView.as_view(template_name="media/templates/book/book_list.html")), ] Below is my book/views.py from django.shortcuts import render from .models import Author, Book, BookInstance, Genre from django.views.generic import ListView def index(request): num_books = Book.objects.all().count() num_instances = BookInstance.objects.all().count() num_instances_available = BookInstance.objects.filter(status__exact = 'a').count() num_author = Author.objects.count() context = { 'num_books' : num_books, 'num_instances' : num_instances, 'num_instances_available' : num_instances_available, 'num_author' : num_author, } return render(request, 'book/index.html', context) class BookListView(ListView): model = Book Error I'm getting is File "E:\DJango\mysite\book\urls.py", line 8 path('list/', BookListView.as_view(template_name="media/templates/book/book_list.html")), ^ SyntaxError: invalid syntax -
Creating an object A with a ForeignKey to object B, when creating an object B
When creating posts in a text editor in the Django administration panel, I upload files. I want to link this file with the current post through a foreign key. The problem is that the post has not yet been created, but I need to refer to it. My model: class UploadFile(models.Model): upload_by = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, on_delete=models.CASCADE, related_name="uploaded_file_author") file = models.FileField(null=True, blank=True, upload_to='files/%Y/%m/%d/',) post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="file_post") My view: @require_POST def file_upload(request): reqfile = UploadFile.objects.create(file=request.FILES['file'], upload_by=request.user, **post="need an object here")** return JsonResponse({'fileurl': reqfile.file.url})