Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django delete row from table of third level foreign key
I want to delete a row from model or table where I have the foreign_key value of the row to be deleted and the value of first level table row. For example, I have models say A, B, C where B is referring to A, C is referring to B. A id a b c 1 x y 100 2 y z 200 . . . . B id b_col a_id c_col 1 q 1 300 2 r 2 400 . . . . C id c_col b_id c_col 1 i 1 500 2 j 2 600 . . . . So here i have model C column c_col value which is 600 and model A column 'c' value=200 so want to remove row from model C where c_col=200. One way is, a = A.object.filter(c=200) b = B.object.filter(a_id=a.id) c = C.object.filter(b_id=b.id).delete() Is there any better way to do this in one single query instead of 3. -
Django queryset annotate calculated values from another model
Please help with the following: I have 4 models in a hierarchy: analysis, books, category and publisher. In my app you analyze books. The books belong to categories where you can view the average analysis rating of all the books in the category. This average rating (that I call avg-catg-rating) is not stored in the dB, it’s calculated in the view. Here’s my question: how do I get the average category rating for each category that the publisher has onto a single publisher view? In other words, how do I annotate the avg-catg-rating onto each category so I can display all of them on the publisher’s page? So do I iterate using the category somehow like this question? If yes, please give a tip on how because I'm not really sure how to go about it. I also tried groupby as suggested by this chap, but I could only get the count of book instances, I couldn't accurately annotate the avg-catg-rating. To clarify: Models.py: class Analysis: #a bunch of fields for analysis book = models.ForeignKey class Book: #a bunch of fields category = models.ForeignKey class Category: #a bunch of fields publisher = models.ForeignKey publisher/views.py: class ViewPublisher: def get_context_data(self, **kwargs): category_qs … -
Django 1.11: export queryset to csv using classes
I am having trouble exporting the results of a Django query to csv using a subclass of my query class as suggested here. https://stackoverflow.com/a/29678525/3973597 I end up with a Page not found (404) error. Here is the relevant code... views.py class QueryResultsView(ListView): template_name = 'query/query_results.html' model = StDetail context_object_name = "object_list" def get_queryset(self): form_input = self.request.GET filters = {"person_name": form_input.get('name'), "city": form_input.get('city'), } # delete keys that are None filters = {k: v for k, v in filters.items() if v is not ''} self.detail_data = get_list_or_404(self.model, **filters) return(self.detail_data) def get_context_data(self, **kwargs): context = super(QueryResultsView, self).get_context_data(**kwargs) context['query_results'] = self.get_queryset() return(context) class QueryResultsCsvView(QueryResultsView): # Subclass of above view, to produce a csv file template_name = 'query/QueryResults.csv' content_type = 'text/csv' urls.py app_name = QueryConfig.name urlpatterns = [ ... url(r'^query', QueryFormView.as_view(), name='person-query'), url(r'^results', QueryResultsView.as_view(), name='query-results'), url(r'^results/csv/$', QueryResultsCsvView.as_view(), name='query-results-csv'), ] query_results.html ... <a href="{% url 'query:query-results-csv' %}">Download Results</a> ... QueryResults.csv Date, City, Name, Sex {% for object in object_list %} {{object.date}},{{object.city}},{{object.name}},{{object.sex}} {% endfor %} The query works without any problems. However, when I click on the Download Results link I get a Page not found (404) error. Can somebody tell me what I'm missing? -
Django userCreationForm modify username in view
I am facing a problem with my Django application requirement. I have a signup form extending userCreationForm class and adding some extra fields to it. On my form in template (signup.html) I have email, password & zip only, no user name and I am suppose to set username at the server similar as user email+some hash. I have tried doing it in form class with clean_field, init, and clean. But nothing works. Every-time it's calling form_invalid method on the view. I fixed the form in form_invalid and called 'return self.form_valid', still no luck. I can't set the username on client end. Can one help me to figure out this. I have wasted three days already. Let me know if I am missing any information here. -
Problems with the schemes using multi-tenants and multilanguages in Django
1239/5000 Good day. I have built a system multi languages and simultaneously with multi-tenants with PostgreSQL database all this based on django. This system is with 12 languages (English, Portuguese, Spanish, Russian, Hindu, Arabic, German, Japanese, Chinese, Traditional, Simplified Chinese and Dutch). At the moment of entering the main page, from there anyone can change the language, when you click on the register, the person can be Arabic and I imagine that the person at the time of registering and entering the name of their work environment does with your native language. Thanks to the multi-tenants, this is added to the database. But if you write in your native language, this does not allow you to add a database and it throws me an error: ['Invalid string used for the schema name.']. I'm looking at some pages based on multi-tenants and I see the page "slack.com", when you register some environment as for example in Arabic language in the url is out as "w1544194703-qdg796900.slack .com". I do not know how that page really works, but that would be the idea that I can do. I would like to know some validation or example. Any answer in well taken, thank you … -
Generate urls automaticlly in django
I want to create an automatic RESP API for any Django project. At first, i can find all models in django project like this: from django.apps import apps for app in apps.get_app_configs(): for model in app.get_models(): ### do something with model here At second, I want to create an url, for example if the model name is lender, i want to create url /lender/, if borrower then /borrower/ etc. But i can't find a way to do this. Can anyone help me? -
Return values of custom authentication in Django REST Framework
I'm trying to write my basic custom authentication for Django REST Framework. I have the following auth backend: class JoeAuth(authentication.BaseAuthentication): def authenticate(self, request): username = request.META.get('HTTP_X_FORWARDED_USER') if not username: return try: user = User.objects.get(krb_name=username, active=True).name except User.DoesNotExist: raise PermissionDenied('Unauthorized user') return (user, None) Accompanied with a view: @api_view() def hello(request): return Response(data='hello') And of course enabled in settings.py: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'helloworld.auth.JoeAuth', ) } Now, if a request comes in and does not specify the HTTP_X_FORWARDED_USER header, the authenticate() function returns None. According so DRF docs: To implement a custom authentication scheme, subclass BaseAuthentication and override the .authenticate(self, request) method. The method should return a two-tuple of (user, auth) if authentication succeeds, or None otherwise. In some circumstances instead of returning None, you may want to raise an AuthenticationFailed exception from the .authenticate() method. A None means authentication failed and should ideally return 401 or 403. However, in practice this doesn't seem to be the case. A request without the HTTP_X_FORWARDED_USER is simply allowed and 200 is returned: $ http http://127.0.0.1:8000/ HTTP_X_FORWARDED_USER:joe HTTP/1.1 200 OK "hello" $ http http://127.0.0.1:8000/ HTTP/1.1 200 OK "hello" Am I misunderstanding the documentation in the sense that a None is considered a successful … -
Login validate with encrypted password in PHP
this is my first question in Stack Overflow and I hope you can help me. I have a PostgreSQL database, which have many users. Users' passwords are encrypted in this format: sha1$678ae$0dd4b5a9588be91a931d1ef1f7e7053477c1478e This encryption was done with Django (although I don't know if you can encrypt it directly in database). What I'm trying to do is make a PHP application that can use and validate these users, with those encrypted passwords. How could I do it? Thanks in advance and sorry for my bad english. Cheers. PS: I'm using PHP 7. -
Why am I unable to access foreign key information in django templates.
I'm working on a django app that needs to create XML files to respond to requests. I've go my models setup like this: # This is an auto-generated Django model module. # You'll have to do the following manually to clean this up: # * Rearrange models' order # * Make sure each model has one field with primary_key=True # * Make sure each ForeignKey has `on_delete` set to the desired behavior. # * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table # Feel free to rename the models, but don't rename db_table values or field names. from django.db import models class Color(models.Model): id = models.AutoField(db_column='ID', primary_key=True) # Field name made lowercase. name = models.CharField(db_column='Name', unique=True, max_length=255) # Field name made lowercase. class Meta: managed = False db_table = 'Data_Colors' def __str__(self): return "Color: [" + self.id.__str__() + ", " + self.name + "] " class Company(models.Model): orders = models.ManyToManyField('Order', through='OrderCompany') id = models.AutoField(db_column='ID', primary_key=True) # Field name made lowercase. name = models.CharField(db_column='Name', max_length=255, blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'Data_Companies' def __str__(self): return "Company:[" + self.orders.__str__() + ", " + self.id.__str__() … -
is there any way to create unique id's to particular field in django model
class Product(models.Model): name=models.CharField(max_length=128) category=models.ForeignKey('Category',on_delete=models.CASCADE) rate=models.IntegerField() peices=models.IntegerField(default=True) def __str__(self): return self.name class Category(models.Model): name=models.CharField(max_length=128) def __str__(self): return self.name here in the product model if i assign 100 integers to peices every piece should have a unique id for eg: levis is a product and if i add 100 to the pieces section of this model so that i could get 100 different unique id's i tried a lot googling it but its of no use anykind of help is appreciated -
Using Postgres Shell to createuser
I am following a tutorial from the book Mele, Antonio. Django 2 by Example: Build powerful and reliable Python web applications from scratch (Kindle Locations 1917-1918). Packt Publishing. Kindle Edition. I'm at this part: > Adding full-text search to your blog > Installing PostgreSQL I'm on Windows 10 and I installed Postgres fine. The instructions say to type in the postgres shell: su postgres createuser -dP blog I guess I'm trying to create a user called 'blog' that will have a password and be allowed to create databases? When I do that I get: Server [localhost]: su postgres Database [postgres]: createuser -dP blog Port [5432]: Username [postgres]: psql: warning: extra command-line argument "postgres" ignored psql: warning: extra command-line argument "-d" ignored psql: warning: extra command-line argument "createuser" ignored psql: warning: extra command-line argument "-dP" ignored psql: warning: extra command-line argument "blog" ignored psql: warning: extra command-line argument "-p" ignored psql: warning: extra command-line argument "5432" ignored psql: could not translate host name "su" to address: Unknown host Press any key to continue . . . I'm not sure what to do or what exactly is going on? The instruction is pretty unclear -
Why .WMV files have mime type 'video/x-ms-asf' instead of 'video/x-ms-wmv'?
I need to accept only MP4 videos and WMV videos in a Django web app I am building. For that, I am checking the mime type of the file once it hits the server. As far as I understand, MP4 files have 'video/mp4' mime type, which is exactly what I am receiving on my web app. The problem comes with the WMV files, which according to every site I found (e.g.: this and that) should have 'video/x-ms-wmv' as the mime type. When I get this files on the server and I inspect them using python-magic I get 'video/x-ms-asf' as its mime type. I have converted some youtube videos to WMV videos using different online converters but the result is always the same. So actually, I do not know what am I doing wrong here. Maybe I have a problem of concets, where WMV videos can also have 'video/x-ms-asf' mime type, and not only 'video/x-ms-wmv' Maybe python-magic is not reading the mime type correctly, which I think would be hardly the case. Any help is deeply appreciated. As a side note, I am using python-magic instead of django's file.content_type because the second is not reliable. Just change the file's extension to … -
error:Manager isn't available; 'auth.User' has been swapped for 'Log.CUstomUser' in Django
when User want Register my website show this error: Manager isn't available; 'auth.User' has been swapped for 'Log.CUstomUser' i use import AbstractUser in my model i work with Django freamwork python Model: from __future__ import unicode_literals from django.contrib.auth.models import AbstractUser , from django.db import models # Create your models here. class CustomUser(AbstractUser): country = models.CharField(max_length=200) number = models.IntegerField(default=1) age = models.IntegerField(default=1) View: from __future__ import unicode_literals from .forms import Register from django.shortcuts import render , render_to_response from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt # Create your views here. @csrf_exempt def Home(request): if request.method == "POST": form = Register(request.POST) if form.is_valid(): form.save() return HttpResponse("Greate") else: form = Register() return render_to_response('home.html' , {'form':form}) Forms: from django import forms from django.contrib.auth.forms import UserCreationForm from .models import CustomUser from django.contrib.auth import get_user_model from django.contrib.auth.models import User class Register(UserCreationForm): email = forms.EmailField(required = True) number = forms.IntegerField() age = forms.IntegerField() class meta: model = User field = ( 'number', 'age', 'username', 'firstname', 'lastname', 'email', 'password1', 'password2' ) please fix my error -
How to call conditional statements on template tags with no arguments django
I'm trying to display html content based on what a template tag function returns. template.html {% load custom_tags %} {% if return_something == True %} # display something {% endif %} custom_tags.py from my_app.models import MyModel @register.simple_tag() def return_something(): if MyModel.objects.filter(active=True).exists() return True else: return False How do I do this? Thank you! -
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