Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Better way to access a nested foreign key field in django
Consider the following models class A(models.Model): id field1 field2 class B(models.Model): id field3 field_a (foreign_key to Class A) class C(models.model): id field4 field5 field_b (foreign_key to Class B) @property def nested_field(self): return self.field_b.field_a Now here that property in class C , would trigger additional sql querries to be fetched , Is there an optimized or better way to get nested foreign key fields ? I have Basically tried searching and finding regarding this and couldn't find a better solution, that addresses this problem. -
DRF spectacular extend_schema_view
what if i want to add one more list to extend_schema_view list=extend_schema( description="The list action returns all available actions." ), list=extend_schema( description="The list action returns all available actions." ), ) class MyViewSet(viewsets.ViewSet): pass I have tried something like this but not working It tried something like the above code I got error : SyntaxError: keyword argument repeated: list -
Django+heroku shows time of response which grows linnearly against volume of data - what to do?
What should I change to make the time shorter? I experimented with numer of records in output table. I pass the number as parameter. Time of processing on server is the same. But time of pause before data transfer is growing fast -
Access local device from Django application
I have a Django application hosted in the server. Now, I want to implement a feature where people will be able to see the locally connected Scanner list and access them directly from the Django-React.js application. After accessing them, I want to get the scan copy directly into the Frontend. How to do that? I found some premium plugins to do that. But I want something free. -
Creating a CRUD System for Multiple Users in Django
Basically, im trying to start a project, I've done few CRUD projects in django, but for specific clients, I just want to replicate these projects for multiple users, meaning, that you registering in my site, you'll be able to have your or CRUD for you particular business... How would this logic be? Is It the same, or its way more complex? What path should I take to achieve this goal. -
Redis Elasticache doesn't work on my Django EBS when setting the DEBUG=False
Do anyone have any idea why my Redis Elasticache doesn't work on my Django EBS when setting the DEBUG=False but works when setting the DEBUG=True? Here is my settings.py `import os from import_export.formats.base_formats import XLSX EXPORT_FORMATS = [XLSX] BASE_DIR = Path(file).resolve().parent.parent SECRET_KEY= os.environ.get( 'DJANGO_SECRET_KEY', ) if 'DJANGO_DEBUG' in os.environ: if os.environ['DJANGO_DEBUG'] == 'False' or os.environ['DJANGO_DEBUG'] == '0': DEBUG = False else: DEBUG = True if 'CacheURL' in os.environ: CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": [ os.environ['CacheURL'], os.environ['ReplicaCacheURL002'], os.environ['ReplicaCacheURL003'], ], "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "ssl_cert_reqs": None, }, "KEY_PREFIX": "example", "KEY_FUNCTION": "django_tenants.cache.make_key", "REVERSE_KEY_FUNCTION": "django_tenants.cache.reverse_key", }, "select2": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": [ os.environ['CacheURL'], os.environ['ReplicaCacheURL002'], os.environ['ReplicaCacheURL003'], ], "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "ssl_cert_reqs": None, } } } CACHE_TTL = 60 * 15 SELECT2_CACHE_BACKEND = "select2"` When I set the DEBUG to False, the redis caching do not work. -
Bag of Words with Negative Words in Python
I have this document It is not normal text It is a text of Scientific terminologies The text of these documents are like this RepID,Txt 1,K9G3P9 4H477 -Q207KL41 98464 ... Q207KL41 2,D84T8X4 -D9W4S2 -D9W4S2 8E8E65 ... D9W4S2 3,-05L8NJ38 K2DD949 0W28DZ48 207441 ... K2D28K84 I can build a feature set using BOW algorithm Here is my code def BOW(df): CountVec = CountVectorizer() # to use only bigrams ngram_range=(2,2) Count_data = CountVec.fit_transform(df) Count_data = Count_data.astype(np.uint8) cv_dataframe=pd.DataFrame(Count_data.toarray(), columns=CountVec.get_feature_names_out(), index=df.index) # <- HERE return cv_dataframe.astype(np.uint8) df_reps = pd.read_csv("c:\\file.csv") df = BOW(df_reps["Txt"]) The result will be the count of words in the "Txt" column. RepID K9G3P9 4H477 -Q207KL41 98464 ... Q207KL41 1 2 8 3 2 ... 1 2 0 1 2 4 ... 2 The trick and here where I need the help, is that some of these terms have a - ahead of it, and that should count as negative value So if the a text have these values Q207KL41 -Q207KL41 -Q207KL41 in that case the terms that starts with - should be count as negative and therefore, the BOW for the Q207KL41 is -1 instead of having a feature for Q207KL41 and -Q207KL41 they both count towards the same term Q207KL41 but … -
How to make roles in django that has different tasks based on the roles?
im kinda new to django but i've tried using django once or twice. However, this is my first time implementing roles in django. So the case is, let's say that i have 2 roles (Manager, Normal User) and lets say 3 department. For the manager, I wanted them to can see all of the dashboard of the company. For the normal user, i wanted them to can see their own department dashboard and couldn't access to any other dashboard other than their own. For example, a Normal User from Finance department could only access Finance Department Dashboard and could not access like Sales Department and Operational Department. I need some clues to make the roles, I've seen the django admin site where you can add some user or group. I tried looking at the documentation but it got me confused and lost. Maybe perharps I could get some hints or description that could lead me to understand how it works? -
Django Web App - Static Files Forbidden 403 Error when Retrieving from AWS S3 Bucket
Context I have successfully developed and deployed a Django web application on AWS, leveraging an AWS RDS Postgres instance for the database. In the deployment process, I utilized the 'collectstatic' command to gather static files, and with the help of the community in a previous post, I overcame challenges related to that stage. Current Challenge Following the successful 'collectstatic' process and upload to an S3 Bucket, I am encountering an issue wherein the static files cannot be retrieved by the HTML within the Django app. GET https://postgram-bucket.s3.amazonaws.com/static/css/main.css net::ERR_ABORTED 403 (Forbidden) GET https://postgram-bucket.s3.amazonaws.com/static/css/bootstrap.min.css net::ERR_ABORTED 403 GET https://postgram-bucket.s3.amazonaws.com/static/img/postgram_logo.png 403 (Forbidden) Troubleshooting Steps Taken Successfully executed 'collectstatic' and uploaded static files to the S3 Bucket. Checked AWS S3 Bucket permissions and confirmed that the IAM role associated with the Django app has the necessary permissions. Validated credentials by making a request through Postman, and the static files were successfully received in the response (refer to the attached image). Relevant Configuration AWS S3 Bucket configuration IAM role configuration Code Snippet setting.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates') ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] ########## # AWS S3 # ########## USE_S3 = … -
hello , so i'm working on my logging for my project using Django and the auth is with metamask but when the user tries to register the data isnt saved
when the user logs for the first time using metamask , he's redirected to the register form to complete his account by adding email , first name , last name and password but when the user submit thr form and i check the admin dashboard i only see the username aka the eth address but the other info from the form arent saved , here's the view : import json import requests import datetime from django.shortcuts import render, redirect from django.http import JsonResponse from django.contrib.auth import authenticate, login from django.contrib.auth.models import User from .forms import RegisterForm from django.contrib.auth.decorators import login_required API_KEY = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJub25jZSI6IjBhM2I2MTRjLWQ2ZjQtNGRkOS04M2RmLTIzNmZiMjBjNzg1OCIsIm9yZ0lkIjoiMzY5NTYzIiwidXNlcklkIjoiMzc5ODE2IiwidHlwZUlkIjoiOTNiZDhjOWYtNTViZC00ZmFmLThiMTQtNTZhYTFhZmIyMjZhIiwidHlwZSI6IlBST0pFQ1QiLCJpYXQiOjE3MDM1MjQ5NTcsImV4cCI6NDg1OTI4NDk1N30.CrZJcIyqcCdYMtM45pbRB4tY7-fOqwxSRhEtmE_dba0' def moralis_auth(request): return render(request, 'login.html', {}) def request_message(request): data = json.loads(request.body) print(data) REQUEST_URL = 'https://authapi.moralis.io/challenge/request/evm' # Adjusted expiration time to 5 minutes from the current time expiration_time = (datetime.datetime.utcnow() + datetime.timedelta(minutes=5)).isoformat() + "Z" request_object = { "domain": "defi.finance", "chainId": 1, "address": data['address'], "statement": "Please confirm", "uri": "https://defi.finance/", "expirationTime": expiration_time, "notBefore": "2020-01-01T00:00:00.000Z", "timeout": 15 } x = requests.post( REQUEST_URL, json=request_object, headers={'X-API-KEY': API_KEY}) return JsonResponse(json.loads(x.text)) def verify_message(request): data = json.loads(request.body) print(data) REQUEST_URL = 'https://authapi.moralis.io/challenge/verify/evm' x = requests.post( REQUEST_URL, json=data, headers={'X-API-KEY': API_KEY}) print(json.loads(x.text)) print(x.status_code) if x.status_code == 201: # user can authenticate eth_address = json.loads(x.text).get('address') print("eth address", eth_address) try: user … -
Error code: Unhandled Exception (Identation error)
Claro, a tradução para o inglês seria: "I can't make sense of this set of errors. It's not making any sense in my head." Image of the error message provided by the server Image of the error in the log file wsgi code # +++++++++++ DJANGO +++++++++++ # To use your own Django app use code like this: import os import sys # assuming your Django settings file is at '/home/horaciobarret1/project/project/settings.py' path = '/home/horaciobarret1/project/' if path not in sys.path: sys.path.insert(0, path) os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings' I would like my link to work normally on the server -
Django-filter won't display TreeNodeChoiceField (MPTT package) as tree choice field
I have a Category MPTT model. I have a Transaction django model which has a ForeignKey assigned to Category model (field = 'category'). Using django-filter lib I'm trying to filter Transactions in a ListView. Everything works fine except the 'category' filter field appears as choice field with plain list of all categories instead of list with tree 'leveling'. My FilterSet class: class TransactionsListFilter(django_filters.FilterSet): """ Filters for Transaction list. """ title = django_filters.CharFilter(lookup_expr="icontains", label="Transaction title") date_created = django_filters.DateFromToRangeFilter(widget=RangeWidget(attrs={'type': 'date'})) category = TreeNodeChoiceField(queryset=Category.objects.all()) class Meta: model = Transaction fields = ["title", "category", "operation", "date_created"] I was trying to add a TreeNodeChoiceField as I did the same in forms (there it works) but in FilterSet class don't make a trick. The dropdown choice field is still plain list without category leveling by subcategory. Is there a way to make the choice list appears with as tree? -
Django: how to access ManyToManyField assignments before .save() method (during model .clean() method)
Background Goal I have a Model that needs to be associated with different objects depending on its type, so I'm validating this in the Model's .clean() method. If it's a "Dialogue" type, then it should only have "dialogue" objects (ForeignKeyField) associated with it. If it's a "Mixed" type, then it should only have "mixed_chunk" (ManyToManyField with a through model) objects associated with it. Problem However, I'm running into issues validating the ManyToManyField ("mixed_chunks") because the relationship cannot be accessed before the object is saved and receives an id. With the code below, when I test in the Admin and try to save a "D" type Evaluation object without attaching any mixed_chunks objects (this is done through an inline in the Admin), the conditional if self.mixed_chunks in my custom .clean() method for the Evaluation model evaluates as true even though I haven't selected any mixed_chunks objects, therefore raising my validation error raise ValidationError(_("Only dialogues allowed to be attached for a 'Dialogue'-type eval")). Things I've tried I've tried to print some things out to see what is going on: when I have selected some EvalMixedEvalChunkCombo objects print(self.mixed_chunks) = "evaluations.MixedEvalChunk.None" print(self.e_eval_mixed_chunk_combos) = "evaluations.EvalMixedEvalChunkCombo.None" when I have not selected some EvalMixedEvalChunkCombo objects print(self.mixed_chunks) = … -
Registration with dj rest auth
The challenge I'm facing is when registering with dj-rest-auth, an authentication component designed for Django. When a user registers, an email is automatically sent to verify their email address. The problem is that I want to customize the appearance of that email, and so far I haven't figured out how to change the default template that dj-rest-auth uses for this purpose. The default template does not fit my needs or design preferences, and I would like to replace it with one that better suits the aesthetics of my application. Basically, I'm looking for a way to modify the email template that is sent for email verification after registration, and I'm having a hard time understanding how to make this adjustment in the dj-rest-auth framework. I have checked the official documentation but nothing appears about this -
How to compute the distance matrix of many origins and destinations
I'm trying to compute the distance matrix of multiple origins and destinations in my django view. I was previously looping through the data and making individual call to the google distance matrix api and saw it was inefficient as it took too long to return the final response. Then I found out that it's possible to make a single batch request. But unfortunately, I'm not getting the desired result as expected. Here's my view below showing what I have class GetAvailableRidersView(AsyncAPIView): permission_classes = [IsAuthenticated] SEARCH_RADIUS_METERS = 10 def get_google_maps_client(self): """Initialize and return the asynchronous Google Maps API client.""" return GoogleMapsClient(key=settings.GOOGLE_MAPS_API_KEY) async def validate_parameters(self, order_location, item_capacity, is_fragile): """Validate input parameters.""" try: item_capacity = float(item_capacity) is_fragile = str_to_bool(is_fragile) except (ValueError, TypeError): return False, "Invalid or missing parameters" if not all( [ order_location is not None and isinstance(order_location, str), item_capacity is not None and isinstance(item_capacity, (int, float)), is_fragile is not None and isinstance(is_fragile, bool), ] ): return False, "Invalid or missing parameters" return True, "" def handle_google_maps_api_error(self, e): """Handle Google Maps API errors.""" return Response( {"status": "error", "message": f"Google Maps API error: {str(e)}"}, status=400, ) def handle_internal_error(self, e): """Handle internal server errors.""" logger.error(str(e)) raise Exception(str(e)) async def get(self, request, *args, **kwargs): order_location = … -
Django container can't communicate with postgres container
My Django container can't communicate with my postgres container. In my django settings file: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ.get('POSTGRES_DB', 'mydatabase'), 'USER': os.environ.get('POSTGRES_USER', 'myuser'), 'PASSWORD': os.environ.get('POSTGRES_PASSWORD', 'mypassword'), 'HOST': 'db', 'PORT': '5432', } } My docker-compose.yml: version: '3' services: db: image: postgres:latest environment: POSTGRES_DB: mydatabase POSTGRES_USER: myuser POSTGRES_PASSWORD: mypassword volumes: - data:/var/lib/postgresql/data django: build: . ports: - "8000:8000" depends_on: - db volumes: data: I can confirm that creating both containers individually works by running docker-compose up -d django and docker-compose up -d db. By "working I mean" that I see the output that the db container is being created, and I can, for example, access the website from the django container in the browser. But when I try to run migrations in the django container (as part of the django service's Dockerfile), I get 1.174 django.db.utils.OperationalError: could not translate host name "db" to address: Name or service not known Does this configuration look good to you in general? Could you think on anything that I could try? -
django.contrib.auth.views LogoutView not working
I am using latest version of django and I want to create a LogoutView using builtin system. But this is giving error when I try to run the server, and not working LogoutView. error image Below is the urls.py code. from django.contrib import admin from django.urls import path, include from users import views as user_views from django.contrib.auth import views as auth_views urlpatterns = [ path('admin/', admin.site.urls), path('food/',include('food.urls')), path('register/',user_views.register,name='register'), path('login/',auth_views.LoginView.as_view(template_name='users/login.html'),name='login'), path('logout/',auth_views.LogoutView.as_view(template_name='users/logout.html'),name='logout'), ] When I checked, I found that the error is : HTTP error code 405 stands for "Method Not Allowed." Django's LogoutView, the expected method for logout is typically POST but this is getting in terminal: "GET /logout/ HTTP/1.1" 405 0 Method Not Allowed (GET): /logout/ Method Not Allowed: /logout/ -
Redirection entre les vues generics
Salut j'ai un petit soucis. J'aimerais savoir comment quitter d'une CreateView ou UpdateView vers une DetailView. Voici mes Vues: CreateView class TeachersCreateView(CreateView): template_name = 'teachers_app/teacher_form.html' form_class = TeachersForm success_url = reverse_lazy('teachers_app:détails)) def form_valid(self, form): return super().form_valid() UpdateView: class TeachersUpdateView (UpdateView): template_name = 'teachers_app/teacher_form.html' form_class = TeachersForm success_url = reverse_lazy('teachers_app:détails)) def get_object(self, *arts, **kwargs): id_ = self.kwargs.get("pk") return get_object_or_404(Teachers,pk=id_) def form_valid(self, form): return super().form_valid () J'obtiens une erreur de type NoReverseMatch at /pk/update. Comment résoudre se problème ? Merci d'avance -
Django + HTMX - hx-get when pressing enter on an input text element only works once
happy new year. I have a small problem that I don't understand why it happens. I have the following code in a django template: <div class="input-group"> <input id="code-input" name="code-input" hx-get="{% url 'get-partial-data' %}" hx-trigger="keyup[key=='Enter']" hx-swap="outerHTML" hx-target="#partial_data" class="form-control" type="text" placeholder="Search by code"> </div> The idea is that when enter is pressed on the input, the GET request is triggered. That does happen, but only the first time. If for some reason I modify the value of the input and press enter again the request does not go out, the event is not fired. Does anyone have any idea why this could happen? -
Deploying React native app with Django API on AWS and playstore
I'm new to development. I have created a react native expo apps that uses django API. So to run app I have to do two things. Python manage.py runserver npm run Android I'm able to run my app locally. My End goal is to Deploy it on Play Store. I'm not sure how this works. I feel I will be requiring some server that is running continuously and have an ip address. AWS can be one. I'm looking forward for more insights on How this deployment can be done and steps involved in it? Thank you so much in advance. -
use celery with Django-verify-email
I am trying to setup a simple task to send email verification with the django-verify-email package and celery here is my code #task.py from celery import shared_task from verify_email.email_handler import send_verification_email @shared_task def send_user_email(request, form): inactive_user = send_verification_email(request, form) #sign_up.py from django.shortcuts import render, redirect from django.contrib import messages from .tasks import send_user_email def signup(request, form_class, template_name, success_message, redirect_url): if request.user.is_authenticated: return redirect(redirect_url) form = form_class() if request.method == 'POST': form = form_class(request.POST) if form.is_valid(): send_user_email(request, form=form) messages.success(request, success_message) return redirect(redirect_url) else: messages.error( request, f'Error creating account. Please check the form.') return render(request, template_name, {'form': form}) context = {'form': form} return render(request, template_name, context) i have this error on the task console [2024-01-03 19:08:34,231: ERROR/ForkPoolWorker-2] Task user.tasks.send_user_email[1f521272-e7e4-4ae0-8fd8-ef1e0ad551e5] raised unexpected: AttributeError("'dict' object has no attribute 'save'") Traceback (most recent call last): File "/home/foli/code/django/freeacademy/.freemindedAcademy/lib/python3.10/site-packages/celery/app/trace.py", line 477, in trace_task R = retval = fun(*args, **kwargs) File "/home/foli/code/django/freeacademy/.freemindedAcademy/lib/python3.10/site-packages/celery/app/trace.py", line 760, in __protected_call__ return self.run(*args, **kwargs) File "/home/foli/code/django/freeacademy/user/tasks.py", line 7, in send_user_email inactive_user = send_verification_email(request, form_data) File "/home/foli/code/django/freeacademy/.freemindedAcademy/lib/python3.10/site-packages/verify_email/email_handler.py", line 94, in send_verification_email return _VerifyEmail().send_verification_link(request, form) File "/home/foli/code/django/freeacademy/.freemindedAcademy/lib/python3.10/site-packages/verify_email/email_handler.py", line 32, in send_verification_link inactive_user = form.save(commit=False) AttributeError: 'dict' object has no attribute 'save' i have this over error on the web console Traceback (most recent call last): … -
Github Actions not finding pytest tests in Django project
For some reason, the Actions aren't finding any tests when I use Pytest on a Django project. If it helps, I had the tests initially using the Django testing framework and it still wouldn't find any tests. This is the django.yml `name: Django CI on: push: branches: [ "main" ] pull_request: branches: [ "main" ] jobs: build: runs-on: ubuntu-latest strategy: max-parallel: 4 matrix: python-version: [3.12] steps: - uses: actions/checkout@v3 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v3 with: python-version: ${{ matrix.python-version }} cache: 'pip' # caching pip dependencies - name: Install Dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt - name: Run Tests run: | pytest -v` The tests can be found in the main branch. There is no problem with test discovery on my local computer, the test file names follow the naming procedure. This is the pytest.ini file: [pytest] DJANGO_SETTINGS_MODULE = playlist_analyser.settings python_files = tests.py *_tests.py This is what an example of a file name looks like: PlaylistAnalyser/playlist_analyser/tests/playlist_tests.py This is what an example of a test looks like in the file (there are no errors): `@pytest.fixture def handler(): yield PlaylistHandler() #------------------ Get_Avg_Of_Attribute Tests ------------------# @pytest.mark.django_db def test_get_avg_attributes(handler): playlist_url = "https://open.spotify.com/playlist/6cUbe8r2kP140bL0Z2HHXV?si=89cbce6452b84b10" playlist … -
Django Chained select not showing up in admin panel
I'm trying to create a chained select in admin panel. In the admin panel, after selecting category in ProductAttribute, a list with associated Attributes should appear. Once Attribute is selected, the associated values from AttributeChoice should appear. my models.py: class Category(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(null=False, unique=True) ordering = models.IntegerField(default=0) is_featured = models.BooleanField(default=False) def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Category, self).save(*args, **kwargs) def __str__(self): return self.title class Meta: ordering = ['ordering'] verbose_name_plural = 'Categories' def get_absolute_url(self): return '/%s/' % (self.slug) class SubCategory(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(null=False, unique=True) ordering = models.IntegerField(default=0) is_featured = models.BooleanField(default=True) category = models.ForeignKey( Category, related_name='subcategory', on_delete=models.CASCADE ) def save(self, *args, **kwargs): self.slug = slugify(self.title) super(SubCategory, self).save(*args, **kwargs) class Meta: ordering = ['ordering'] verbose_name_plural = 'SubCategories' def __str__(self): return self.title def get_absolute_url(self): return '/%s/%s/' % (self.category, self.slug) class SubSubCategory(MPTTModel): parent = TreeForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE) title = models.CharField(max_length=50) slug = models.SlugField(null=False, unique=True) sub_category = models.ForeignKey( SubCategory, related_name='subsubcategory', on_delete=CASCADE, null=True ) create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title class Meta: verbose_name_plural = 'Sub_subcategories' class MPTTMeta: order_insertion_by = ['title'] def get_absolute_url(self): return reverse('susubcategory_detail', kwargs={'slug': self.slug}) def __str__(self): full_path = [self.title] k = self.parent while k is not None: full_path.append(k.title) k = k.apparent … -
MultipleObjectsReturned at / - Django allauth
I'm trying to make authentication to my Django app via Google using Allauth. However, django throws an error - MultipleObjectsReturned at /. Error occures in <a href="{% provider_login_url 'google' %}?next=/">Login with Google</a> Tracelog: C:\Users\user\Documents\1PROJECTS\py\OAuth-authorization-demo\venv\Lib\site-packages\allauth\socialaccount\adapter.py, line 290, in get_app apps = self.list_apps(request, provider=provider, client_id=client_id) if len(apps) > 1: raise MultipleObjectsReturned ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Local vars: SocialApp: <class 'allauth.socialaccount.models.SocialApp'> apps: [<SocialApp: Google>, <SocialApp: >] apps array is indeed longer than 1, but second object is empty and i can't find where it coming from. SOCIALACCOUNT_PROVIDERS has only one key "google". Checked SITE_ID variable, Site.object.all() has only 1 object. -
How can I test this github project?
ps-random-combo-generator-github Pen Spinning Random Combo Generator, using Django Framework & mySQL. I am interested in the hobby field of pen spinning. I have no programming knowledge, but I want to test this project. I've been trying for 2 days but I'm stuck, I try different things but eventually I get the same errors. Can you give me an idea on how I can make this project work? I would be grateful if you could suggest a path I can follow. First of all, I installed the latest versions of Python, Django and Mysql-server on my computer. I am proficient in graphic design and computer use, but since I have no knowledge of programming, I took help from chatgpt. I ran the python manage.py runserver command and it froze with the following error. "ImportError: cannot import name 'url' from 'django.conf.urls' (C:\Users\maco\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\conf\urls_init_.py)" Then I heard that the urls.py file contains old commands. (It contains """django 1.9""" information.) from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^combos/', include('randomGen.urls')), url(r'^admin/', admin.site.urls), ] I changed the content from this to this from django.contrib import admin from django.urls import include, path, re_path urlpatterns = [ path('combos/', include('randomGen.urls')), path('admin/', admin.site.urls), ] But I …