Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get verbose name of foreign key from objects _meta dynamically in Django
For simplicity sake, with models like the following: class Plan(models.Model) name = models.CharField(max_length=255, verbose_name="Phone Plan Name") monthly_charge = models.FloatField() class Company(models.Model): name = models.CharField(max_length=255, verbose_name="Company Full Name") phone_plan = models.ForeignKey(Plan) class Client(models.Model): name = models.CharField(max_length=255, verbose_name="Client Full Name") company = models.ForeignKey(Company) Given a string, I want to know if there is an easy way to retrieve the verbose name of a model attribute even if that string traverses through foreign keys. I know that I can get the verbose name of a Client attribute by Client._meta.get_field("name").verbose_name and this would result in "Client Full Name". But what if I had the string "company__phone_plan__name", I cannot simply use Client._meta.get_field("company__phone_plan__name").verbose_name to arrive at "Phone Plan Name" as it yields an error. These strings will be dynamic, so I am wondering what is the easiest way to arrive at the proper verbose name of an attribute, even if it traverses models? This particular case is using Django 1.11 Thanks! -
Django select_related on chained foreign keys
I read the documentation and all the related questions here but I haven't properly understood how select_related behaves on chained/multiple foreign keys. Assume we have the following models: class RecordLabel(models.Model): title = models.CharField(...) class Band(models.Model): band_name = models.CharField(...) class Artist(models.Model): record_label = models.ForeignKey(RecordLabel,...) belongs_to_band = models.ForeignKey(Band, ...) class Producer(models.Model): customer = models.ForeignKey(Artist, ...) A. How would we use select_related in a Producer.objects.filter(...).select_related(?) query so that everything is preloaded? Would it be like: Producer.objects.filter(...).select_related(customer__record_label, customer__belongs_to_band) and why? B. If class Band had 2 foreign keys A, B then in order to have everything preloaded we would do something like this: Producer.objects.filter(...).select_related(customer__record_label__A, customer__record_label__B, customer__belongs_to_band__A, customer__belongs_to_band__B) or something like this: Producer.objects.filter(...).select_related(customer__record_label__A, customer__record_label__B, customer__belongs_to_band, customer__belongs_to_band) -
django/python: pass **kwargs
I want to build a url. It bring in "kwargs", which it should not. custom_redirect('mieteinheit', kwargs={"wohnungsgruppenname": form.cleaned_data["wohnungsgruppenname"]}) def custom_redirect(url_name, *args, **kwargs): #some code is passed "?%s" % urllib.parse.urlencode(kwargs) This creates: ?kwargs=%7B%27wohnungsgruppenname%27%3A+%27ghs%27%7D But it should create ?wohnungsgruppenname%3Dwohnungsgruppenname -
after deploy django code to aws, datas in django admin are gone
I am new in Django, python , and AWS. I register a user, and I can see the user in my Django admin deployed to AWS. After I write a new feature and 'eb deploy' to AWS. I can see the new feature, but the user I registered before disappear. Can any one help? -
Django Rest Framework many-to-many serialization is not working as expected
I dug into stackoverflow and couldn't find anything related to this error/mistake. Well, I have this model: class ChatRoom(models.Model): class Meta: app_label = 'chatbot' group = models.CharField(max_length=255) category = models.CharField(max_length=255) name = models.CharField(max_length=255) url = models.URLField() online = models.IntegerField(default=0) recaptcha_hash = models.TextField(null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) bots = models.ManyToManyField(MarkBot, through='ChatBot') def __str__(self): return '{0}/{1}/{2}'.format(self.group, self.category, self.name) This serializer: class ChatRoomSerializer(ModelSerializer): bots = MarkBotSerializer(read_only=True, many=True, allow_null=True) class Meta: model = ChatRoom fields = ['group', 'category', 'name', 'url', 'online', 'recaptcha_hash', 'bots'] read_only_fields = ['pk', 'created_at', 'updated_at'] My many-to-many (with "through") middle model is: class ChatBot(models.Model): class Meta: app_label = 'chatbot' room_token = models.TextField() bot = models.ForeignKey(MarkBot, on_delete=models.CASCADE) chat_room = models.ForeignKey(ChatRoom, on_delete=models.CASCADE) And, in all my JSON serialized results I receive the attribute "bots" equals "null", even when I have a bot attached to a room. Expected Output A list of bots attached to that specific room or null if it has none. Thank you, in advance! -
What is wrong with my view that I'm getting an attribute error?
I'm getting the following error when trying to cancel a payment in my project the error is: AttributeError at /compra/cancelar/24761/ 'NoneType' object has no attribute 'get' and in my terminal is: File "kentriki/financials/views.py", line 2686, in cancel_user_order ) = WebCA.get_order_cancellation_data(request.context, order_id) File "kentrikios/core/klogging.py", line 85, in wrapper raise e AttributeError: 'NoneType' object has no attribute 'get' [19/Sep/2018 11:44:31] "GET /compra/cancelar/24761/ HTTP/1.1" 500 224272 The definition of in my view is this: def cancel_user_order(request, order_id): """ Renders the user's order to cancel it :param order_id: Order ID :type order_id: int """ store_url = request.subdomain if store_url and request.method == 'GET': store, template_root, static_root = WebCA.get_store_template_paths(request.context, store_url) template = template_root + 'user_cancel_order.html' params = dict(store=store, template_root=template_root, static_root=static_root, can_cancel=None) try: # WebCA.get_order_cancellation_data ( order, cancel_data, score_verbs, uncomplete_reasons, cancelation_payment, is_canceled, charges_dict ) = WebCA.get_order_cancellation_data(request.context, order_id) if order.seller_id != store.user_id: raise Http404 params['order'] = order params['cancel_data'] = cancel_data params['score_verbs'] = score_verbs params['uncomplete_reasons'] = uncomplete_reasons params['cancelation_payment'] = cancelation_payment except DataNotValid: params['can_cancel'] = False return render_response_with_fragment(['store_navbar', 'store_footer'], store.id, request, template, params) else: raise Http404 -
Derived model assignment in Django
Consider Django model B derived from model A: class A(models.Model): # ... class B(A): # ... Now let model C refer to A: class C(models.Model): a = models.ForeignKey('A') Let's we have an object c of class C. Will c.a = b (where b is an object of class B) do the right thing, assigning the primary key of A not of B? -
Django-Differentiate between verified and non verified users in database via email confirmation link
I want to differentiate between the users who signed up and are verified through email confirmation link, and those who signed up but not verified through email confirmation. I tried "is_active" and "is_authenticated" but did not got the desired results. -
Querydict not recognizing json array in django
Django and Django Rest Framework is not sensing the array in the following JSON object: { "datum": [ {'proposed':'20/sep/2018', "pk":"475"}, {'proposed':'20/sep/2018', "pk":"517"} ] } When I do a print(request.data) this is the output: <QueryDict: {'{"datum":[{"proposed_submission_date":"20/Sep/2018","pk":"475"},{"proposed_submission_date":"20/Sep/2018","pk":"512"}]}': ['']}> and when I do a print(request.data.keys())I get: {"datum":[{"proposed_submission_date":"20/Sep/2018","pk":"475"},{"proposed_submission_date":"20/Sep/2018","pk":"512"}]} You can see that its taking the json string as the key, and not assigning "datum" as the key. Do I need to do something else with the JSON string? I'm doing an AJAX PUT to the Django rest framework backend. -
Number of days between 2 dates for each row,then Add All of them for the whole database
models.py class Orders(models.Model): orderid = models.IntegerField(db_column='orderID', primary_key=True) pickupdate = models.DateField(db_column='pickupDate', blank=True, null=True) returndate = models.DateField(db_column='returnDate', blank=True, null=True) I would like to substract the returndate with pickupdate (returndate - pickupdate) for each rows, and then add them together for the whole table I have tried the code below, but it produced large decimal numbers. Orders.objects.aggregate(days=Sum( F('returndate') - F('pickupdate') ) I also have tried the code below,but it produced error Orders.objects.aggregate(days=Sum( 'returndate' - 'pickupdate' ) -
Django; Admin site doesn't load from S3
I'm working on Django project. I deployed my app into elasticbeanstalk but I cannot go to admin page. (Templatedoesnotexist) So I was trying to see if Admin CSS loads from S3 and works on local but it doesn't work as well. (I can go to admin page on local because html works.) Other static files load from S3. Here is settings.py #AWS S3 configuration # --------------------------------------------------------------------------------- AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID', '') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY', '') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME', '') AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' AWS_DEFAULT_ACL = None #STATIC FILES configuration # --------------------------------------------------------------------------------- # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_DIRS = ( os.path.join(APPS_DIR, 'static'), ) STATICFILES_LOCATION = 'static' STATICFILES_STORAGE = 'config.storage_backends.StaticStorage' First why doesn't Admin CSS load from S3? How can I fix this? Second how can I fix so Admin site works in production? -
how can I edit a fillable pdf in python/django without making output pdf non-editable?
I want to edit a fillable pdf using python/django and resulting pdf should be editable. I tried pdg jinja but resulting output in not editable. open to any suggestion -
Django dynamic filter based on variable (str)
I am writing a function that can return table items based on a dynamically inserted model. So I need to refrain from using the model name in the function. Now I sometimes will have a many-to-many relationship with another model and want to select on that. Say I have a projects = ManyToMany(Projects) field in my Files model. Now I can use: filter(projects__in=[1]) to select for files related to projects with id 1, but I need the projects part of this filter to be dynamic, so I can use something like: a_field = 'projects' filter(a_field+'__in'=[1]) which obviously doesn't work. How should I do this? -
Terminology of Static- and Media-Files in Django
I'm having trouble understanding the difference of using static and media files in Django. As far as I understand it, static files are files that are usually unchanged by users of my app such as CSS or e.g. a banner-image or logo, whereas media files are possibly user defined. Furthermore I get confused by the whole terminology when it comes to deployment. Let's say, I have a development environment, where a model has some FileField, e.g. a profile picture, that can be provided by the user. Is this file considered to be media? In production, I want to create a page, that serves that file inside a template or view (e.g. on the user's profile page). Wherever the django docs speak about serving files in production, they are referred to as static. So my question here: In a productive environment, does user uploaded content count as static or do I need to turn all media files into static ones during deployment or is it okay to serve media files in production? -
Django W.005: Admin Not Unique Namespace
I keep getting the warning: (urls.W005) URL namespace 'admin' isn't unique. You may not be able to reverse all URLs in this namespace However, I've checked my URLs files in my main and sub projects and this is my only call to admin: ... from django.contrib import admin ... admin.autodiscover() ... urlpatterns = [ url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin/', include(admin.site.urls)), ... ] The full setup is far too large to put here. But you can browse at your leisure on github: https://github.com/RPI-HASS/rpi_csdt_community -
Proper setting for foreign key on_delete when trying to keep historical data
I have a quick question about using a foreign key in a model. Let say I have a table of cars and a table of engine types. I want the car table to use the engine type as a foreign key to populate the car's engine. That is easy enough. My problem is this. Lets say that the engine table only should show active engines that are in production, so if they have stopped making the 3.5 liter 120 hp engine from the 1970's I don't want it to appear on the selection of engine types when you are creating a new car. The other part of this is that I want all the records to stay in the car database for historical reporting. So what happens is I try and delete the engine mentioned above and if I have on_delete=Cascade this doesn't do what I want because I lose the historical data. If I have on_delete=Protect I can't delete the unwanted engine model. How do you handle this? Thanks -
Using max() with Django query
Is there a way to make this query work with Django? stage = Task.objects.filter(id = input_stage.id)\ .update(start_date = max(data.get('start_date'), F('start_date')), finish_date = max(data.get('finish_date'), F('finish_date'))) Now I get an error: TypeError: '>' not supported between instances of 'F' and 'datetime.date' -
Django 2 - Login Authentication PROBLEM: MultiValueDictKeyError for username
I am trying to implement for the first time the Authentication for Django. I am creating the Login part following the official guide of Django 2. However I am having this problem: "Exception Type: MultiValueDictKeyError Exception Value: 'username'" I created an app called "accounts". Inside of it, I have the followings: In accounts/views.py: from django.shortcuts import render, redirect from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout def login(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: return redirect('home') else: return render(request, "accounts/login.html") In templates/accounts.html: {% extends 'mysite/base.html' %} {% block content %} <h1>Login</h1> <form method="POST" action="{% url 'login' %}"> {% csrf_token %} Username: <br> <input type="text" name="username" /> <br> Password: <br /> <input type="password" name="password" /> <br> <br> <input class="btn btn-primary" type="submit" value="Sign Up!" /> </form> {% endblock %} In urls.py (of my app "accounts" not of the project): from django.urls import path, include from . import views urlpatterns = [ path("signup/", views.signup, name="signup"), path("login/", views.login, name="login"), path("logout/", views.logout, name="logout"), ] Many thanks for your help. -
Django multi-tenants error in admin mytable matching query does not exist
I have a django project that i have to use in multi tenants mode. i use django-tenant-schema (https://django-tenant-schemas.readthedocs.io/en/latest/) all was set done and my app run ok, the only problem is when, in admin templates i try do add record in a table. Wen try to add a record using 'public' schema all works done, but when i run app using another schema i got the error temp_case matching query does not exist. My table, in model.py is: class temp_case(models.Model): main_id = models.ForeignKey(temp_main, null=True, blank=True, verbose_name="Main Template", on_delete=models.CASCADE,) descr = models.CharField(max_length=200, verbose_name="Case description") #Fields for API permissions owner = models.ForeignKey('auth.User', related_name='tcase_owner', on_delete=models.CASCADE, verbose_name="API Owner") class Meta: verbose_name = '2-Test Case' verbose_name_plural = '2-Test Cases' ordering = ('descr',) def __str__(self): return '%s -> %s' % (str(self.main_id), self.descr) def __repr__(self): return self.descr in my settings.py i setup the application like this: SHARED_APPS = ( 'tenant_schemas', # mandatory, should always be before any django app 'frontend', # you must list the app where your tenant model resides in 'django.contrib.contenttypes', # everything below here is optional 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.messages', ) TENANT_APPS = ( 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.messages', 'django.contrib.sessions', 'django.contrib.admin', 'rest_framework', # your tenant-specific apps 'frontend', 'backend', ) INSTALLED_APPS = [ 'tenant_schemas', # mandatory, should always … -
Django 2 - Login Authentication PROBLEM: MultiValueDictKeyError for username
I am trying to implement for the first time the Authentication for Django. I am creating the Login part following the official guide of Django 2. However I am having this problem: "Exception Type: MultiValueDictKeyError Exception Value: 'username'" In views.py: from django.shortcuts import render, redirect from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout def login(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: return redirect('home') else: return render(request, "accounts/login.html") In templates/accounts.html: {% extends 'mysite/base.html' %} {% block content %} <h1>Login</h1> <form method="POST" action="{% url 'login' %}"> {% csrf_token %} Username: <br> <input type="text" name="username" /> <br> Password: <br /> <input type="password" name="password" /> <br> <br> <input class="btn btn-primary" type="submit" value="Sign Up!" /> </form> {% endblock %} In urls.py (of my app "accounts" not of the project): from django.urls import path, include from . import views urlpatterns = [ path("signup/", views.signup, name="signup"), path("login/", views.login, name="login"), path("logout/", views.logout, name="logout"), ] -
Django: Filter database query in template
I think the answer is simple but I can't figure it out. So I have three models: host, project and a model that relates those two. In my template I have two 'select' inputs, one for the host and one for the project. What I want to do is show only the projects that are related to the host that is currently selected(the relations are described in the third model). Perhaps there is a better way to do this in the views.py file than in the html page. -
Paginate custom queryset based on object
I've got following API View with custom queryset based on object. I'm getting object by pk provided in url. I want to return all related instances for object with pagination. class ListVotedAPIView(generics.ListAPIView, VoteModelMixin): serializer_class = UserSerializer def get(self, request, *args, **kwargs): return self.voted(request) def get_queryset(self): instance = self.get_object() return services.get_voted(instance) class VoteModelMixin: def voted(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) And here is services.get_voted(): def get_voted(obj): """ Return all users that voted `obj`. """ obj_type = ContentType.objects.get_for_model(obj) return User.objects.filter( votes__content_type=obj_type, votes__object_id=obj.id ) The problem is that generics.ListAPIView list() method starts with this line: queryset = self.filter_queryset(self.get_queryset()) And I'm getting the following error: RecursionError: maximum recursion depth exceeded -
can we use tornado asynchronous library in django to achieve asynchronous web request inside django views?
I am having the Django project, have to request external api to get data and that should be asynchronous. but in Django, there is no asynchronous library. so that could I use tornado asynchronous library inside the Django app? is that works? please elaborate on your answer. thank you in advance. -
Migrations and two applications sharing parts od database on different machines
Question: how to organise ./manage migrate on client in following setup: I have to create django web site on client machine, with local usesr to login there and do some stuff locally. There is also server with huge django application, which have its users doing things on the server. And there is "just python" application on client machine, which gets data transtferred from server, stored locally and work with the local copy with direct SQL queries (lot of server table-connections are not used there), modifiing only two local tables, which structure (but not data) is copied from the server for consistency. The server django application and the client "just python" applications have already established protocol for connecting and transfer data, purely from server to client. Not all tables are transferred (as not all are needed), sometimes only a structure of table is enforced on the client, sometimes also data. The tables are transferred just as content of "normal Mysql tables" via some XML/ssh/whatever, losing its django connections, mainly no auth.* / admin.* / session.* / content.* tables are transferred (as irelevant), while a lot of django model have "modified_by_user" ForeignKey to (nontransfered) User table. This does not matter more on … -
how to pass parameters from Django view to contract function using web3.py
I have a contract which has a payout function with three inputs: function payout(uint256[] ids, address[] recipients, uint256[] amounts) public authorized and a function is defined in views.py which calls that: q=Question.objects.filter() ids = [] adds = [] for cur in q: for a in cur.answer.all(): ids = a.user.id adds = a.user.user_wallet_address bounty_for_answering(ids, adds, cur.ether) return redirect('/') The problem is that I do not know how to pass input arguments to bounty_for_answering.