Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Strange error: django.db.utils.OperationalError: (2000, 'Unknown MySQL error')
Like this question but more stranger: What is django.db.utils.OperationalError: (2000, 'Unknown MySQL error') I have an application using Django3.2 and works fine in container(ubuntu 18.04), yesterday I try to run it in another container based on the image python:3.9.13-bullseye from docker hub, it works fine on my macbook and Windows laptop, BUT when I run app in container based on the same image in our test envrionment , exec python manage.py runserver, it reports Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/usr/local/lib/python3.9/site-packages/django/db/backends/mysql/base.py", line 73, in execute return self.cursor.execute(query, args) File "/usr/local/lib/python3.9/site-packages/MySQLdb/cursors.py", line 206, in execute res = self._query(query) File "/usr/local/lib/python3.9/site-packages/MySQLdb/cursors.py", line 319, in _query db.query(q) File "/usr/local/lib/python3.9/site-packages/MySQLdb/connections.py", line 254, in query _mysql.connection.query(self, query) MySQLdb._exceptions.OperationalError: (2000, 'Unknown MySQL error') Django DATABASES settings: DATABASES["default"] = { "ENGINE": "django.db.backends.mysql", "NAME": "diag", "USER": DATABASE_USER, "PASSWORD": DATABASE_PASSWORD, "HOST": DATABASE_HOST, "PORT": DATABASE_PORT, "OPTIONS": { "connect_timeout": 5, "charset": "utf8mb4", }, } Differences between my macbook and our test environment: macbook: host: macOS 12.5.1 Docker version 20.10.16, build aa7e414 test env: host: ubuntu 16.04 Docker version 19.03.14, build 5eb3275d40 Strange things continues. Inside the test env container, I ran python manage.py shell Python 3.9.13 (main, Aug 23 2022, 09:07:44) [GCC … -
How do I dynamically change the logging level for all "django apps" that work with the "daphne" multi-process?
I am developing an API service backend consisting of "nginx + daphne + django". In 'nginx' and 'daphne', multiple "workers" handle requests. The log of "django app" is currently set to be output to stdout/stderr by the stream handler, which 'daphne' writes to the specified file. The log handlers set in the settings.py file are as follows. =============================================================== 'handlers': { 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'verbose' }, =============================================================== The daphne contents set in the supervisor.conf file are as follows. =============================================================== [fcgi-program:asgi] # TCP socket used by Nginx backend upstream socket=tcp://ipaddress:port # Directory where your site's project files are located directory=/my/path/project # Each process needs to have a separate socket file, so we use process_num # Make sure to update "mysite.asgi" to match your project name command=daphne -u /my/path/supervisord/daphne%(process_num)d.sock --fd 0 --access-log /dev/null --proxy-headers myproject.asgi.deploy:application # Number of processes to startup, roughly the number of CPUs you have numprocs=8 # Give each process a unique name so they can be told apart process_name=asgi%(process_num)d # Automatically start and recover processes autostart=true autorestart=true # Choose where you want your log to go stdout_logfile=/my/path/logs/asgi.log redirect_stderr=true =============================================================== In addition, I also need to provide an API that can dynamically change the log level … -
Django user activation doesnt work with token -- TypeError: a bytes-like object is required, not 'str'
So I have the following token activation setup for users to activate their accounts # urls.py # Activation path('activate/<uidb64>/<token>/', user_views.activate, name='activate'), # views.py User = get_user_model() # Get custom user model def activate(request, uidb64, token): # Debugging uid = force_bytes(urlsafe_base64_decode(uidb64)) print(User.objects.get(pk=uid)) try: uid = force_bytes(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.email_confirmed = True user.save() login(request, user) return redirect('/dashboard/overview/') else: return render(request, 'user/authentication/account_activation_invalid.html') # tokens.py from django.contrib.auth.tokens import PasswordResetTokenGenerator import six class AccountActivationTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.email_confirmed) ) account_activation_token = AccountActivationTokenGenerator() # models.py # Custom usermodel class UserProfile(AbstractBaseUser, PermissionsMixin): # Unique identifier id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) # Email and name of the user email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) # Privilege and security booleans is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=False) email_confirmed = models.BooleanField(default=False) objects = UserProfileManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def email_user(self, subject, message, from_email=None, **kwargs): """Send mail to user - Copied from original class""" send_mail(subject, message, from_email, [self.email], **kwargs) def __str__(self): return self.email However, when I click the emailed link, the view always returns the isn't valid path. Some … -
How to pass context data to an another file as a dict/list/any format in django?
In my project I'm trying to scrape reviews of a car chose by user. In the django app I want to pass the data in the context dictionary to an another scrape.py file. Code: models.py class SelectCar(models.Model): BRANDS = ( ('BMW','BMW'), ('MR','Mercedes') ) brand = models.CharField(max_length=30, choices=BRANDS, default="BMW") CAR_MODELS = ( ('X1','X1'), ('X2','X2'), ('X3','X3') ) car_model = models.CharField(max_length=30, choices=CAR_MODELS, default="X1") forms.py from .models import SelectCar class SelectCarForm(forms.ModelForm): class Meta: model = SelectCar fields = '__all__' scrape.py, here i want to import the context data and choose the url for the specific car in an if-else chain. For example, if chose car is honda amaze, context should be imported into scrape.py such that I'm able to choose url. import requests from bs4 import BeautifulSoup """import context here in some way""" def happyScrape(): """here, import the context and choose url based on chosen car if car is Honda amaze, choose url for honda amaze and so on. example- if brand is honda and model is amaze, """ url = 'https://www.carwale.com/honda-cars/amaze/user-reviews/'\ headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36'} cw_result = requests.get(url, headers=headers) cw_soup = BeautifulSoup(cw_result.text, 'html5lib') scrapeList =[] #scrape code here, stored in scrapeListHTML for data in … -
After splitting settings.py file, mod_wsgi failed to exec Python script file. And application = get_wsgi_application() errors occured over and over
Hi everybody I tried to deploy my django project with apache, mod_wsgi in windows. I splited my settings.py like this: source root folder project folder apps config settings init.py base.py local.py prod.py init.py asgi.py urls.py wsgi.py myenv After I splited settings.py, Mod_wsgi failed to exec python scripts file : 'C:/user/users/desktop/source_root_folder/project_folder/wsgi.py'. Mod_wsgi also show the exception that Exception occurred processing WSGI script : 'C:/user/users/desktop/source_root_folder/project_folder/wsgi.py' In Apache24 error log, 'C:/user/users/desktop/source_root_folder/project_folder/wsgi.py' application = get_wsgi_application() error occured. # project_folder/wsgi.py import os from django.core.wsgi import get_wsgi_application import sys sys.path.append('C:/Apache24/htdocs/ C:/user/users/desktop/source_root_folder') os.environ['DJANGO_SETTINGS_MODULE'] = 'project_folder.config.settings' os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project_folder.config.settings') application = get_wsgi_application() how can i deal with those errors? please give me some helps. -
Ajax sending data to django python
Recreating a page to use django forms (current screen does not use any django forms implementation when rendering a template), to take in data from google places autocomplete. Basically just taking the response from google, converting it to json and making an ajax call with the form data and google data. The problem I'm getting is when I serialize the form to pass the data into an ajax call the field that's storing this json value is coming in as a json wrapped in an array instead. Looking at the current page I have this does not happen and the data retrieved from google's api comes in as correctly. The javascript that handles fetching the data from google is both the same and when applying it to the google-details field in the html, the value is updated by doing a .val(JSON.stringify()) on the data that is retrieved from google. $(document).ready(function () { $("#myForm").on("submit", function () { event.preventDefault(); do_ajax_call(); } } function do_ajax_call() { let foo = $("#myForm").serialize(); $.ajax({ url: '/destination/', type: 'post', data: foo, success: function(res) { //Do stuff } }) } <form id="myForm"> <input type="hidden" id="google-details" name="google-details"> {{ form }} <button type="submit" id="submit">submit </form> data that I'm getting from … -
ImportError: cannot import name 'get_rule_detail' from 'jira_plug.utils.rule' (D:\code\ido-jira-plug\IdoJiraPlug\jira_plug\utils\rule.py)
My Django project have a problem when it starts 2022-09-01 09:22:51,525 [MainThread:25612] [django.utils.autoreload:612] [INFO]- Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Python37\lib\threading.py", line 926, in _bootstrap_inner self.run() File "C:\Python37\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Python37\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Python37\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Python37\lib\site-packages\django\core\management\base.py", line 396, in check databases=databases, File "C:\Python37\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Python37\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Python37\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Python37\lib\site-packages\django\urls\resolvers.py", line 408, in check for pattern in self.url_patterns: File "C:\Python37\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python37\lib\site-packages\django\urls\resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Python37\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python37\lib\site-packages\django\urls\resolvers.py", line 582, in urlconf_module return import_module(self.urlconf_name) File "C:\Python37\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "D:\code\ido-jira-plug\IdoJiraPlug\IdoJiraPlug\urls.py", line 23, in … -
How to efficiently add similar contexts to multiple views in django?
Suppose we have two or more views, where each view templates extends from base.html, and inside the base.html are context variables project_name and company_name: base.html: <!DOCTYPE html> <html> <head> <title>{{ project_name }}</title> </head> <body> {{ company_name }} {% block content %}{% endblock %} </body> </html> Then we would have to add the above-mentioned contexts to our views as follow: views.py def view1(request) context = { "view1 data": "some data", "project_name": "Project Name", "company_name": "Company Name", } return render(request, "view1.html", context) class View2(DetailView): template_name = "view2.html" model = SampleModel def get_context_data(self, **kwargs): context = super(View2, self).get_context_data(**kwargs) context["view2 data"] = "sample data" context["project_name"] = "Project Name" context["company_name"] = "Company Name" return context How do we write an efficient code so that our views will look like as follows, i.e. the common contexts project_name and company_name are factored out somewhere else yet will still be displayed in the base.html? desired views.py def view1(request) context = { "view1 data": "some data", } return render(request, "view1.html", context) class View2(DetailView): template_name = "view2.html" model = SampleModel def get_context_data(self, **kwargs): context = super(View2, self).get_context_data(**kwargs) context["view2 data"] = "sample data" return context -
Showing Details in Django Admin for Many to Many Relationship
I have a model where there are log class model and there is session class model. For each session there is several logs that can be recorded. So I created the following model: class Log(models.Model): log_workout = models.CharField(max_length = 30, blank=True, null=True) log_exercise = models.CharField(max_length = 30, blank=True, null=True) log_order = models.IntegerField(validators=[MinValueValidator(1)],blank=True, null=True) class ActiveSession(models.Model): active = models.BooleanField(default=False) log = models.ManyToManyField(Log) date = models.DateTimeField(auto_now_add=True,blank=True, null=True) In the admin I tried to use the inline so that I can see the details of each log in a session but it is only showing the full list and highlighting the added logs. Here is the admin.py class ActiveSessionInline(admin.TabularInline): model = ActiveSession.log.through class LogAdmin(admin.ModelAdmin): model = Log inlines = [ ActiveSessionInline, ] My question: Can I instead of showing the added log in the below image to show the logs that is selected as if I am viewing them from LogAdmin even if it is inline -
django.db.utils.IntegrityError: UNIQUE constraint failed OneToOneField Django
I have a problem with my database. I have two models (Member, ActiveMember) with a OneToOneField relationship setup. A member can only have one membership at a time. However, I seem to be getting a Unique error. Once I update my members membership using the update function things seems to get mixed up and the ID no longer work. I also get another error DoesNotExist. I think this happens with I delete a members and/or update, the ID's are shifting somehow. This Error I got when I tried to migrate. I had to delete the member the was causing me problems for it to work. Running migrations: Applying members.0007_alter_activemember_member...Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/usr/local/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 423, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: UNIQUE constraint failed: new__members_activemember.member_id The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/topxgym/.virtualenvs/env/topxgym/manage.py", line 22, in <module> main() File "/home/topxgym/.virtualenvs/env/topxgym/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File … -
Building a discussion forum with Django
I'm trying to build a robust discussion forum with Django. I haven't really found any good resources on how to do so.If anyone could share some resources and lead me into the right direction on how to get started that would be greatly appreciated. -
Deploy Django Prject in AAPnael
Does someone how to deploy a Django Project in AAPanel? I tried Python Maganer 2.0 but impossible for me! I get this error: Sorry, something went wrong: Traceback (most recent call last): File "class/flask_sockets.py", line 30, in call handler, values = adapter.match() File "/www/server/panel/pyenv/lib/python3.7/site-packages/werkzeug/routing.py", line 1945, in match raise NotFound() werkzeug.exceptions.NotFound: 404 Not Found: The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again. ...and many others after that.... Please help me -
Django Bootstrap Modal not working on everypage
I created a modal pop up its Django Bootstrap Modal module--it works fine but only on the user profile page. I want it to work on every page of the website, I have the button placed in the header. Has anyone encountered t his issue before. Here is my code: view.py from bootstrap_modal_forms.generic import BSModalCreateView class BookCreateView(BSModalCreateView): template_name = 'tutorials/create_book.html' form_class = CreateTutorialForm success_message = 'Success: Book was created.' success_url = reverse_lazy('index') def create_book(request): return render(request, 'tutorials/create_book.html', { }) forms.py class Meta: model = Book fields = ['title','author'] urls.py path('create_book/', views.BookCreateView.as_view(), name='create_book'), templates files <a class="nav-link create_book_button" id="create-book" href="#">create book <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" class="bi bi-plus-circle-dotted" viewBox="0 0 16 16"> <path d="M8 0c-.176 0-.35.006-.523.017l.064.998a7.117 7.117 0 0 1 .918 0l.064-.998A8.113 8.113 0 0 0 8 0zM6.44.152c-.346.069-.684.16-1.012.27l.321.948c.287-.098.582-.177.884-.237L6.44.153zm4.132.271a7.946 7.946 0 0 0-1.011-.27l-.194.98c.302.06.597.14.884.237l.321-.947zm1.873.925a8 8 0 0 0-.906-.524l-.443.896c.275.136.54.29.793.459l.556-.831zM4.46.824c-.314.155-.616.33-.905.524l.556.83a7.07 7.07 0 0 1 .793-.458L4.46.824zM2.725 1.985c-.262.23-.51.478-.74.74l.752.66c.202-.23.418-.446.648-.648l-.66-.752zm11.29.74a8.058 8.058 0 0 0-.74-.74l-.66.752c.23.202.447.418.648.648l.752-.66zm1.161 1.735a7.98 7.98 0 0 0-.524-.905l-.83.556c.169.253.322.518.458.793l.896-.443zM1.348 3.555c-.194.289-.37.591-.524.906l.896.443c.136-.275.29-.54.459-.793l-.831-.556zM.423 5.428a7.945 7.945 0 0 0-.27 1.011l.98.194c.06-.302.14-.597.237-.884l-.947-.321zM15.848 6.44a7.943 7.943 0 0 0-.27-1.012l-.948.321c.098.287.177.582.237.884l.98-.194zM.017 7.477a8.113 8.113 0 0 0 0 1.046l.998-.064a7.117 7.117 0 0 1 0-.918l-.998-.064zM16 8a8.1 8.1 0 0 0-.017-.523l-.998.064a7.11 7.11 0 0 1 0 .918l.998.064A8.1 8.1 0 0 0 16 8zM.152 9.56c.069.346.16.684.27 1.012l.948-.321a6.944 6.944 0 0 1-.237-.884l-.98.194zm15.425 1.012c.112-.328.202-.666.27-1.011l-.98-.194c-.06.302-.14.597-.237.884l.947.321zM.824 11.54a8 8 … -
How can I return the input of the API request into my html template, without it returning on my terminal using Django?
this is my function that uses google finance api to get news articles. someapp/views.py def news(request): if request.method == 'POST': url = "https://google-finance4.p.rapidapi.com/ticker/" querystring = {"t":"ETH-USD","hl":"en","gl":"US"} headers = { "X-RapidAPI-Key": "API KEY", "X-RapidAPI-Host": "google-finance4.p.rapidapi.com" } response = requests.request("GET", url, headers=headers, params=querystring) response.status_code response.text response.json() articles = response.json()['news'] return render(request, 'news.html', { "article": articles }) else: return HttpResponse('Error') this is the html code <body class="bg-dark"> <div style=" position: flex; width: 450px; align-items: center; align-content: center; justify-content: center; margin: 370px auto; " > <img class ="img-fluid" src="{% load static %} /static/logo.png" " alt="Crypto Talk" </div> <p>**{{ article }}**</p> </body> this is the html to the page where the POST request is coming from. <form class="form-inline" method="POST" action="{{ 'news/' }}" name="news" > <div class="input-group mb-3" style="margin: 0 auto; display: flex; width: 450px" > {%csrf_token%} <input type="text" class="form-control" placeholder="Enter Crypto" name="search" style=" display: block; margin: 0 auto; border-top-left-radius: 0; border-bottom-right-radius: 0; border-top-left-radius: 5px; border-bottom-left-radius: 5px; " /> <button class="btn btn-outline-primary btn-md" type="submit" id="button-addon2" > Search </button> for some reason it takes me to the new html but the page only has the logo. The content from the api I am looking to return is showing up in my terminal with the error "Not Found: … -
Django sending email using outlook
I'm trying to send email using Django on localhost, but it's giving me the below error. SMTPException at /listings No suitable authentication method found This is my function: send_mail( 'Subject here', 'Here is the message.', 'emailfrom', ['emailto'], auth_user='username', auth_password='password', ) And this is my settings: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'mail.etisalat.com' EMAIL_HOST_USER = 'myemail' EMAIL_HOST_PASSWORD = 'mypassword' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER -
Activate and Deactivate Boolean Django
I have this first model called "People", which has an attribute called "State" that is of type Boolean, this model I call in the model "Birthday". What I want is that when a person is inactive in their "State", they disappear from the "Birthday" model, and that when they are activated again, they appear in the "Birthday" model. It should be noted that in the Django administrative panel, when I enter the "birthday" model, all the people registered in the "People" model are displayed, even if they are active or not due to their "State" (Boolean). Maybe it could be solved with a condition. class People(models.Model): Name = models.CharField('Name', max_length = 20, blank = False, null = False) Last_Name = models.CharField('Last Name', max_length = 20, blank = False, null = False) State = models.BooleanField('Active Client', default = True) class Meta: verbose_name = 'People' verbose_name_plural = 'People' ordering = ['Name'] def __str__(self): return "{0} - {1}".format(self.Name, self.Last_Name.capitalize()) class Birthday(models.Model): People_Birthday = models.OneToOneField(People, on_delete = models.CASCADE) BirthdayCalendar = models.DateField('Birthday', blank = False, null = False) class Meta: verbose_name = 'Birthday' verbose_name_plural = 'Birthdays' def __str__(self): return str(self.People_Birthday) -
Role or Groups? DJANGO
I'm developing an application, and I'm not sure about permissions. I have two types of user, client and supermarket. The only thing i want is to limit the views (What one can see and the other can't). Is the best approach role or groups ? Or both together. I get the expected behavior with one or the other, but I don't know which is correct -
I have a problem uploading images to DO Spaces resized with PILL
I'm uploading images to Digital Ocean Spaces using boto3. It's working really good until I add PILL. In django view I have this code when I get the image: images = request.FILES.getlist('images') for index, image in enumerate(images): size = image.size content_type = image.content_type file_name = image.name I can see all the information of each image. To upload the image I use this method that is working too: def upload_file(self, key, file, content_type, acl='private'): client = self.default_session_client() client.put_object( Bucket=BUCKET_NAME, Key=key, Body=file, ACL=ACL[acl], ContentType=content_type, Metadata={ 'x-amz-meta-my-key': '*****' } ) The problem start when I call this another method to resize the image, even if I just leave te method with pillow_image = Image.open(image) I get the error. from PIL import Image def resize_maintain_its_aspect_ratio(image, base_width): pillow_image = Image.open(image) width_percent = (base_width / float(pillow_image.size[0])) height_size = int((float(pillow_image.size[1]) * float(width_percent))) resized_image = pillow_image.resize((base_width, height_size), Image.ANTIALIAS) return resized_image So, the error is ( even if I use Image.open(image)) I see this: An error occurred (BadDigest) when calling the PutObject operation (reached max retries: 4): Unknown Does anyone know what the problem is ? -
Django development server not accessible via Cypress E2E testing
I use django-tenants for multitenancy. I use subdomains for each tenant and have a test tenant set up with a schema_name=demo. When running python manage.py runserver in local development, the server is accessible at http://demo.localhost:8000. However, when configuring cypress to use the local server (via Chrome E2E), it does not resolve the server. I have confirmed that the server is running and accessible from a normal instance of Chrome. My cypress config: module.exports = defineConfig({ projectId: '4dofbo', e2e: { baseUrl: 'http://demo.localhost:8000', }, }); What could be causing this? -
Django redirect from resource not working
I have this in my resource: def after_import_instance(self, instance, new, row_number=None, **kwargs): ... base_url = 'https://account.box.com/api/oauth2/authorize' client_id = '[CLIENT_ID]' auth_url = f'{base_url}?client_id={client_id}&response_type=code' print(auth_url) return redirect(auth_url) the auth_url is being printed, but the redirect is not working. Here is the print: [2022-09-01 05:07:10,617: WARNING/MainProcess] https://account.box.com/api/oauth2/authorize?client_id=[CLIENT_ID]&response_type=code -
Django Rest Framework - SearchFilter
I need to try get a SearchFilter working for fields within a set within another set. class Fight(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE, related_name="fights") class FighterStats(models.Model): fight = models.ForeignKey(Fight, on_delete=models.CASCADE, related_name="fighters") fighter = models.ForeignKey(Fighter, on_delete=models.CASCADE, null=True) class EventSearchFilter(filters.SearchFilter): def get_search_fields(self, view, request): field_names = { "name": "name", "venue": "location__venue", "fighters": "fights__fighters__fighter__first_name__name" } Don't have issues with getting foreign keys to work but i could use some help with foreign sets. I removed the unrelated fields/code from above. -
Rendering Django_Filter Search Results on the searched Property Page
I have tried different options and I don't seem to get how to show my searched property from the home page on searched page. Basically, I have two templates home page and searched property page. I have a search form in my home page and I would like to display the results on the other page. My views.py for Home Page def home(request,): properties = Property.objects.all()[:5] context = {"property": property, "properties": properties} return render(request, "base/index.html", context) My views for Search Page def prop_search(request,): property = Property.objects.all() properties = Property.objects.all() images = Image.objects.filter(property__in=property.all()) propFilter = PropertyFilter(request.GET, queryset=property) count = propFilter.qs.count() context = { "propFilter": propFilter, "property": property, "properties": properties, "images": images, 'paginator':paginator, } return render(request,'base/property-list.html', context) My Urls.py path("", views.home, name="home"), path("add-property", views.addProperty, name="addProperty"), path("prop_search", views.prop_search, name="prop_search"), -
how i can change str serializers name to class objects using django
class Create(View): def get(self, request): sername = request.GET.get('SerializersName') result = sername(request.POST) if result.is_valid(): result.save() return ***** -
Django dynamic ListView filtering problem
I am working on my first solo project with Django and I have hit a problem that no amount of searching and reading similar post on SO have solved. I am trying to filter a gallery of images by their category, so that when the user clicks on a picture it will result in a page showing all the images with the same category. This will use HTMX hopefully in the final product, but I'm trying and failing to implement it using regular Django views initially. As I said, this is my first solo project, so I'm very much a beginner, I know this isn't a debug service but just wanted some pointers on where I could be going wrong. Another set of eyes as you will. I followed the docs on dynamic filtering CBV. I have overwritten get_queryset passing the Category slug into the kwargs and I have overwritten the get_context_dataso I can pass slug into the template. I am getting a Reverse for 'select' with arguments '('',)' not found. 1 pattern(s) tried: ['select/(?P<slug>[-a-zA-Z0-9_]+)\\Z'] error, so I belive the problem is in my template/URLconf. Models. Media with a FK to it's Category class Category(models.Model): title = models.CharField(max_length=200, null=True) slug … -
Django-allauth : prevent user to provide alternative email when logging using social account
I use django-allauth with google and facebook providers and the following options: SOCIALACCOUNT_AUTO_SIGNUP=True SOCIALACCOUNT_EMAIL_VERIFICATION="none" With these settings, django-allauth will use the email provided by the 3rd-party app (Facebook, Google), unless it is already used in an existing account. In this case the user can choose whatever email. I would like an error message instead of that, saying that the address is already in use since I do not want to validate email with social accounts (using social accounts should be handy). How to prevent using social accounts that are associated with an address which is already registered?