Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Forms - Form is not valid but no errors are shown / single submit for different forms and form types
I have a form setup containing three forms: CharField for the front of the index card CharField for the header of the index card back CharField [CKEditorWidget] for the body of the index card back The first issue is that the data that I enter should change the corresponding field from a model inside the database. To analyze the problem I put a print("valid") snippet after if card_change_form.is_valid():, to look whether the change could even happen at all. In fact, the form isn´t even valid. To find out the error I used print(change_card_form.errors) which lead to the error "Name wird bereits genutzt" (german interface) which translates to "Name is already taken", an expection I wrote myself. This is the same thing for all forms (change_card_form.front, change_card_form.back and change_card_form.name name is the same here as header). I found out that my custom clean function uses the old name to look for existing cards with the same name, which leads to an error because the filter finds the card itself. I need a way to search the DB with the variable "new_name" or "new_front" or "new_back" instead of "name"/"front"/"back" from the view function. I checked super().clean() and it only contains the old … -
Using Django Check Framework to detect admin unknown fields?
so imagine I have a models.py class User(models.Model): name = models.CharField(max_length=30) and I used to have a last_name = models.CharField that I have removed. in admin.py @admin.register(User) class UserAdmin(models.Model): fields = ("name", "last_name") When navigating in the admin, I obviously get a FieldError: Unknown field(s) (last_name) specified for User. This error is not picked up by ./manage.py check, which makes me sad. How do I set up the Check Framework so that it can detect such errors? -
Why is django TestCase not creating a test database?
I am writing a Django test inheriting from django.test.TestCase. Everywhere, in the docs, this tutorial and event in this accepted SO accepted answer is stated that when using Django TestCase, a test db will be automatically created. Previously I have worked with DRF APITestCases and all worked well. Here I am using the very standard approach but the setUpTestData class method is using my production db. What do I do wrong and what has to be done so a test db is spawned and used for the test? Please see my code bellow. from django.test import TestCase from agregator.models import AgregatorProduct from django.db.models import signals def sample_product_one(): sample_product_one = { # "id": 1, "name": "testProdOne", "dph": 21, "updated": datetime.now(), "active": True, "updatedinstore": False, "imagechanged": False, "isVirtualProduct": False, } return sample_product_one class TestCreateProdToCategory(TestCase): """ Test for correct creation of records """ @classmethod @factory.django.mute_signals(signals.pre_save, signals.post_save) def setUpTestData(cls): AgregatorProduct.objects.create( **sample_product_one() ) def test_create_prod_to_cat(self): product = AgregatorProduct.objects.get(id=1) self.assertEqual(product.id, 1) -
Django: Groups as User that contains user accounts
I'd like to ask if there exists an established practise/design pattern in Django to solve a common need to use Groups as Users? Example: Your Django application has Organizations/Companies as their users. These Organizations/Companies has in turn their own Employees/Users, (which could be divided into user-groups to control access). Your app typically allows a single user to login and this user is then controlled by which Organization/Company it belongs to, as well as, which user-group it belongs to. To programmatically access a user's organization/company name one ideally should be able to: client=request.user.group or even better: client=request.user.client Meanwhile current Group model in Django intended purpose is to admin user-groups which allows several users client=request.user.groups.values_list('name', flat=True)[0] How do you achieve group-user abilities in Django? I have seen there exist third-party apps, such as django-organizations, but I wanted to try create a minimal version myself. -
python manage.py inspectdb > models.py dont work in existing mongo database
sample_data is the name of the mongo collection. At first I created a model class named sample_data coz i thought it will just read whats already existing in my mongodb but the result was... It creates a new collection named {{MyDjangoAppName}}_sample_data so I search on google "Integrating Django with a legacy database" then tried it to generate the model for me but ahahahaha sad coz It replace my models with the error message and looks like this... i added a picture of my terminal with the error message below. is it about the mongo ObjectId? how can i exclude the objectId here and generate a new id? Is that possible? should i stick on manually creating the models in models.py and rename the collection name of the existing database? what is the right approach for this? -
How to run a script with different parameters by clicking on a HTML button using django
i'm struggling with something that is probably very simple, but hard for a beginner. I didn't find any clear answer to that question on google and stackoverflow so i hope it will help other people if i find a solution. I'm making a website using python and django. My goal is to create a homepage with some inputs and a submit button like that: <div class="wrapper"> <div class="one"> <div class="api-key-title">Api-Key</div> <span class="api-key">Your api key:</span><br> <input type="number"><br> <div class="api-key-title">Secret Api-Key</div> <span class="api-key">Your secret api key:</span><br> <input type="number"><br> <div class="title-action">Buy</div> <span class="price-buy">Price:</span><br> <input type="number"><br> <span class="quantity-buy">Quantity:</span><br> <input type="number"><br> <button class="button-buy">Buy</button> </div> </div> The concept of this small website is to send orders to an API (Binance exchange), to buy/sell crypto-currencies depending of the inputs given by the visitor on the website. For now, i made a simple python script that does one simple order. If i understand how to link them (HTML page and the script) i can easily adapt the script depending of the parameters. Here is the script: from binance.client import Client api_key=("xxx") api_secret=("xxx") client = Client(api_key, api_secret) order = client.order_market_buy( symbol='BUSDUSDT', quantity=xxx, price=xxx) Thank you so much if you can help. I litteraly tried all the solutions on stackoverflow … -
Cannot connect MongoDB to Django
So I was running my Django app really well with SQLite but decided to shift to MongoDB. Apparently, I cannot seem to connect to MongoDB for some reason. Django keeps giving me an error. "TypeError: 'Collection' object is not callable. If you meant to call the 'list_collection_names' method on a 'Database' object it is failing because no such method exists." My settings.py connection: DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'mirror1', 'CLIENT': { 'host': '27017', } } } I haven't used Pymongo or any MongoDB querying in my project before. Just pasted the above settings and am getting this error. All help would be appreciated. Thank you I have MongoDB version 4.4 installed along with MongoDB compass -
How to pass url params to Django model filter with mulitiple values in url
I am trying to pass url param values to Django model filter here is my sample url . https://www.example.com/api/organization?id=5&status=0,1&class=4,5 Here is my code. def set_if_not_none(self, mapping, key, value): if value is not None: mapping[key] = value def get_org_list(self, status, id, format=None): filter_params = {} self.set_if_not_none(filter_params, "is_active", status) self.set_if_not_none(filter_params, "org_id", id) queryset = Organization.objects.filter(**filter_params).order_by("org_name") Error : ValueError: Field 'is_active' expected a number but got '0,1'. How to fix this -
Creating a new django project using code from a previous project
I am trying to create a duplicate of an original django project, but with a different secret key, database, etc. Currently, I am just copying and pasting the original project, and then deleting the manage.py file in the new file. After that, I start a new project in the file. Then, I copy the settings as well as the urls from the original project into the new project. Since I want to keep all of my pip installments, I am not going to create a new virtual env, but just copy and paste the original one from the old project(hence creating a new env with the pip installments). I am not sure if this method is okay when creating a new version of the original project. My project seems to work fine after duplicating it, but I am a little worried that there might be a security issue when deploying it, or some part of the new project may not work properly. I hope you guys could tell me if this method is okay, and if there are any better methods. Since I am a beginner, if possible, I would like to stick to this method if it is okay, … -
AWS Elastic Beanstalk requires SQLite 3.8.3 or higher for Django Application
I am trying to upload a Django application on AWS Elastic Beanstalk. I used the following tutorial: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html But I end up with the following error message after login attempt on /admin NotSupportedError at /admin/login/ deterministic=True requires SQLite 3.8.3 or higher Request Method: POST Request URL: http://django-env50.eba-3ipauf3e.us-west-2.elasticbeanstalk.com/admin/login/?next=/admin/ Django Version: 3.1.7 Exception Type: NotSupportedError Exception Value: deterministic=True requires SQLite 3.8.3 or higher Exception Location: /var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py, line 215, in get_new_connection Python Executable: /var/app/venv/staging-LQM1lest/bin/python Python Version: 3.8.5 Python Path: ['/var/app/current', '/var/app/venv/staging-LQM1lest/bin', '/var/app/venv/staging-LQM1lest/bin', '/usr/lib64/python38.zip', '/usr/lib64/python3.8', '/usr/lib64/python3.8/lib-dynload', '/var/app/venv/staging-LQM1lest/lib64/python3.8/site-packages', '/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages'] Server time: Mon, 29 Mar 2021 16:23:05 +0000 Here is the Pipfile: [[source]] url = "https://pypi.org/simple" verify_ssl = true name = "pypi" [packages] asgiref = "==3.3.1" pytz = "==2021.1" sqlparse = "==0.4.1" Django = "==3.1.7" [dev-packages] [requires] python_version = "3.8" Thank you for your help. -
Show profile to the owner only and not to other users in view
I want to show this view to the owner of the object not other logged in userse. Is this possible with the UserPasseTestMixin i class view? And hos should i do this? this is not login related so please dont write about login related information thx thx class UserDetailView(LoginRequiredMixin, UserPassesTestMixin, DetailView): model = User slug_field = "pk" slug_url_kwarg = "pk" def get(self, request, *args, **kwargs): self.object = self.get_object() context = self.get_context_data(object=self.object) return self.render_to_response(context)``` -
Can you please check this and tell me why "NoReverseMatch " error for show view is coming?
https://gist.github.com/Hemanth99999/dbaafde569b78883986b32b64a5c22bd I am sharing the gist of my project that is getting me "NoReverseMatch" error -
Django get model all field after group by
I have a model; class Location(models.Model): g_id = models.ForeignKey(User, on_delete=models.CASCADE, related_name="guard_id") corX = models.IntegerField() corY = models.IntegerField() date = models.DateTimeField() def __int__(self): return self.map_id ı want to get the newest record per foreign key using this query; query = Location.objects.values('g_id').annotate(timestamp=Max('date')) This my query result. <QuerySet [{'g_id': 1, 'timestamp': datetime.datetime(2021, 3, 29, 8, 57, tzinfo=<UTC>)}, {'g_id': 2, 'timestamp': datetime.datetime(2021, 3, 29, 8, 55, 50, tzinfo=<UTC>)}]> How to get corX, corY values with groupping data? -
NoReverseMatch, but it exist and was found
urls.py url(r'^hr/checktask/(?P<pk>\d+[-]\w)/$', core_views.CheckTask, name='checktask_hr'), url(r'^admin/checktask/(?P<pk>\d+[-]\w)/$', core_views.CheckTask, name='checktask_admin'), url(r'^finance/checktask/(?P<pk>\d+[-]\w)/$', core_views.CheckTask, name='checktask_finance'), url(r'^manager/checktask/(?P<pk>\d+[-]\w)/$', core_views.CheckTask, name='checktask_manager'), Essentially, I have 4 separate urls, but they all call the same function. Each has a different name. In my code, depending on my url, I will call one of those patterns pk = 42387790148475610; callingView = request.META.get('PATH_INFO').split("/")[1] return HttpResponseRedirect(reverse('checktask_' + callingView, kwargs={'pk': pk})) But somehow, I get a NoReverseMatch error, despite it actually pointing to the right url pattern (hr in this case) Reverse for 'checktask_hr' with keyword arguments '{'pk': '42387790148475610'}' not found. 1 pattern(s) tried: ['hr/checktask/(?P<pk>\\d+[-]\\w)/$'] Where am I going wrong? -
Celery workers fail to boot after resizing DO celery cluster
This morning we have resized a celery cluster on DO because of an increasing memory usage. [2021-03-30 09:38:05,741: CRITICAL/MainProcess] Unrecoverable error: OperationalError('this user has no permissions to access one of the channels used as arguments')Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/kombu/connection.py", line 454, in _reraise_as_library_errors yield File "/usr/local/lib/python3.8/site-packages/kombu/connection.py", line 533, in _ensured return fun(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/kombu/messaging.py", line 200, in _publish return channel.basic_publish( File "/usr/local/lib/python3.8/site-packages/kombu/transport/virtual/base.py", line 604, in basic_publish return self.typeof(exchange).deliver( File "/usr/local/lib/python3.8/site-packages/kombu/transport/virtual/exchange.py", line 150, in deliver self.channel._put_fanout( File "/usr/local/lib/python3.8/site-packages/kombu/transport/redis.py", line 794, in _put_fanout client.publish( File "/usr/local/lib/python3.8/site-packages/redis/client.py", line 3098, in publish return self.execute_command('PUBLISH', channel, message) File "/usr/local/lib/python3.8/site-packages/redis/client.py", line 901, in execute_command return self.parse_response(conn, command_name, **options) File "/usr/local/lib/python3.8/site-packages/redis/client.py", line 915, in parse_response response = connection.read_response() File "/usr/local/lib/python3.8/site-packages/redis/connection.py", line 756, in read_response raise responseredis.exceptions.NoPermissionError: this user has no permissions to access one of the channels used as arguments During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/celery/worker/worker.py", line 208, in start self.blueprint.start(self) File "/usr/local/lib/python3.8/site-packages/celery/bootsteps.py", line 119, in start step.start(parent) File "/usr/local/lib/python3.8/site-packages/celery/bootsteps.py", line 369, in start return self.obj.start() File "/usr/local/lib/python3.8/site-packages/celery/worker/consumer/consumer.py", line 318, in start blueprint.start(self) File "/usr/local/lib/python3.8/site-packages/celery/bootsteps.py", line 119, in start step.start(parent) File "/usr/local/lib/python3.8/site-packages/celery/worker/consumer/mingle.py", line 40, in start self.sync(c) File "/usr/local/lib/python3.8/site-packages/celery/worker/consumer/mingle.py", line 44, in sync replies … -
Django SOAP client
I need to implement a simple SOAP server for an external company to send me notifications. They sent me a WSDL file. I started by trying to re-implement this file by writing the same models using spyne. This is a tedious work. Since I cannot define my own models (wsdl provided externally), is there a better way to do this ? I only have a couple RPC methods to implement. Isn't it a way to use the WSDL file to parse a django response, extract what I need (method call and args) and build an appropriate response to their requests ? -
How to show M2M fields with CreateView
I'm trying show the score CharField next to the People Name to allow for the entry of the score for each People when saving the Game. But currently the only thing that is showing is the People name's with no where to enter & save the score. How can I show the score CharField with the People name? People Model: class People(models.Model): name = models.CharField(verbose_name="Name", max_length=250) def __str__(self): return self.name Game Model: class Game(models.Model): title = models.CharField(verbose_name="Title", max_length=100) details = models.TextField(verbose_name="Details/Description", blank=False) people = models.ManyToManyField( People, through='PeopleGame', related_name='games' ) People Game Model: class PeopleGame(models.Model): game = models.ForeignKey(Game, on_delete=models.CASCADE) person = models.ForeignKey(People, on_delete=models.CASCADE) score = models.CharField(max_length=4) def __str__(self): return f"Game: {self.game.title}, Person: {self.person}, Score: {self.score}" Game Create View: class GameCreateview(CreateView): model = Game fields = ['name', 'details', 'people'] success_url = 'home/game/game_details.html' -
how in Django sending a letter by date
I'm new to django and maybe this question is stupid, so please don't minus, but I don't know where else to ask it. Is it possible in Django to set up sending a letter to the mail at a specific time, and how can this be implemented? -
Correct way to copy column value from primary table to another second and third model in Django
I want to copy username of the Django auth model to each level of the tables below. I tried ForeignKey, but what is the correct way to just copy a username to second or third level table below? Is it safe to have such two foreign keys in this case? Django User: `username` | |-> Order #copy username here | |-> Tracking #copy username here from django.db import models from django.contrib.auth.models import User class Order(models.Model): primary_user = models.ForeignKey(User, to_field='username', on_delete=models.CASCADE) department = models.CharField(max_length=100) Order_number = models.BigAutoField(primary_key=True, null=False) objects = models.Manager() class Tracking(models.Model): primary_user = models.ForeignKey(User, to_field='username', on_delete=models.CASCADE) Order_number_copied = models.ForeignKey(Order, to_field='Order_number', on_delete=models.CASCADE) comment = models.CharField(max_length=100) objects = models.Manager() -
django home page path not found
enter image description heredjango stopped showing me the admin page so i used "make migrations" it worked now it won't show me a "hello world" page views.py from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("hello world") urls.py from django.urls import path from . import views urlpatterns = [ path("",views.index,name="home"), ] urls.py for the app from django.contrib import admin from django.urls import path,include urlpatterns = [ path("products/",include('products.urls')), path('admin/', admin.site.urls), ] enter image description here -
How to solve MissingRate Error in Django?
I want to convert currencies in my Django app. I created a model Customer. In customer model, there are two fields for that credit_limit and currency_choice. I am using django-money for conversion. But I get an error: MissingRate at /customer Rate EUR -> USD does not exist How can I solve it? views.py from djmoney.money import Money from djmoney.contrib.exchange.models import convert_money def customer(request): form_class = NewCustomerForm current_user = request.user userP = UserProfile.objects.get_or_create(username=current_user) company = userP[0].company if request.method == 'POST': form = NewCustomerForm(request.POST) if form.is_valid(): newCustomer = form.save() newCustomer.company = company selected_currency = newCustomer.currency_choice selected_limit = newCustomer.credit_limit value = Money(selected_limit, selected_currency) converted = convert_money(value, 'USD') print(converted) newCustomer.save() return redirect('user:customer_list') else: form = form_class() return render(request, 'customer.html', {'form': form}) models.py class Customer(models.Model): ... CURRENCIES = [ ('USD', 'USD'), ('EUR', 'EUR'), ('GBP', 'GBP'), ] ... credit_limit = models.FloatField(default=0) currency_choice = models.TextField(max_length=50, default='Select', choices=CURRENCIES) settings.py ... INSTALLED_APPS = [ ..., 'djmoney', ... ] ... EXCHANGE_BACKEND = 'djmoney.contrib.exchange.backends.FixerBackend' CURRENCIES = ('USD', 'EUR', 'GBP') OPEN_EXCHANGE_RATES_URL = 'https://openexchangerates.org/api/historical/2017-01-01.json?symbols=EUR,NOK,SEK,CZK' FIXER_URL = 'http://data.fixer.io/api/2013-12-24?symbols=EUR,NOK,SEK,CZK' traceback Environment: Request Method: POST Request URL: http://127.0.0.1:8000/customer Django Version: 3.1.4 Python Version: 3.8.8 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'register', 'customer', 'financial_analysis', 'ocr', 'core', 'approvals', 'crispy_forms', 'ckeditor', 'rest_framework', 'requests', 'ckeditor_uploader', 'django_filters', 'activity_log', … -
Django: '<' not supported between instances of 'User' and 'User'
When I do: qs1 = User.objects.filter(first_name__icontains=search).filter(is_superuser=False) qs2 = User.objects.filter(last_name__icontains=search).filter(is_superuser=False) users = sorted(set(chain(qs1, qs2))) I get this error: '<' not supported between instances of 'User' and 'User' -
redirect to a different model in django
in my project after updating and submitting the File, I want to redirect to associated object in Content how I could do it? If I want to use def get_absolute_url in File model, how I can use it to redirect to 'content.detail' which is defined in urls.py I tried this: def get_absolute_url(self): return reverse('content.detail', args=[str(self.id)]) and it returns the content object that has same id as File, for example if we have a File id=5 that is associated to content by id=74, by get_absolute_url function, it returns a content id=5, however I want it to return content id=74. models.py class File(models.Model): history = AuditlogHistoryField() extension = models.CharField(max_length=20, default='html') base64encoded = models.BooleanField(default=False) compressed = models.BooleanField(default=False) data = models.TextField() class Content(models.Model): history = AuditlogHistoryField() name = models.CharField(max_length=120, unique=True) sorry_content_file = models.ForeignKey( File, on_delete=models.CASCADE, null=False, related_name='first_file') busy_content_file = models.ForeignKey( File, on_delete=models.CASCADE, null=False, related_name='second_file') emergency_content_file = models.ForeignKey( File, on_delete=models.CASCADE, null=False, related_name='last_file') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) view.py class FilesUpdateView(generic.UpdateView): model = File fields = ['data'] file_form.html {% block content %} <form method="POST" class="user"> <div class="row"> <div class="col-lg-8"> <div class="card shadow mb-4"> <div class="card-header py-3"> <h6 class="m-0 font-weight-bold text-primary">{% trans 'Details' %}</h6> </div> <div class="card-body"> {% csrf_token %} {% for field in form.visible_fields %} … -
why am I getting "TypeError" while creating super user in Django?
I am woking on a project where I need to have Django custom model. Based on the documents available I came up with the below code base: from django.db import models from django.contrib.auth.base_user import BaseUserManager from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from django.utils.translation import gettext_lazy as _ class AccountManager(BaseUserManager): def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(email, password, **extra_fields) def create_user(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) if not email: raise ValueError(_('Enter the email before proceeding')) email = self.normalize_email(email) user = self.model(email=email, password=password, **extra_fields) user.set_password(password) user.save() return user class NewEmployeeProfile(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) employee_code = models.IntegerField() contact = models.CharField(max_length=10) objects = AccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name', 'contact'] def __str__(self): return str(self.email) I migrated the model without any hiccups. However, when I am trying to create super user, I am getting below error: Traceback (most recent call last): File ".\manage.py", line 22, in <module> main() File ".\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Admin\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Admin\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) … -
Show only the user profile of the logged in user to the logged in user
I hope somebody can help me with this. When a user logs in they se their user profile page, but if the user guesses another users profile URL they can view other peoples profiles I have tryed to use the get_object_or_404 method to restrict the access but cant tweak for user with genreric detail view. Is it possible to user get_object or do you recommend another approach? My user Class class UserDetailView(LoginRequiredMixin, DetailView): model = User slug_field = "pk" slug_url_kwarg = "pk" Get object or 404 method def user_detail(request, user_id): user = get_object_or_404(User, user_id=user_id, is_active=True) return render (request, 'users/user_detail_2.html',{'users':users})