Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - How to change dropdown form into table
I'm creating an application in Django and I'm having an issue with iterating through options in a dropdown from a form in Django. I was wondering if anyone could be of assistance. detail.html {% for subject in subject_list %} <form action="" method="POST"> {% csrf_token %} <table class='table table-borderless table-hover'> <tbody> <tr> <td>{{ subject.subjectname }} {% for field in form %} {{ field.hidden }} {% endfor %} </td> </tr> </tbody> </table> <button type="submit" id="login-btn" class="btn">Create a new evaluation</button> </form> {% endfor %} forms.py class CreateEvalForm(forms.ModelForm): subjectname = ModelChoiceField(queryset=Subject.objects, label='', empty_label="Choose subject..") class Meta: model = Evaluation fields = ['subjectname', ] models.py class Subject(models.Model): id = models.AutoField(primary_key=True) subjectname = models.CharField(max_length=255, help_text="Type the name of the subject.") slug = models.SlugField(max_length=200, unique=True) Ideally we want it to look like on the picture below: Note that the picture is in danish and Fag = Subject, Opret ny evaluering = Create new evaluation and Se evaluering = View evaluation we want this we don't want this -
redirecting users after login django
By default after login django redirects the user to an accounts/profile page or if you edit the LOGIN_REDIRECT_URL you can send the user to another page you specify in the settings.py. I want my users to, after logged in, not be able to go to the login page but instead be redirected to the LOGIN_REDIRECT_URL automatically. Is there a way of doing it using the default login view? Any input is appreciated. -
Django Performance, APIView vs ViewSet
I was looking at building a star topology type model with a CI/CD workflow, with a white list based signal flow, and with that design model I want to integrate APIs, but I want to optimize for performance to push my code to the limits. I was looking at APIView vs ViewSet, where one allows me to do a wide array of things, to include interacting with other APIs with an API, whereas the other is pretty well defined with preset tasks in mind, typically focused towards working with specific systems and models, but I wanted to also know if by doing so it gained a performance boost, or potentially gained a performance hit by being focused. I'm not entirely sure how to test it either. What are some recommendations on how to effectively test API performance on a side by side basis? My thoughts are to create a python script that queries the system with a specific predefined load, run a series of tasks with that predefined load, and tags the start and stop time. Fastest time wins obviously, but is that a fair assessment? Are there any previously built tools for this, and if so, what are they? … -
What should be applied, ManyToMany or a model with 2 Foreign Keys?
I have two models: Owner and Accountants. A Owner can have 0 or more Accountants, an Accountant can be connected to 1 or more Owners. So far I've created the two models using a ManyToManyField, here they are: models.py class Accountants(models.Model): owner = models.ManyToManyField(Owner, related_name='accountants') company = models.CharField(db_column='Company', max_length=25) fiscal_rep = models.BooleanField(default=False) class Owner(models.Model): name = models.CharField(db_column='Owner_Name', max_length=200) surname = models.CharField(db_column='Owner_Surname', max_length=30) property = models.ManyToManyField(Property, blank=True) I've created my form to add the accountant, it looks like this: class AccountantAddForm(forms.ModelForm): owner = forms.ModelMultipleChoiceField(queryset=Owner.objects.all(),widget=forms.Select( attrs={ ... The problem here is that when I add an accountant, the Owner field is expecting more than one value, and on my form I pass the owner pre-filled as initial data, so I came up with an idea of making another model named Owner_Accountant connecting both Owner and Accountants models, as below: class Owner_Accountants(models.Model): owner_pk = models.ForeignKey(Owner, related_name='owner_accountant') accountant_pk = models.ForeignKey(Accountants, related_name='accountants_owner') What I want to know is: is this a good solution or is it quite the same? Is there a better way to do this, or am I doing it completely wrong? -
Django Channels : How to run AsyncConsumer as a worker
In Django channels, I want to run an AsyncConsumer in an infinite loop as a separate process, like a worker. I can't use the usual worker because the channel name is fixed there. In my case, I want to use my own channel name on which to send data. I want to create a new channel name for the consumer to listen on. I was able to this in a crude way by just creating my own channel like below. self.layer = get_channel_layer() self.channel_name = await self.layer.new_channel() Similarly sending await self.layer.send(self.master, data) But, I thought, if we can use the AsyncConsumer and a recommended way to listen in a loop (as in runworker), it might be more stable. Any thoughts... -
How to accelerate autocomplete function with Django?
I have implemented django-autocomplete-light on my website (Python 3.6.5 / Django 1.11.20) but retrieving results is very slow (www.capelight.com). The source database is made of 12,000 names (cities, provinces, etc). How can I accelerate this process ? I have read that implementing a Trie strongly accelerates the process, but I have no clue how to do that. Or maybe django-autocomplete is already based on Trie ? Thanks a lot -
How to create pagination and category filter in django-cms?
I got the next model: class Post(models.Model): title = models.CharField(max_length=100) short_description = models.CharField(max_length=100) image = models.ImageField(upload_to="uploads/images/") content = HTMLField(blank=True) slug = AutoSlugField(always_update=True,populate_from='title', unique=True) date_created = models.DateField(default=datetime.date.today()) categories = CategoryManyToManyField() Here I get posts list: posts = [] for plugin in plugins posts.extend(Post.objects.filter(id=plugin[0].post_id)) My next step its to create pagination and categories filter, but I don't know how I can do that? For pagination, I have a simple solution - I want to split full posts list into small lists with static elements count (3 posts in the example): Full_list = [Post1, Post2, Post3, Post4, Post5, Post6, Post7, Post8, Post9] to split list = [[Post1, Post2, Post3], [Post4, Post5, Post6], [Post7, Post8, Post9]] Every element of the list corresponds to one page of the pagination. For every pagination page, I programmatically generate the page. So every element of list has his own page. And the same mechanism for categories - each category has own page. How to combine those things? Maybe I should create separated pagination pages for every category? -
How to send encrypted ids in admin URLs of django admin interface?
I have an application which uses django admin interface. This application allows user to perform CRUD operations on its products. During these operations, the admin URL exposes the actual ID value of that product like https://localhost/product/1/change. I'm looking for an option to obfuscate that ID value shown in URL like https://localhost/product/F87BA2/change. Can someone please share your thoughts on how to achieve this? Thank you! -
When is _create() method of factory.DjangoModelFactory called when initialising an object?
We are using factoryboy and following the docs seem to do the task intended but am trying to understand what goes behind the screens. We are overwriting _create() method of factory.DjangoModelFactory for custom user creation. However there is no init in the class. How does python ensure that _create() method is called every time a factory object is created? class CustomerFactory(factory.DjangoModelFactory): class Meta: model = Customer @class_method def _create(cls, model_class, *args, **kwargs): ...... <custom_code> alex = CustomerFactory() -
how to connect django database connection by using xampp server
raise ImproperlyConfigured('mysqlclient 1.3.13 or newer is required; you have %s.' % Database.version) django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3. -
How to get the value of Primary Key of any table for a particular row
In django Im creating user, and after that I want the PK of the User and then I want to put it into some other table. I am using the below code id_profile = User.objects.filter(email = email) id_profile = id_for_profile.values("id") here im getting the output "" but i want the Number "11" associated with the variable "id_profile" How can it be done? -
How to define permission on django views?
I have these models: class Author(Model): user = OneToOneField(User, on_delete=CASCADE) # Fields class Post(Model): author = ForeignKey(Author, on_delete=CASCADE) title = models.CharField(max_length=200) text = models.TextField() and a few views as below: def authors(request) authors = Authors.objects.all() return render(request, 'authors.html', {'authors': authors}) The authors' view has a corresponding url path as below: path('authors/', authors, name='authors') in authors.html I loop over authors and for each one, I have a link that sends the author primary key to the author url and view: {% for author in authors%} <a href="{% url 'author' author_pk=author.pk %}"{{author.user.email}}</a><br><br> {% endfor %} Ok; Everybody is able to see the list of authors. I then have author url path as below: path('authors/<int:author_pk>/', author, name='author') path('authors/<int:author_pk>/<int:post_pk>/delete/', author_delete_post, name='author_delete_post') And I have the author view in which I show the posts each author has published and a button to delete it. def author(request, author_pk) author=get_object_or_404(Author, pk=author_pk) author_posts = Post.objects.filter(author=author) return render(request, 'author.html', {'author_posts': author_posts} @login_required def author_delete_post(request, author_pk, post_pk): author=get_object_or_404(Author, pk=author_pk) author_post = Post.objects.get(author=author, pk=post_pk) # I know that author=author is redundent but it makes no problem return redirect(author, author_pk) This author template: {% for author_post in author_posts %} {{author_post.title}}<br> {% if user.is_authenticated and author.user == user %} <a href="{% url 'author_delete_post' … -
Displaying empty chart using chart.js
Displaying empty chart i am using django 2.2 and chart.js. Is there some one who can help me . I can see the data in console.log but not in graph. I am working to solve this problem from hours. views.py class secondapi(APIView): authentication_classes = [] permission_classes = [] def get(self, request, format=None): newlabels = ['black', 'Red', 'Blue', 'Yellow', 'Green', 'Purple'], newdata = [111, 22, 21 , 113, 14, 15], data = {'newlabels':newlabels, 'newdata':newdata, } return Response(data) html page <div class="container-fluid w-50 h-50 float-left"> <canvas id="myChart"></canvas> </div> <script> var endpoint = '/api/chart/data/' var newlabels = [] var newdata = []; $.ajax({ method: 'GET', url: endpoint, success : function(i){ newlabels = i.newlabels newdata = i.newdata console.log(newdata) // working in console var ctx = document.getElementById('myChart'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: newlabels, // CHANGED datasets: [{ label: '# of Votes', data: newdata, // CHANGED }] } }) }, // FIRST ONE error : function(error_data){ console.log('error') console.log(error_data)} }) </script> Getting this result -
How to delete django model User in multi databases?
For example, I have a project (mysite) with two apps (myapp, myapp2). These apps use different databases: settings.py: DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "HOST": "127.0.0.1", "USER": "postgres", "PASSWORD": "root", "PORT": "5432", "NAME": "test", }, "test": { "ENGINE": "django.db.backends.mysql", "HOST": "127.0.0.1", "USER": "root", "PASSWORD": "root", "PORT": "3306", "NAME": "test", }, } Then I write a databases router: from django.conf import settings class AppRouter: def db_for_read(self, model, **hints): return settings.APP_DB_MAPPER.get(model._meta.app_label) def db_for_write(self, model, **hints): return settings.APP_DB_MAPPER.get(model._meta.app_label) def allow_relation(self, obj1, obj2, **hints): db1 = settings.APP_DB_MAPPER.get(obj1._meta.app_label) db2 = settings.APP_DB_MAPPER.get(obj2._meta.app_label) if db1 and db2: if db1 == db2: return True else: return False return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label in settings.APP_DB_MAPPER: return db == settings.APP_DB_MAPPER[app_label] return None Then apply it. settings.py: DATABASE_ROUTERS = ["mysite.app_router.AppRouter"] APP_DB_MAPPER = {"myapp": "default", "myapp2": "test"} Add a model in each app: myapp/models.py: from django.db import models from django.contrib.auth.models import User class TestDefault(models.Model): name = models.CharField(max_length=100) user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True) myapp2/models.py: from django.db import models from django.contrib.auth.models import User class TestApp(models.Model): name = models.CharField(max_length=100) user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True) After migrating, these tables are created: mysql("test" db): +----------------------------+ | Tables_in_test | +----------------------------+ | auth_group | | auth_group_permissions | | auth_permission | | auth_user | … -
Most efficient way of creating pandas DataFrame from list of Django models
I need to create a DataFrame from a list of Django models and one simple Python object. Say we have the following class and Django model: class User: def __init__(self, name, age, gender, ...): self.name = name self.age = age self.gender = gender ... class Book(models.Model): author = models.CharField() price = models.DecimalField() pages = models.IntegerField() ... Having one User object and a list of Books, I want to make a DataFrame combining data from each book with data of the user: user = User('Molly', 55, 'F') books = [Book('John', 10.99, 245), Book('Jack', 9.99, 154)] would produce: name age gender author price pages 1 Molly 55 F John 10.99 245 2 Molly 55 F Jack 9.99 154 An obvious straightforward solution would be: df = pd.DataFrame([{ 'author': b.author, 'price': b.price, 'pages': b.pages, 'name': user.name, 'age': user.age, 'gender': user.gender } for b in books]) Is there a simpler faster way of doing that? -
Two submit inputs within one form and ajax in Django
This is the third time I ask this question, unfortunately there is no expert who can answer this simple question. Without javascript code the method within view.py works perfectly both for save and calc, two submit for one form. However when I use ajax, it fails (because of e.preventDefault();), here is my code: html <form method="post" id="idForm" name="fmr1" action = "/myproject/save/" enctype="multipart/form-data"> .... <input type="submit" name="save" value="Save"> <input type="submit" name="calc" value="Calculate"> </form> js $("#idForm").submit(function(e) { e.preventDefault(); // avoid to execute the actual submit of the form. var frm = $('#idForm'); $.ajax({ type: frm.attr('method'), url: frm.attr('action'), data: frm.serialize(), success: function (data) { alert(data.mylist) }, error: function (data) { alert("ajax fails") } }); }); views if request.method == 'POST' and 'calc' in request.POST: print("runs calc form") mylist= [5] return JsonResponse({'mylist':mylist}) Question Now the difficulty is in "'calc' in request.POST", so it does not run when I add ajax or id="idForm" to the form. I need "'calc' in request.POST" since I have to run "save" as well. Both will have to run inside one method in views. What can be the reason that javascript (e.preventDefault();) prevents it from running correctly? How to fix it? -
django// 1054, Unknown column 'rank.post_id_id' in 'field list'"
django=2.2.3 mariadb This error occurs after importing model from an existing database with 'inspectdb' and changed field properties. class Post(models.Model): post_id = models.AutoField(primary_key=True) post_name = models.CharField(max_length=255, blank=True, null=True) email = models.CharField(max_length=255, blank=True, null=True) class Rank(models.Model): rank_id = models.AutoField(primary_key=True) rank_type = models.IntegerField(blank=True, null=True) created_at = models.DateTimeField() # post_id = models.IntegerField(blank=True, null=True) post_id = models.ForeignKey(Post, on_delete=models.SET_NULL, blank=True, null=True) Originally, it was # post_id, but I removed "managed = False", changed it to ForeignKey and then "migrate". As far as I know that if the "post_id" in the "Post" model is "primary_key True", it replaces the "id" value with "post_id". But "Django" keeps calling up the "post_id_id". There is no command to refer to post_id_id elsewhere. If you have a solution or something that I'm missing, please give me some advice. -
Django 1.11 to 2.2 => performance div 2
I just upgraded from Django 1.11 to 2.2. I changed nothing in the code except backwards incompatibilities: - changing url to path with route instead of regex argument - adding a few on_delete arguments where I had forgotten Here are my unit tests run in local before and after the migration: before: Ran 496 tests in 62.891s after: Ran 496 tests in 157.244s I have tested with DEBUG=False, same result. I have tested with my CI that runs on an Heroku environment (to be sure it's not related to my local env), same result (2x longer to execute tests). My Django backend consists of an API for a SPA. I'm using Django Rest Framework 3.10.3. When running my SPA in local, I immediately noticed my requests are slower, and unit tests time execution was just a confirmation of the issue. Question Do you have any idea of what's going on here? How would you debug this? -
How to pass arguments to custom template tags from templates of type queryset dict
I have a context of variable say 'a' which is of type queryset and in the queryset there are fields of type dict. So how should I pass field name as an argument to the template tags I tried using a|total: b, a|total a b none of this works for me. @register.filter def total(a, key): total_ = 0 for d in a: if key' in d: total_ += d[key'] return total_ 1. a|total: b 2. a|total a b -
Simulating 1 table inheritance in Django
Considering I have 3 apps in a Django Project (let's say "HR", "Fleet", and "HR-Fleet"). Both "HR" and "Fleet" are standalone apps that can be used on their own (I mean only one or the other, or both but they do not talk to each other). The idea is to create a "bridge-module" (here "HR-Fleet") that extends "HR" and "Fleet" and that depends on both of them. The idea is to add some extra functionalities in that bridge module. If you have a class "Employee" in "HR" and a class "Car" in "Fleet", in the bridge module "HR-Fleet" I would extend the class "Employee" with a foreign key to the "Car" model. The thing is I want to have all fields of "Employee" to be in the same database table. Is it a good practice to do so ? In "HR" App : class Employee(models.Model): class Meta: db_table = 'employee' name = models..... firstname = models..... .... In "Fleet" App : class Car(models.Model): class Meta: db_table = 'car' brand = models...... model = models...... .... In "HR-Fleet" App : class Employee(models.Model) class Meta: db_table = 'employee' company_car = models.ForeignKey(....) .... This would result in extending the "Employee" model ONLY if … -
Why can not get email message (python, gmail, django)?
all. Have a troubles with email sending in django. Have next in my settings.py EMAIL_USE_TLS = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_PASSWORD = 'password' EMAIL_HOST_USER = 'xxx@gmail.com' Try to call function send_mail from django.core.mail: send_mail('Subject here', 'Here is the message.', settings.EMAIL_HOST_USER, ['yyyy@coin-host.net', ], fail_silently=False) Have next output: Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: Subject here From: xxxx@gmail.com To: yyyy@coin-host.net Date: Mon, 23 Sep 2019 09:57:10 -0000 Message-ID: <20190923095710.1383.3314> Here is the message. But I have not any messages in my mail client. Have checked Spam folder too - it's empty. -
First/Previous and Next/Last links for Django paginated query
I've made a filter form using Django, which returns a list of paginated matches. When I initially run the filter, I get the correct number of pages showing. However, when I click on another page number, the page then reverts to that relevant page number for the unfiltered results. For example, I filter the results on 'Bug' and I get all the paginated results for tickets with a type of 'Bug'. The pagination shows the links to the different pages (1, 2, 3, etc.) and also the next and last buttons. However, if I click on '3', the results revert to the unfiltered results, I'm given the results for page 3 of the unfiltered results instead of page 3 of the filtered results, and the total number of pages for the unfiltered results show in the pagination links. Please could anybody help me to understand how to fix the issue and keep the filtered results when navigating through the pagination? all_tickets.html: // filter form code // // Displayed results (unfiltered results displayed when page is first loaded) // <!-- Pagination - only visible if there are multiple pages --> {% if tickets.has_other_pages %} <ul class="pagination center-align"> <!-- Previous/First button - … -
deal with one user model for multiple type of user in django rest framework
I'm trying to build a multiple type user api with django rest framework in my project i have two types of users: -customer who is an individual user -corporates who are companies What i'm trying to achieve is to have two separates users on the admin apnel whith its own viewset at the endpoint but for django corporates and individual user are users so when i display my individual user endpoint in json django render information for customer&corporates but the only one i want in the json is customer information not a both it's same issue for corporates endpoint -
Retrieve values of excel as python dictionary
Sr. No Name 1 a 2 b 3 c Imagine this is my excel file. And To get the header: dic = pandas.read_excel(excelfile).columns convert excel file into dict: readers = pandas.read_excel(csvfile).to_dict() To retrieve values: for reader in readers: reader['Name'] So if I Retrieve values like that, its showing "list indices must be int, not str". How to resolve this issue. -
How to identify group permission on base template
{% if perms.permission.view_permission or perms.permission.view_group %} <li class="nav-item with-sub {% if request.resolver_match.url_name == "group_permission" or request.resolver_match.url_name == "group_user_control" %}show{% endif %}"> <a href="" class="nav-link"><i data-feather="users"></i> <span>User & Permission</span></a> <ul> {% if perms.permission.view_permission %} <li class="{% if request.resolver_match.url_name == "group_user_control" %}active{% endif %}"><a href="{% url 'group_user_control' %}"><i data-feather="users"></i> <span>Users & Permission</span></a></li> {% endif %} {% if perms.permission.view_group %} <li class="{% if request.resolver_match.url_name == "group_permission" %}active{% endif %}"><a href="{% url 'group_permission' %}"><i data-feather="settings"></i> <span> Group & Permission </span></a></li> {% endif %} </ul> </li> {% endif %} Group users will not be able to access this content. However I am giving permission to these groups. It's only work direcly giving permission a user.