Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Embed google review in Django website?
I was going through the Google Cloud Platform Console to find out how I could embed a Google review on my Django website. I found the Google Places API to be the most relevant (not quite sure), but then I got lost with all the details, pricing, and different tiers. My case is actually quite simple. I just want to display the total number of stars a specific place has. Is there a free way to get that, which I didn't understand? -
Portable windows app built with electron-builder takes too long to start up
I have used electron-builder to package my React + Django application into a single executable file. When I build the app, the resulting dist folder contains: -- dist (folder generated after building the app with electron) | |- MyApp0.0.1.exe (portable exe file) | |- win-unpacked | | | |-MyApp.exe | |-multiple_folders (dependencies of the MyApp.exe) | |-multiple_files (dependencies of the MyApp.exe) The problem is the following: When runnning the MyApp.exe inside the win-unpacked folder, and as long as the dependency files/folders are at the same level, the app works perfectly fine and takes less than a second to startup and display. It even asks for admin password, as in the package.json config it is specified to build it with "requestedExecutionLevel": "highestAvailable". When running the MyApp0.0.1.exe which is supposed to be the portable, standalone .exe file for the application, although it does run perfectly fine, it takes up to 6 minutes to start-up and display the app. I have tried skimming down the project as much as possible in terms of the node_modules that I need, removing large data files not needed, ... I am clueless as to why this is happening. I am not a web-dev expert in any way … -
Custom Admin Site in Django
I have problem to change title_header, site_header, index_title in custom admin site. My admin.py: from reviews.models import Movie, MovieCasts, Review, Actor class CritiflixAdminSite(AdminSite): title_header = 'Aplikacja administracyjna Critiflix' site_header = 'Aplikacja administracyjna Critiflix' index_title = 'Administracja witryną Critiflix' movie_admin_site = CritiflixAdminSite(name='critiflix') movie_admin_site.register(Movie) movie_admin_site.register(MovieCasts) movie_admin_site.register(Review) movie_admin_site.register(Actor) My urls.py: from django.urls import include, path from . import views urlpatterns = [ path('admin/', movie_admin_site.urls), path('movies/', views.movie_list, name = 'movie_list'), path('movies/<int:pk>', views.movie_detail, name = 'movie_detail'), path('', views.base, name = 'base') ] When i run manage.py nothing is change and models aren't on panel. -
Sending and receiving custom signals in Django and ensuring it is atomic
I want to create a custom signal and send the signal after some database operations. The receiver also performs database operations. I want to make sure all the database operations before sending the signal and in the signal, receiver is atomic meaning either all fail, or all succeed. Consider the following code: def send_my_signal(): # Database operation 1 # Database Operation 2 my_signal.send(sender=MyModel) The receiver: @receiver(my_signal) def my_receiver(sender, **kwargs): # Database operation 3 # Database operation 4 I want either all database operations 1 to 4 succeed or fail together. By asking from generative AI models, one proposed solution is to wrap the body of the function that performs database operations and sends the signal inside the transaction.atomic() context manager. So, the code would look like this: def send_my_signal(): with transaction.atomic(): # Database operation 1 # Database Operation 2 my_signal.send(sender=MyModel) But I could not find any resource or anything in Django documentation confirming this. It's not like I am calling the receiver of the signal inside the transaction.atomic() context manager, I am just sending the signal there. -
Optimizing One-to-Many Joins in Django MySQL ORM for Better Data Presentation
In Django MySQL ORM, I wanted to join tables with one-to-many relations. Consider a scenario where one user can belong to more than one department. Users and Departments are different entities. Now, if I want to demonstrate the rows as, User columns and department names the user belongs to in a single column as a list. How do I do that most efficiently? Example: class User(models.Model): name = models.CharField(max_length=100) class Department(models.Model): name = models.CharField(max_length=100) user = models.ForeignKey(User, on_delete=models.CASCADE) Output: [ {'id': 1, 'name': 'John', 'department_names': ['HR', 'IT']}, {'id': 2, 'name': 'Alice', 'department_names': ['Finance']} ] I tried this: queryset = User.objects.values( 'id', 'name', ).annotate( department_names=Concat( 'department__name', Value(', '), output_field=CharField(), ) ).filter( department__isnull=False ).distinct() But got this: <QuerySet [ {'id': 1, 'name': 'John', 'department_names': 'HR, '}, {'id': 1, 'name': 'John', 'department_names': 'IT, '}, {'id': 2, 'name': 'Alice', 'department_names': 'Finance,'} ]> Expecting something this: <QuerySet [ {'id': 1, 'name': 'John', 'department_names': 'HR, IT'}, {'id': 2, 'name': 'Alice', 'department_names': 'Finance'} ]> -
Validate Django `JSONField` values are dictionaries
Is there anyway to require that a Django JSONField stores dictionary values only? And throws an error on scalar values. For example, I want the following values to be valid: {} {"a": 1} {"a": 1, "b": 2} And I want the following values to be invalid: "hello world" True 1 JSONField currently accepts all of these values, which makes sense because they're all valid json. But I want to change that behavior. -
How do I reduce the number of connections requests created by a multithreaded Django request?
My project is roughly set up like this thread_pool = ThreadPoolExecutor() def my_background_thread(model: MyModel): # Other DB Reads here ... # Some long running action here, spawning several threads ... # Save result of action to DB model.field = val model.save() # Other DB writes ... def my_view(request): model = MyModel.objects.get(...) thread_pool.submit(my_background_thread, model) # Return before thread has completed return HttpResponse("success") Unfortunately, because of the way I've set it up, Django is creating far too many DB connections -- more than necessary and exceeding my DB limits. Some things that are not clear: When I pass model to the new thread, does it create a new connection at that point? Does it create a new connection only when I read / write to the model? Only when I write? How do I check the number of open connections, or show when a connection is created? In short, how can I prevent Django from creating too many connections in this scenario? -
Emulating an empty queryset with an abstract model
I have a use case in which I have a ListAPIView that connects to a 3rd party (Stripe) API, fetches data (invoices) and returns that data to the user. I have a serializer, but I don't have a model. The entire code looks something like this: class InvoicesList(generics.ListAPIView): serializer_class = InvoiceSerializer def get_queryset(self): if getattr(self, 'swagger_fake_view', False): return # <---- ¿?¿?¿?¿?¿?¿?¿?¿? return StripeWrapper().get_invoices() class InvoiceSerializer(serializers.Serializer): ...fields.. ...fields... ...fields class StripeWrapper(): def get_invoices(): return requests.get(......) Since I don't have a model, drf-spectacular refuses to generate the proper openapi specs. It expects to receive an EmptyQuerySet (SomeModel.objects.none()), but I can't provide it any since I don't have an Invoice model. I could create an abstract model like this: class Invoice(models.Model): class Meta: abstract = True but I still won't be able to provide drf-spectacular with an Invoice.objects.none() since there is no manager in that class (and there can't be since it's abstract). How can I "emulate" (¿?) or "generate" an EmptyQuerySet so I can workaround this issue? -
Django get all Models with an associated Model
Hi im currently trying to learn Django. How would I write a query to get all Person instances that have an associated existing Form instance. For example: These are my models: class Person(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) class Form(models.Model): filled_by = models.ForeignKey(Person, on_delete=models.CASCADE) I have the following Person objects PersonA: {id: 1, name: 'Will'} PersonB: {id: 2, name: 'Greg'} PersonC: {id: 3 name: 'Dan'} And the following Form objects Form1: {filled_by: PersonA} Form2: {filled_by: PersonC} Query should return PersonA and PersonC -
AssertionError: Model userauths.User can't have more than one auto-generated field
This is my user model from django.db import models from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager, PermissionsMixin, ) from django.core.exceptions import ValidationError from django.core.validators import validate_email from django.utils.translation import gettext_lazy as _ import uuid from django.utils import timezone class CustomUserManager(BaseUserManager): """Manager for users""" def email_validator(self, email): try: validate_email(email) return True except ValidationError: raise ValueError(_("You must provide your interac email address")) def create_user(self, first_name, last_name, email, password, **extra_fields): """Create, save and return a new user""" if not first_name: raise ValueError(_("Users must have a first name")) if not last_name: raise ValueError(_("Users must have a last name")) if email: email = self.normalize_email(email) self.email_validator(email) else: raise ValueError(_("Users must have an email address.")) user = self.model(email=email, first_name=first_name, last_name=last_name **extra_fields) user.set_password(password) extra_fields.setdefault("is_staff", False) extra_fields.setdefault("is_superuser", False) user.save(using=self._db) return user def create_superuser(self, first_name, last_name, email, password, **extra_fields): """Create and return a new super user""" user = self.create_user(first_name, last_name, email, password) 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_staff=True")) if extra_fields.get("is_active") is not True: raise ValueError(_("Superuser must have is_active=True")) if not password: raise ValueError(_("Superuser must have a password")) if email: email = self.normalize_email(email) self.email_validator(email) else: raise ValueError(_("Superuser must have an email address.")) … -
Internal Server Error 500 Django on Apahce
Created a getting started Django app (Rocket screen..). Implemented serving the Django app locally via Apache according to this guide. Followed all the previous threads here in stack. Result: localhost:8000 Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator at admin@example.com to inform them of the time this error occurred, and the actions you performed just before this error. More information about this error may be available in the server error log. httpd -e debug [Thu Feb 08 19:44:25.462095 2024] [so:debug] [pid 23164:tid 436] mod_so.c(266): AH01575: loaded module actions_module from C:/Users/u/Desktop/Ido/WorkSpace/Apps/apache/Apache24/modules/mod_actions.so [Thu Feb 08 19:44:25.463099 2024] [so:debug] [pid 23164:tid 436] mod_so.c(266): AH01575: loaded module alias_module from C:/Users/u/Desktop/Ido/WorkSpace/Apps/apache/Apache24/modules/mod_alias.so [Thu Feb 08 19:44:25.465112 2024] [so:debug] [pid 23164:tid 436] mod_so.c(266): AH01575: loaded module allowmethods_module from C:/Users/u/Desktop/Ido/WorkSpace/Apps/apache/Apache24/modules/mod_allowmethods.so [Thu Feb 08 19:44:25.466114 2024] [so:debug] [pid 23164:tid 436] mod_so.c(266): AH01575: loaded module asis_module from C:/Users/u/Desktop/Ido/WorkSpace/Apps/apache/Apache24/modules/mod_asis.so [Thu Feb 08 19:44:25.467114 2024] [so:debug] [pid 23164:tid 436] mod_so.c(266): AH01575: loaded module auth_basic_module from C:/Users/u/Desktop/Ido/WorkSpace/Apps/apache/Apache24/modules/mod_auth_basic.so [Thu Feb 08 19:44:25.468159 2024] [so:debug] [pid 23164:tid 436] mod_so.c(266): AH01575: loaded module authn_core_module from C:/Users/u/Desktop/Ido/WorkSpace/Apps/apache/Apache24/modules/mod_authn_core.so [Thu Feb 08 19:44:25.470163 2024] [so:debug] [pid 23164:tid 436] mod_so.c(266): AH01575: loaded module authn_file_module from … -
django authenticate error with DJANGO_SETTINGS_MODULE
im new to django . I was doing some things to figure out how the code works. I did some part of the tutorial. I have an app folder named polls and the standard mysite folder where there is the settings.py file . I created another python file in mysite folder , auth.py and I wrote this code : from django.contrib.auth import authenticate user_auth = authenticate(username = "test-username", password = "test-password") print(user_auth) What I want to do is just see what the authenticate function returns. I want to know certain things like , where are the credentials searched for the authentication. I don't know any of that and that's the reason I want to print some things in the code. First question is, can I do that ? I always have learned coding with actually doing the things from the very basics, looking for what is happening with the code . The second question is that im trying to run the code but it gives me an error : django.core.exceptions.ImproperlyConfigured: Requested setting AUTHENTICATION_BACKENDS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I searched in google and I found the … -
Django - how do I filter or exclude by two identical fields?
We are using Django for our website. I have a query for model User and I want to exclude users which have two identical fields - in this case id and username. So if the id==username, I want to exclude them. How do I do it? The query looks like: users = User.objects.filter(...) And I want to add .exclude(...) where the id and username fields are equal. -
Django | NOT NULL constraint failed | When trying to reverse migrations
I, on a whim, made a bad decision to comment out a models.OneToOneField in one of my models and then migrate to see if it fixed a problem I was having. I realized after that I can't just re-migrate a models.OneToOneField in the same way I had originally and it started to throw the error "django.db.utils.IntegrityError: UNIQUE constraint failed:" this being because I was trying to re-migrate a models.OneToOneField back into my model I didn't think this was a huge issue, I was just going to reverse migrate to "0008_alter_profile_profile_private" because "0009_remove_profile_user" was the migration that caused the issue to start with. But now it's throwing the error "django.db.utils.IntegrityError: NOT NULL constraint failed: new__profiles_profile.user_id" Here is all the code that I understand to be important: Excerpt of my: models.py in "profiles" app: class Profile(models.Model): # User Profile model user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) #creates a OneToOneField connected to the user, that when the user gets deleted, so does the profile riot_name = models.TextField(default="RiotUser#1234") # Riot Username avatar = models.ImageField(upload_to='avatars', default='avatar.png') # Profile Image Field banner = models.ImageField(upload_to='banners', default='banner.jpg') # Banner Image Field friends = models.ManyToManyField(User, related_name='friends', blank=True) # Friends list bio = models.TextField (default="I don't have a bio... :(") # … -
django_countries not being recognized for import in my Pycharm
I am building an ecommerce website with Django and I want to add a dropdown menu for the user to select their state of residence. Since manually inputting (hardcoding) the list of states in the country would be tedious and unnecessary, I tried using the django_countries package. I have successfully installed the package using pip install django-countries it comes up in my list of installed packages in my Django project. I added it to my list of installed apps in my settings.py - INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'ecommerce', 'accounts', 'cart', 'social_django', 'social_core', 'anymail', 'django_countries' ] So everything seems right, and at the top of my views.py, after all other imports I have - from django_countries import countries this is my views funtion that needs the import - def address_book_create(request): user = request.user # Get the logged-in user personal_details = user.personal_details # Add 'COUNTRIES' to the context dictionary context = { 'user': user, 'personal_details': personal_details, 'COUNTRIES': countries, # Include the country data } return render(request, 'accounts/address_book_create.html', context) So the line from django_countries import countries is being underlined in my Pycharm with the words "Unresolved reference 'django_countries'" I don't know why.the error is being shown because i … -
while using vs code, terminal no longer activates the virtual enviroment
whenever i open a new terminal window inside vs code, I get this pop-up massage. terminal works just fine, but I no longer can see the activation script that is like source/...../bin/activated. here is the actual massage: Python virtual environment was successfully activated, even though "venv" indicator may not be present in the terminal prompt. -
Django is automatically adding an ID field during unit tests even though I declared a primary key for my model
I have a django project with multiple tables and am in charge of writing unit tests for the api of said django project. One of the tables has a ForeignKey of a different table, however when I try to create the model object in a unit test I get the following IntegrityError after the model object the ForeignKey refers to is successfully queried, despite being able to post data to this table while the server is running: Traceback (most recent call last): File "C:\Python312\Lib\site-packages\django\db\backends\utils.py", line 105, in _execute return self.cursor.execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Python312\Lib\site-packages\django\db\backends\sqlite3\base.py", line 328, in execute return super().execute(query, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ sqlite3.IntegrityError: NOT NULL constraint failed: app_examplemodel.location_id The above exception was the direct cause of the following exception: ... Traceback (most recent call last): File "~\tests\test_example_model.py", line 19, in test_post_example_model_valid response = self.client.post(reverse("examplemodelurl"), EXAMPLE_MODEL_DICT, content_type="application/json") django.db.utils.IntegrityError: NOT NULL constraint failed: app_examplemodel.location_id Here is the unit test (it throws the error before I get the chance to assert anything): class TestPostExampleModel(TestCase): def test_post_example_model_valid(self): self.client.post(reverse("locations"), {"name": "location name"}, content_type="application/json") response = self.client.post(reverse("examplemodelurl"), {"name": "example name", "location": "location name"}, content_type="application/json") The main confusing thing about this is that on the official django site, it says the following about model autofields: If you’d … -
django.db.utils.IntegrityError: duplicate key value violates unique constraint "iranian_citi
I am a django developer, I want to use iranian cities library, but when I run this command py manage.py generate_city this error got: > (myenv) D:\myproject\math\maths>py manage.py generate_city Traceback (most recent call last): File "D:\myproject\math\myenv\Lib\site-packages\django\db\backends\utils.py", line 89, in _execute return self.cursor.execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ psycopg2.errors.UniqueViolation: duplicate key value violates unique constraint "iranian_cities_ostan_pkey" DETAIL: Key (id)=(1) already exists. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "D:\myproject\math\maths\manage.py", line 22, in <module> main() File "D:\myproject\math\maths\manage.py", line 18, in main execute_from_command_line(sys.argv) File "D:\myproject\math\myenv\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "D:\myproject\math\myenv\Lib\site-packages\django\core\management\__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\myproject\math\myenv\Lib\site-packages\django\core\management\base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "D:\myproject\math\myenv\Lib\site-packages\django\core\management\base.py", line 458, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\myproject\math\myenv\Lib\site-packages\iranian_cities\management\commands\generate_city.py", line 128, in handle self.generate_ostan(ostan_data_path) File "D:\myproject\math\myenv\Lib\site-packages\iranian_cities\management\commands\generate_city.py", line 37, in generate_ostan Ostan.objects.bulk_create(ostan_objs) File "D:\myproject\math\myenv\Lib\site-packages\django\db\models\manager.py", line 87, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\myproject\math\myenv\Lib\site-packages\django\db\models\query.py", line 786, in bulk_create returned_columns = self._batched_insert( ^^^^^^^^^^^^^^^^^^^^^ File "D:\myproject\math\myenv\Lib\site-packages\django\db\models\query.py", line 1831, in _batched_insert self._insert( File "D:\myproject\math\myenv\Lib\site-packages\django\db\models\query.py", line 1805, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\myproject\math\myenv\Lib\site-packages\django\db\models\sql\compiler.py", line 1822, in execute_sql cursor.execute(sql, params) File "D:\myproject\math\myenv\Lib\site-packages\django\db\backends\utils.py", line 102, in execute return super().execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\myproject\math\myenv\Lib\site-packages\django\db\backends\utils.py", line 67, in execute return self._execute_with_wrappers( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\myproject\math\myenv\Lib\site-packages\django\db\backends\utils.py", … -
Django Channels - Group
If in a group there are two channels, after group_send the event chat.message is handled by chat_message.. and its happening for both the channels because I'm printing the channel names and getting two different names... but UI gets updated for only on consumer and that too twice, whereas the other consumer shows no changes. In my client-side code, I have onmessage function, which is responsible for my UI getting updated. The ideal case is if I have two channels in the same group then the message should be broadcast to both and thus UI of both consumers should get updated. class MyWebsocketConsumer(WebsocketConsumer): def connect(self): print("Connected...",self.channel_name) self.group_name = self.scope['url_route']['kwargs']['group_name'] # print('Group Name...',self.group_name) async_to_sync(self.channel_layer.group_add)(self.group_name, self.channel_name) self.accept() def receive(self, text_data=None, bytes_data=None): async_to_sync(self.channel_layer.group_send)(self.group_name,{ "type": "chat.message", "msg": text_data, },) def chat_message(self,event): self.send(text_data = event['msg']) print(self.channel_name) def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)(self.group_name, self.channel_name) ws.onmessage = function(event){ console.log('Message recived from server...', event) document.getElementById('chat-log').value += (event.data + '\n') } -
Django - Autocomplete Search Throws Error For Logged Out Users?
I’m making some updates to the autocomplete portion of the search functionality in my application and for some reason i’m getting an error for logged out users that says TypeError: Field 'id' expected a number but got <SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x1088a5e20>>. This is only happening for logged out users. When users are logged in the autocomplete works as built so I know I’m missing something but I just don’t know what. What needs to get changed to fix this issue? I’m building a gaming application where users have access to play certain games based on their rank in our application. So when a user is logged in I’d like the autocomplete functionality to reflect the games they have unlocked. So let’s say if a user has a rank of 100 then all the games with a game_rank of 100 and below will be displayed. For logged out users I would like all games to be shown. Made some notes in my views.py code from what I tested and added the JavaScript to the search functionality just in case. Screenshots below of what displays for users logged out and logged in. Logged Out Screenshot Logged In Screenshot Below is my … -
Django channels - groups
If in a group there are two channels, after group_send the event chat.message is handled by chat_message.. and its happening for both the channels because I'm printing the channel names and getting two different names... but UI gets updated for only one consumer and that too twice, whereas the other consumer shows no changes. ` from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync class MyWebsocketConsumer(WebsocketConsumer): def connect(self): print("Connected...",self.channel_name) self.group_name = self.scope['url_route']['kwargs']['group_name'] # print('Group Name...',self.group_name) async_to_sync(self.channel_layer.group_add)(self.group_name, self.channel_name) self.accept() def receive(self, text_data=None, bytes_data=None): async_to_sync(self.channel_layer.group_send)(self.group_name,{ "type": "chat.message", "msg": text_data, },) def chat_message(self,event): self.send(text_data = event['msg']) print(self.channel_name) def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)(self.group_name, self.channel_name) ws.onmessage = function(event){ console.log('Message recived from server...', event) document.getElementById('chat-log').value += (event.data + '\n') } ` In my client-side code, I have onmessage function, which i responsible for my UI to get updated. An ideal case is if I have two channels in a group then the message should be broadcast to both and thus UI of both consumers should get updated. -
AssertionError in Django Unit Test: Unable to Retrieve Correct Count from Database
I'm encountering an AssertionError in my Django unit test when attempting to save a POST request to an existing list. Despite creating the list and sending the POST request successfully, the test fails with the following error: Failure Traceback (most recent call last): File "C:\ACode\TDD_Django\lists\tests.py", line 105, in test_can_save_a_POST_request_to_an_existing_list self.assertEqual(Item.objects.count(), 1) AssertionError: 0 != 1 Here's the relevant code: class NewListTest(TestCase): def test_can_save_a_POST_request_to_an_existing_list(self): # Arrange inputs and targets. correct_list = List.objects.create() # Act on the target behavior. self.client.post( f'/lists/{correct_list.id}/add_item', data={'item_text': 'A new item for an existing list'}, ) # Assert expected outcomes. self.assertEqual(Item.objects.count(), 1) new_item = Item.objects.get() self.assertEqual(new_item.text, 'A new item for an existing list') self.assertEqual(new_item.list, correct_list) URL: path('lists/<int:list_id>/add_item/', views.add_item, name='add_item') View: def add_item(request, list_id): our_list = List.objects.get(id=list_id) Item.objects.create(text=request.POST['item_text'], list=our_list) return redirect(f'/lists/{list_id}/') Model: def add_item(request, list_id): our_list = List.objects.get(id=list_id) Item.objects.create(text=request.POST['item_text'], list=our_list) return redirect(f'/lists/{list_id}/') I've tested the code manually using the requests library and verified that the view (add_item) works correctly. However, the unit test continues to fail. Any insights into why this test might be failing would be greatly appreciated. -
Create Raise error in model (clean method isn't working)
I want to raise some error like: if user create both bus_stop_1 and bus_stop_2 with same foreign key or if the count of an object exceed in a table more than 4 So my doubt is how can i raise the error when i use clean method it is not working properly class ConnectedRoute(models.Model): bus_stop_1 = models.ForeignKey( BusStop, on_delete=models.CASCADE, related_name='stop1') bus_stop_2 = models.ForeignKey( BusStop, on_delete=models.CASCADE, related_name='stop2') distance = models.FloatField(blank=True, null=True) time = models.TimeField(blank=True, null=True) def clean(self): if self.bus_stop_1 == self.bus_stop_2: raise ValidationError('Both stop cannot to the same') count_stop1 = ConnectedRoute.objects.filter( bus_stop_1=self.bus_stop_1).count() count_stop2 = ConnectedRoute.objects.filter( bus_stop_2=self.bus_stop_2).count() if count_stop1 + count_stop2 > 4: raise ValidationError('Only 4 connections allowed.') I tried to use this clean method, but i never found it useful is there anything that am missing -
Gmail django sending
Today, looking at a page about django recommendations, I got the concept of a fat model and skinny views, so I had a doubt if what it was doing was good or not and if it could be applied to a model and how? def EnvioGmail(self,Nombre,gmail): context = {"Gmail":gmail,"Nombre":Nombre} template = get_template("Correo.html") content = template.render(context)#Renderisamos la plantilla con el contexto email = EmailMultiAlternatives(#Este sirve para enviar muchos correos como html "Registro exitoso", "", settings.EMAIL_HOST_USER, [gmail] ) email.attach_alternative(content,"text/html")#Es para atajar el email y darle mas datos como el contenido y comos se mostrara email.send() def post(self,request,*args,**kwargs): Formmain = Usuarios(request.POST) if Formmain.is_valid(): Usuario = Formmain.cleaned_data["nombre"] Gmail = Formmain.cleaned_data["gmail"]#Aqui extraemos el gmail del objeto Formulario self.EnvioGmail(Usuario,Gmail) Formmain.save() return HttpResponseRedirect("/Informacion/") else: Mensaje ="Porfavor revisa tus datos" return render(request,"Base.html",{"Mensaje":Mensaje,"Formulario":Usuarios}) I hope someone can help me, I'm still learning many things about django. -
How to connect to existing instance of firefox using selenium in django and how to pass these arguments
I want to login to a page manually in firefox using selenium and use django to connect to this existing firefox browser and click on a link on this already opened page. I did see that a marionette port can be useful for this process but I am not sure how to add these arguments in the driver class and also how to call it to connect to this manually opened browser to click on an element and open a new browser. This is the driver class: class FirefoxDriver(webdriver.Firefox, CustomDriverBase): def init(self, *args, **kwargs): firefox_binary = FirefoxBinary(settings.FIREFOX_BINARY_PATH) super().init(firefox_binary=firefox_binary, *args, **kwargs) class BasePage: def init(self, driver: WebDriver): self.driver = driver def get_url(self, url: str) -> NoReturn: self.delay() self.driver.get(url=url) class HomePage(BasePage): url = 'any url which can be logged into' def get(self) -> NoReturn: self.get_url(url=self.url) self.click_button(locator_cls=locators.HomePageLocators, locator_name='submit') I want to login to a webpage manually in marionette port(and keep it open all the time) and in the HomePage class , I want to click on a link which has been opened on the marionette port and continue the process. I am not able to understand where the arguments for marionette port needs to be specified and how to click on a link …