Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Allauth Account Management email addresses not listed in account_email view
I am working on my first django project with allauth and working through customising the allauth templates with my own styles. I have linked the user to the email.html template so that they can view the email addresses associated with their account. When I check this out on my deployed site there are no email addresses shown where it should list them. This is despite having checked 'verified' from admin panel. I can add a new email and it successfully shows in the admin panel and resend verification emails that successfully arrive in my mail box. Is there something I need to do in the settings somewhere to get the email set to show? -
Processing Django Migrations
We have a multiple database Django project that uses database routers. For some reason when we run a migration the reference to the migration end up in the django_migrations table but no actual migrations are actually run - that is - there is no change in target database. How can you manually force a migration to take effect? -
Django migration not applied to the DB
I had an Django2.2.3 app, it was working fine. But I had to chane the name of a field in a table, and add another field. Then I ran ./manage.py makemigrations && ./manage.py migrate. Besides the terminal prompt: Running migrations: No migrations to apply. No error is throwed. But then when I go to the MySQLWorkbench to check the database, it is exactly as I didn't make any change. I tried deleting the migrations and making again, the process ends with no errors but the database don't change. I create another empty database, change the name on settings.py and make migrations and migrate again, and it worked, but when I put the old database name on the settings, it just did not work. Can someone explain this behavior for me? There is any kind of cache for these information migrations or something? I realy want to know why this is not winrkig as I espect. -
how can I add a post as an admin?
I have a blog app in my project with posts. I am able to create posts if I go to the admin in the link, but I want to use CRUD. so if my user is a super user another option will appear to add posts. however I am not able to because it keeps saying that it cannot find the template.` I'm not sure what to add in the models and views. I've tried many things but it's still not working. would appreciate any help! here is my code: from django.urls import path from . import views urlpatterns = [ path('', views.posts, name='posts'), path('posts/<slug:slug>/', views.PostDetail, name='post_detail'), # path('add_post/', views.add_post, name='add_post'), ] views: def posts(request): """ A view to show all posts, including sorting """ posts = Post.objects.all() sort = None direction = None if request.GET: if 'sort' in request.GET: sortkey = request.GET['sort'] sort = sortkey if sortkey == 'title': sortkey = 'lower_title' posts = posts.annotate(lower_title=Lower('title')) if 'direction' in request.GET: direction = request.GET['direction'] if direction == 'desc': sortkey = f'-{sortkey}' posts = posts.order_by(sortkey) current_sorting = f'{sort}_{direction}' context = { 'posts': posts, 'current_sorting': current_sorting, } return render(request, 'blog/posts.html', context) -
How can I display my updated output in browser django
Hello guys hope you are fine... I want to ask something from you I really need help from you because I am stuck in this problem... I deployed my (django) app in heroku and in that app I used apscheduler which works fine (which basically get historical weather data from api and then train my model on that data and gives me predictions ) and I shows that new prediction values on console but not in browser which I wants to every time when my scheduler runs and got new prediction values then those new values should be shown on my browser instead of old values. How can I achieve this task?? Thanks in advance.... -
Django: Separate queryset into two sets
I have a Book class and a Wish class. Users can search for a book title and see a list of all users who have this book in their (available for trade) Book list. I want to separate this list into two lists of "perfect matches" and "possible matches". Perfect matches occur when another user has the book you are searching for in their Book list and your Book list contains at least one book from their Wish list. Possible matches are the rest of the users who have this book in their Book list. Here is the code I have so far: results = Book.objects.filter(Q(name__icontains=query)).distinct() books = Book.objects.filter(user=request.user) for result in results: wishes = Wish.objects.filter(user=result.user) matches = books.filter(name__in=wishes.values_list('name')) if not matches: print("Not a perfect match.") else: print("This is a perfect match!") How can I separate "results" into two separate querysets/lists of perfect matches and possible matches? -
Querying jsonb fields in PostgreSQL using Django: IN vs. CONTAINS
When Django's ORM translates a JSONB query using CONTAINS into SQL it uses the ->> operator which is working fine. For example, something like: "metadata__my_field_name__icontains": "1234" runs as: ...WHERE UPPER(("table"."metadata" ->> my_field_name)::text) LIKE UPPER(%9740253%)... which works great. However, when I try to use the IN operator and a list of values: "metadata__my_field_name__in": my_list the SQL generated uses the JSON, as opposed to JSONB operator like this: ..."table"."metadata" -> gbif_taxon) IN ('9405810', '2480631', ... While it runs, it does not return the expected values (empty set). By contrast, if I manually run the same query using the JSONB operator, ->>, the expected values are returned. The metadata field in this case is generated in a view using the jsonb_object_agg function (unmanaged by Django) and is defined in Django code as a JSONField() from django.contrib.postgres.fields. Is there a way to force Django to use the JSONB operator? -
Failed to fetch due to cors
I cant seem to make this alert in the console dissappear: Access to fetch at 'https://streamlabs.com/api/v1.0/user' from origin [mywebsite] has been blocked by CORS policy: Request header field access_token is not allowed by Access-Control-Allow-Headers in preflight response. I looked into already answered questions, but couldnt make it work. I have this in my settings.py: MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] INSTALLED_APPS = [ ... 'corsheaders', ... ] ALLOWED_HOSTS = ['*'] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = False Also I tried removing 'django.middleware.clickjacking.XFrameOptionsMiddleware' to check if this was the problem, but still didn't work. Any ideas? This is my fetch: <script> window.onload = function() { fetch("https://streamlabs.com/api/v1.0/user", { method: "GET", headers: { 'access_token': '{{request.user.streamlabs_access_token}}', } }) .then(response => { console.log(response); }) .catch(err => { console.error(err); }); } </script> -
Django: Testing LoginView throwing AssertionError
Quesiton I'm building a testing suite for my login process and immediately ran into a hiccup. I believe the issue is that LoginView is a 'class' while the code is testing it as a function. What is the proper way to assert that the URL resolved to the LoginView? urls.py from . import views from users.views import * from django.urls import path from django.contrib.auth.views import LoginView, LogoutView from users.forms import LoginForm urlpatterns = [ path('', views.user_home_view, name='user_home'), path('sign_up', views.SignUpView.as_view()), path('login', LoginView.as_view(authentication_form=LoginForm), name='login'), path('logout', LogoutView.as_view(), name='logout') ] tests.py from django.test import SimpleTestCase from django.urls import reverse, resolve from django.contrib.auth.views import LoginView, LogoutView from users.forms import LoginForm from users.views import * # Create your tests here. class UrlTestCase(SimpleTestCase): def test_login_url_resolved(self): url = reverse('login') self.assertEquals(resolve(url).func, LoginView) Testing Results (./manage.py test) AssertionError: <function LoginView at 0x7f970ca05320> != <class 'django.contrib.auth.views.LoginView'> -
Django update part of page - Class based View
I'm having the following doubt: my app has a html with a navbar with all menu items and when you click in one of them, it refresh all page. This was made with {% extend %} and {% block %} for no-repeat code. In the back, I use default Django Views (CreateView, UpdateView, List..) with their basic function use.. get_context_data().. post().. Now, I need to update the page when you click any menu button, but ONLY should change de {% block %} content. Is not nice updating also menu and all page everytime you navegate. I tried using Ajax requesting the endpoint of any view and changing the DOM elements. It works in the front.. but when I submit, the backend obviosly still "thinking" in the previous class view and validate fields that NOT exist.. For example.. you are in Book html, creating one of them, then you click on Create Person.. html change.. but when submit, it still ask for Book Title.. Is there any nice way to do this?? I hope it understood! Thank u in advance! -
How to provide different sets of data to different users in django?
I'm a newbie to the django framework and trying to make a watchlist for stocks. I've already made the crux of the webapp, where-in, a user can search for a quote and add it to their watchlist, along with relevant data about that quote. What I want to do now is, to save the separate watchlists that different users are creating (after creating an account on my site) and upon logging in to my site, they can view their personalized watchlist and edit it. I'm using a model for storing the data for the watchlist quotes and looking for a way to provide the different personalized watchlist data depending upon the logged in user. Can anyone give me a lead on how to employ the logic for this? Do I need to use two data bases - one for the data of the users and the other one for storing the respective user watchlists? If yes, how do I connect everything? -
TypeError: 'Post' object is not callable
I'm new to Django and I keep getting this error on my project. I have tried to fix it by examining similar problems, but I keep struggling to find the problem. Here is the code for models.py file. class Post(models.Model): publisher = models.ForeignKey(User, related_name='posts_published', on_delete=models.CASCADE) category = models.ForeignKey(Category, related_name='posts', on_delete=models.CASCADE) subject = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True) overview = models.TextField() published = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-published'] def __str__(self): return self.subject class Module(models.Model): post = models.ForeignKey(Post, related_name='modules', on_delete=models.CASCADE) subject = models.CharField(max_length=200) add_desc = models.TextField(blank=True) order = OrderField(blank=True, for_fields=['post']) class Meta: ordering = ['order'] def __str__(self): return f'{self.order}. {self.subject}' A snippet from views.py class PostUpdateViewModel(TemplateResponseMixin, View): template_name = 'publications/manage/module/formset.html' post = None def get_formset(self, data=None): return PostsModuleFields(instance=self.post, data=data) def dispatch(self, request, pk): self.post = get_object_or_404(Post, id=pk, publisher=request.user) return super().dispatch(request, pk) def get(self, request, *args, **kwargs): formset = self.get_formset() return self.render_to_response({'post': self.post, 'formset': formset}) def post(self, request, *args, **kwargs): formset = self.get_formset(data=request.POST) if formset.is_valid(): formset.save() return redirect('posts_list_merge') return self.render_to_response({'post': self.post, 'formset': formset}) My formset.html {% extends "home.html" %} {% block title %} Edit "{{ post.subject }}" {% endblock %} {% block content %} <h1>Edit "{{ post.subject }}"</h1> <div class="module"> <h2>Course modules</h2> <form method="post"> {{ formset }} {{ formset.management_form }} {% csrf_token … -
Django factory boy mock model method in factory
My model's save method is calling an api after saving. To test my application I am using DjangoModelFactory to generate objects for testing. However, the api still being called. class MyClass(models.Model): def save(self, *args, **kwargs): super().save(*args, **kwargs) self.call_api() I have tried mocking the method but it is not working #... from .models import MyModel @pytest.mark.django_db @patch("MyModel.call_api") class MyModelFactory(factory.django.DjangoModelFactory, factory.base.BaseFactory): class Meta: model = MyModelFactory My Question is, how can I use mock methods when I use it with factories? -
How do I add context/an additional dictionary to Django DayArchiveView
I have a DayArchiveView where I pass in a queryset of booking slots. I would like to be able to pass in some context too, like more data. Specifically, I would like to pass the earliest time, latest time and a few other small calculations. My view is currently this. class BookingArchiveView(DayArchiveView): queryset = BookingSlot.objects.filter(location__club__id=1) date_field = "start_time" ordering = ['location'] #I would like to pass in another object like so context["earliest_time"]=BookingSlot.objects.filter(location__club__id=1).annotate(Min('start_time')) So I would like to be able to pass in some aggregate functions and calculations that I could render in html. Right now, the HTML only has access to my queryset. -
How to create this type of relationship using Django Models
After seeing a model that I should implement in Django, I was a little confused and I will explain what I tried to do and what was sent to me. The following image is the relationship I must implement in Django https://i.stack.imgur.com/FOYNq.png What I tried to do was: class Contact(models.Model): person = models.OneToOneField(Person) class Person(models.Model): contact = models.ForeignKey(Contact) However this does not work, both classes are in the same file. I read the documentation for ManyToManyField, OneToOneField and ForeignKey, but what makes me confused is the model wanting the variable in both classes, in previous models that I saw there was this same relationship, but the variable only existed in one of the classes. What is the correct way to implement this? -
Python - Generate N colors names
I want to generate N colors (from the darkest to the brightest). The colors should NOT BE RGB, But they should be represent as names ("black","navy","lightgreen") e.g - colors that can be drawn at HTML pages. I try to find a solution but I find only RGB generators. Thank you very much, Amit. -
How to get History (Product List) from orders that user has purchased in django
I have a model Order which has a ManyToManyField order_entries class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) order_entries = models.ManyToManyField(OrderEntries, blank=True) ... I have another model OrderEntries class OrderEntries(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField() Now, I have to get history of purchased products. What is the efficient way to get all those products? Any help will be highly appreciated -
type object 'ViewSet' has no attribute 'action'
I generate this little question in case some developer finds this problem in the current versions of djangorestframework that generates a conflict with the 'action' attribute in my case when overriding the 'get_authenticators' method after doing an analysis I found that it can be solve this way before def get_authenticators(self): print(self.action) Show error "has no attribute" replace self.action with self.action_map['get'] my current version is djangorestframework==3.12.0 -
django model class returns different values on different queries
i have a model called profile with a field for balance which is an integer field, and another model class called task with a foreign key to profile, when I run profile.balance (with the correct pk) it returns a value of 0, but when i run task.profile.balance i get 400, but when i run profile == task.profile it returns True, the foreign key is definitely the right model instance but the field values don't add up any help would be greatly appreciated -
How to have a child key form view in foreign key detail view
I am having a lot of trouble finding this answer as I don't know how to ask it properly. I have found a solution to do something similar to what I want. https://docs.djangoproject.com/en/1.11/topics/class-based-views/mixins/#an-alternative-better-solution But it seams to fail to work. It loads page correctly, and redirects correctly. But it does not populate the database with child entry for the main foreign key. Any help would be appreciated. class QuizDisplayView(DetailView): model = Quiz context_object_name = 'quiz' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = Q_And_A_Form() return context class QuizQuestionView(SingleObjectMixin, FormView): template_name = 'Quizer/quiz_detail.html' form_class = Q_And_A_Form model = Quiz def post(self, request, *args, **kwargs): #if not request.user.is_authenticated: #return HttpResponseForbidden() self.object = self.get_object() return super(QuizQuestionView, self).post(request, *args, **kwargs) def get_success_url(self): return reverse('quizer:quizDetail', kwargs={'pk': self.object.pk}) class QuizDetailView(View): def get(self, request, *args, **kwargs): view = QuizDisplayView.as_view() return view(request, *args, **kwargs) def post(self, request, *args, **kwargs): view = QuizQuestionView.as_view() return view(request, *args, **kwargs) -
How to server favicon.ico with Django and Whitenoise
I use whitenoise for static files and it works fine. But how can I serve the /favicon.ico file? There is a setting called WHITENOISE_ROOT, but I don't understand how to use it. I would like to keep my nginx config simple and serve all files via gunicorn -
The view polls.views.vote didn't return an HttpResponse object. It returned None instead
Studied the tutorial up to the seventh part. Everything was fine until I decided to launch my application. After launch, I added a multiple choice question. The error occurs after I select one of the answers to the question. A long search for an answer led nowhere. Please help. I get this error: ValueError at /polls/1/vote/ The view polls.views.vote didn't return an HttpResponse object. It returned None instead. Request Method: POST Request URL: http://127.0.0.1:8000/polls/1/vote/ Django Version: 4.0.dev20210118085850 Exception Type: ValueError Exception Value: The view polls.views.vote didn't return an HttpResponse object. It returned None instead. Exception Location: c:\users\mrand\django\django\core\handlers\base.py, line 309, in check_response Python Executable: C:\Users\mrand\Anaconda3\envs\mysite\python.exe Python Version: 3.8.6 Python Path: ['C:\\Users\\mrand\\mysite', 'C:\\Users\\mrand\\Anaconda3\\envs\\mysite\\python38.zip', 'C:\\Users\\mrand\\Anaconda3\\envs\\mysite\\DLLs', 'C:\\Users\\mrand\\Anaconda3\\envs\\mysite\\lib', 'C:\\Users\\mrand\\Anaconda3\\envs\\mysite', 'C:\\Users\\mrand\\Anaconda3\\envs\\mysite\\lib\\site-packages', 'c:\\users\\mrand\\django', 'C:\\Users\\mrand\\Anaconda3\\envs\\mysite\\lib\\site-packages\\win32', 'C:\\Users\\mrand\\Anaconda3\\envs\\mysite\\lib\\site-packages\\win32\\lib', 'C:\\Users\\mrand\\Anaconda3\\envs\\mysite\\lib\\site-packages\\Pythonwin'] Server time: Wed, 27 Jan 2021 22:41:24 +0300 Traceback: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/polls/1/vote/ Django Version: 4.0.dev20210118085850 Python Version: 3.8.6 Installed Applications: ['polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "c:\users\mrand\django\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "c:\users\mrand\django\django\core\handlers\base.py", line 188, in _get_response self.check_response(response, callback) File "c:\users\mrand\django\django\core\handlers\base.py", line 309, in check_response raise ValueError( Exception Type: ValueError at /polls/1/vote/ Exception Value: The view polls.views.vote didn't … -
how to call property method from model class to html in django
Im making a django app, and its basically an admin site, i have an app called calculator, inisde it i have 3 models Transaction, FamilyGroup and FamilyMember, each model has some property methods for calculation purposes. here are the models for more clearness : class Transaction(models.Model): chp_reference = models.CharField(max_length=50, unique=True) rent_effective_date = models.DateField(null=True, blank=True) income_period = models.CharField(max_length=11) property_market_rent = models.DecimalField(max_digits=7) @property def ftb_combined(self): ftb_combined = 0 for family_group in self.familygroup_set.all(): ftb_combined += family_group.ftb_combined return ftb_combined class FamilyGroup(models.Model): name = models.CharField(max_length=10) transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE) last_rent = models.DecimalField(max_digits=7) @property def additional_child_combined(self): return (self.number_of_additional_children or 0) * self.maintenance_rate_additional_child class FamilyMember(models.Model): transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE) family_group = models.ForeignKey(FamilyGroup, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=100, null=True, blank=True) date_of_birth = models.DateField(null=True, blank=True) income = models.DecimalField(max_digits=6) @property def weekly_income(self): if self.transaction.income_period == 'Weekly': return self.income return (self.income or 0) / 2 this is how my models are connected, now i made a method in views.py as below: def transaction_print(request, transaction_id): transaction = Transaction.objects.get(id=transaction_id) return render(request, 'report.html', {'transaction':transaction}) I want to make a report in report.html, 1 report for each transaction, and the transaction can have many FamilyGroups and FamilyMember, and will include almost all the data from the models and the property methods inside it. here … -
How to override row size RichField Django CKEditor
I am trying to override the default RichField row size from 10 to 5 but it's not working. Here is my implementation # models.py class Comment(models.Model): """Model definition for Comment.""" content = RichTextField(_('Content'), blank=True, null=True) # forms.py class CommentForm(forms.ModelForm): """Form definition for Comment.""" class Meta: """Meta definition for Commentform.""" model = Comment fields = ('content',) widgets = { 'content': forms.Textarea(attrs={'rows': 5}) } Default Richfield row size is still being used. Any help to solve this is highly appreciated. Thanks in advance. -
How do I call a custom manage.py command from code
I am trying to simulate the progression of match , whose data I receive as an XML file, in order to progress the match I call a manage.py command python3 manage.py db_schedule --filename=./test_data/replay.xml I would like to automate this call from a python code. I tried using call_command(), but get the error "no such command as db_schedule"