Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Avoid Duplicate Validation When Creating Django Model Instances Manually and via Forms?
I’m new to Django and I need some help with model validation. Here’s what I’m trying to figure out: When I create new instances using forms, I know that calling is_valid on the form automatically runs the full_clean method for validation. After that, I just call save on the form. But when I create new instances manually, I need to call full_clean manually before calling save. I saw online that some people suggest overriding the save method in the model to ensure custom validation always runs, like this: def save(self, *args, **kwargs): self.full_clean() super().save(*args, **kwargs) This works fine when I’m creating instances manually, but it seems to call full_clean twice when I use forms (once during is_valid and once during save). This feels redundant and probably not efficient. My Question: What’s the best way to make sure my custom validation runs in Django models both when creating instances manually and via forms, without calling full_clean twice? Any advice or best practices would be really appreciated! Thanks a lot! -
python django library project
i have been making libraries with many tutorials and tips but couldnt find one that really suited my project can anybody give me suggestions on it i would really apreciate where to find some proper tutorials that can show me how to make an python django library that allows me to have two roles vendor and librarian, vendor sells books can edit the names of the books and basic things like that and librarian can search up the books and find the one he/she will like well i have tried multiple tutorials which did pretty well but not up to the level i need for -
Problem connecting to BlueStacks from the Django project using ADB
1. Creating a Django project: 2. Preparation of forms (models.py): enter image description here 3. Preparation of presentations (views.py): enter image description here enter image description here enter image description here 4. Set up templates (templates/bot_controller.html): enter image description here ADB settings: adb connect 127.0.0.1:5555 adb devices CSP CORS settings.py: enter image description here The full project link: https://github.com/MoYonsei/AbotZ/tree/master Attempts to solve the problem: Made sure that ADB is working properly and BlueStacks is connected. Updated the CSP and CORS settings to allow loading the emulator inside the framework. Tried using different addresses in the iframe such as localhost and 127.0.0.1. -
Why is my AWS EC2 instance Supervisor failing?
I'm deploying a Django API I've named "ScientistBirthYear" to AWS EC2 following these instructions, including using the gunicorn.conf code, but modifying it to account for my virtual environment's name, project name, and X.wsgi:application from my project. At 24:50, the presenter's instance shows gunicorn running, where mine has failed multiple times. I've come across several solutions online, and none of them have worked. Here's the last several entries of my /var/log/supervisor/supervisord.log: 2024-07-16 22:56:07,174 INFO spawned: 'gunicorn' with pid 1861 2024-07-16 22:56:07,281 WARN exited: gunicorn (exit status 0; not expected) 2024-07-16 22:56:09,284 INFO spawned: 'gunicorn' with pid 1866 2024-07-16 22:56:09,391 WARN exited: gunicorn (exit status 0; not expected) 2024-07-16 22:56:12,396 INFO spawned: 'gunicorn' with pid 1871 2024-07-16 22:56:12,502 WARN exited: gunicorn (exit status 0; not expected) 2024-07-16 22:56:12,503 INFO gave up: gunicorn entered FATAL state, too many start retries too quickly 2024-07-16 22:56:25,588 CRIT Supervisor is running as root. Privileges were not dropped because no user is specified in the config file. If you intend to run as root, you can set user=root in the config file to avoid this message.> 2024-07-16 22:56:25,589 INFO Included extra file "/etc/supervisor/conf.d/gunicorn.conf" during parsing 2024-07-16 22:56:25,589 INFO RPC interface 'supervisor' initialized 2024-07-16 22:56:25,589 CRIT Server 'unix_http_server' … -
Testing services with django-pytest: User.DoesNotExist
I'm trying to test functions with pytest. It returns No tables found. While i see migrate output and test sqlite3 database. authentication/tests/test_services.py::test_register_user - users.models.User.DoesNotExist: User matching query does not exist. My conftest is: import os import pytest from django.core.management import call_command from rest_framework.test import APIClient from users.models import User @pytest.fixture(scope='session') def delete_db(): print("delete_db") try: os.remove("db_test.sqlite3") except Exception: pass @pytest.fixture(scope='session') def django_db_setup(delete_db, django_db_blocker): print("django_db_setup") with django_db_blocker.unblock(): call_command('sqlflush') with django_db_blocker.unblock(): call_command('migrate', '--noinput') yield @pytest.fixture(autouse=True, scope='session') # def user(data, django_db_blocker): def user(django_db_setup, django_db_blocker): with django_db_blocker.unblock(): user = User.objects.create( name='Test user', email='test@eaxmple.com', password='Password' ) @pytest.fixture(autouse=True, scope='session') def guest_client(): return APIClient() @pytest.fixture(autouse=True, scope='session') def user_client(guest_client, django_db_blocker): with django_db_blocker.unblock(): client = APIClient() user = User.objects.get(email='test@example.com') response = guest_client.post('/api/v1/auth/login/', data={"email": user.email, "password": "Adminqwe1,"}) token = str(response.json().get("access")) client.credentials(HTTP_AUTHORIZATION="Bearer " + token) return client Test user from fixture is created my test file is: import pytest from authentication.services import register_user @pytest.mark.django_db() def test_register_user(guest_client): data = {'email': 'test1@example.com', 'name': 'Test user', 'password': 'Adminqwe1.'} user = register_user(data=data) assert user.name == 'Test user' assert user.check_password('Admninqwe1.') is True tested function: from users.models import User def register_user(data): password = data.pop("password") user = User.objects.create(**data) user.set_password(password) user.save() return user settings_test: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db_test.sqlite3', } } pytest.ini: [pytest] DJANGO_SETTINGS_MODULE … -
Vuetify2 styles not working properly with Django
I'm trying to add vue + vuex + vuetify framework to my django project I have installed node.js and yarn, then prescribed the commands - yarn global add @vue/cli and vue create client in project root dir, and modified the config files: package.json { "name": "client", "version": "0.1.0", "private": true, "scripts": { "serve": "vue-cli-service serve", "build": "vue-cli-service build", "dev": "vue-cli-service build --dest=../../static/builds/dev --mode=development --watch" }, "dependencies": { "axios": "^0.21.4", "copy-to-clipboard": "^3.3.1", "core-js": "^3.6.5", "vue": "^2.6.11", "vue-modal-dialogs": "^3.0.0", "vue-router": "^3.2.0", "vuedraggable": "^2.24.3", "vuetify": "2.6.5", "vuex": "^3.4.0" }, "devDependencies": { "@vue/cli-plugin-babel": "~4.5.0", "@vue/cli-service": "~4.5.0", "sass": "~1.32.0", "sass-loader": "^10.0.0", "vue-cli-plugin-vuetify": "~2.4.2", "vue-template-compiler": "^2.6.11", "vuetify-loader": "^1.7.0" } } main.js import Vue from 'vue' import App from './App.vue' import router from './router' import store from './store' import vuetify from './plugins/vuetify' Vue.config.productionTip = false new Vue({ router, store, vuetify, render: h => h(App) }).$mount('#app') vuetify.js import Vue from 'vue' import Vuetify from 'vuetify/lib/framework' import ru from 'vuetify/es5/locale/ru' import "vuetify/dist/vuetify.min.css"; Vue.use(Vuetify); export default new Vuetify({ lang: { locales: {ru}, current: 'ru' } }); then I ran the yarn dev command and plugged the assembled files into the existing html from static <script defer="defer" src="{% static 'builds/dev/js/app.js'%}"></script> <div class="tab-pane fade" id="structure-tab-content" role="tabpanel" aria-labelledby="structure-tab"> <div id="app"></div> </div> But vuetify … -
Error When Publishing to LinkedIn via API - Code: 422
I'm encountering an error when publishing to LinkedIn via their API. Here are the details: Error code: 422 Response: { "message": "ERROR :: /author :: \"urn:li:person:aba2390d-7792-4cb2-ad6b-e116d9783606\" does not match urn:li:company:\\d+|urn:li:member:\\d+\n", "status": 422 } Context Request type: POST API URL: https://api.linkedin.com/v2/ugcPosts Payload: { "author": "urn:li:person:aba2390d-7792-4cb2-ad6b-e116d9783606", "lifecycleState": "PUBLISHED", "specificContent": { "com.linkedin.ugc.ShareContent": { "shareCommentary": { "text": "Here is the content of my post." }, "shareMediaCategory": "ARTICLE", "media": [ { "status": "READY", "originalUrl": "https://www.example.com/article", "title": { "text": "Example Article" } } ] } }, "visibility": { "com.linkedin.ugc.MemberNetworkVisibility": "PUBLIC" } } Here is my code: def linkedin_login(request): auth_url = f"https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id={settings.LINKEDIN_CLIENT_ID}&redirect_uri={settings.LINKEDIN_REDIRECT_URI}&scope=w_member_social" return redirect(auth_url) def linkedin_callback(request): if 'error' in request.GET: error = request.GET.get('error') error_description = request.GET.get('error_description') return render(request, 'error.html', {'error': error, 'description': error_description}) code = request.GET.get('code') if not code: return render(request, 'error.html', {'error': 'No code provided'}) # Exchange the code for a token token_url = 'https://www.linkedin.com/oauth/v2/accessToken' data = { 'grant_type': 'authorization_code', 'code': code, 'redirect_uri': settings.LINKEDIN_REDIRECT_URI, 'client_id': settings.LINKEDIN_CLIENT_ID, 'client_secret': settings.LINKEDIN_CLIENT_SECRET } response = requests.post(token_url, data=data) if response.status_code != 200: return render(request, 'error.html', {'error': 'Failed to obtain access token', 'description': response.text}) token_data = response.json() access_token = token_data.get('access_token') expires_in = token_data.get('expires_in', 3600) # default to 1 hour if not provided # Generate a unique identifier for this token linkedin_id = … -
Connect Django to Docker MS SQL
I have requirements: Python 3.11.9 ( Windows https://github.com/pyenv/pyenv ) latest version of Django (5.0.7.) MS SQL 2019 To create a simple REST app with Django AUTH logic. As I have local installed Python and the packages in .env folder I use MS SQL 2019 in Docker. The app works if I use default default SQLite DB engine. After changing it to mssql-django (https://pypi.org/project/mssql-django/) I get: django.db.utils.InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)') requirements.txt asgiref Django django-cors-headers djangorestframework djangorestframework-simplejwt PyJWT pytz sqlparse python-dotenv pyodbc mssql-django .env DB_HOST=localhost DB_PORT=1433 DB_USER=mssql DB_NAME=friendly_beaver DB_PASSWORD=admin(!)pass settings.py DATABASES = { 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': BASE_DIR / 'db.sqlite3', 'ENGINE': 'mssql', 'NAME': os.getenv('DB_NAME'), 'USER': os.getenv('DB_USER'), 'PASSWORD': os.getenv('DB_PASSWORD'), 'HOST': os.getenv('DB_HOST'), 'PORT': os.getenv('DB_PORT'), 'OPTIONS': { 'driver': 'ODBC Driver 19 for SQL Server', }, } } Docker is up and running (https://hub.docker.com/r/microsoft/mssql-server): docker run -e "ACCEPT_EULA=Y" -e "MSSQL_SA_PASSWORD=admin(!)pass" -p 1433:1433 -d mcr.microsoft.com/mssql/server:2019-latest Any assist would be grateful. -
How to Properly Handle Character Encoding in Django Database Dump?
I'm working on a Django project and I've encountered a character encoding issue when dumping my sqlite3 database to a JSON file. The database contains special characters such as accented letters (e.g., "França", "Bélgica"), but when I dump the data, these characters are not displayed correctly. Im trying to migrate the data from sqlite3 to MySQL. Currently, my dump file contains incorrectly encoded characters like: "França" instead of "França" "Bélgica" instead of "Bélgica" "EslovÛnia" instead of "Eslovênia" "Ge¾rgia" instead of "Geórgia" Could someone please guide me on how to ensure the Django dumpdata command creates a JSON file with the correct UTF-8 encoding from the start? When i execute the commando: python manage.py dumpdata > db_data.json, my JSON is shown as "UTF-16 LE" Here are the steps I've taken so far: I've ensured my database (MySQL) is set to UTF-8 encoding. I've tried using Python scripts to manually fix the encoding issues after dumping the data, but the problem persists. My goal is to have the JSON dump file correctly display all characters. -
Problems with changing the status from pending to rejected/approved
Okay, so I am a django developer but also I am beginner I do not know much about js but I tried to submit the data with clicking on the button The project is about approve or reject orders in the panel of the owner of the shop Things in django admin went well and I can change it through the admin interface, but I also want it to be user friendly so the owner of the shop can approve the request by clicking on approve and reject it by clicking on the cancel button. In conclusion, i want to make a logic that whenever the owner click on approve button the pending in the database changes to approved and the same for reject When I click on the button(reject or approval) it gives me 405 error My views.py: def update_appointment_status(request: HttpRequest): timeslice_id = request.GET.get('timeslice_id') status = request.GET.get('status') timeslice = get_object_or_404(TimeSlice, id=timeslice_id) if status == 'approve': timeslice.approve() elif status == 'refuse': timeslice.refuse() return JsonResponse({'success': True}) My js codes: $(document).ready(function() { // Approve button click handler $('.approve-btn').click(function(event) { event.preventDefault(); var timesliceId = $(this).data('id'); $.ajax({ url: '/approve/', // Adjust the URL to your specific endpoint type: 'POST', data: { 'timeslice_id': timesliceId, 'csrfmiddlewaretoken': … -
How to Upload songs in python/django MYsql or Sqlite .?
I want to upload a Media like Song , Video , and other media file on my music player app how can store in my django project file called "model.py" what data type should i give to store that king of files i want to store the file in my database in backend to store the songs comming or requesting from user how can i upload the songs -
Prevent duplicates when filtering on prefetch_related
I have two models: Seller and Product. Each product has a foreignKey to a seller. So each product only has one seller, but a seller can be related to many products. This is the ForeignKey in my Product-Class: seller = models.ForeignKey( Seller, on_delete=SET_NULL, null=True, related_name="products", ) Now I try to query all Sellers and have the related products for each seller with them. sellers = ( Seller.objects.filter( ..doing some filtering ).prefetch_related("products").filter(products__branch=current_branch) ) By doing this, my sellers has multiple entries for many sellers as I am filtering on the prefetche_related products resulting in a join inside the database-query. What would be the best way to end up with a List of Sellers, each of them having their list of products with them? Without duplicates. I still need to filter on the products as I don't want all the products to be queried. -
Django - get value of a form textinput on onchange event
I am using this to get the ID and the value of a select item in a form in django with the onchange event: class forms_bdc(forms.ModelForm): [...] bdc_description_1 = forms.ModelChoiceField( widget=forms.Select(attrs={'id': 'editable-select-2','onchange': 'populate_selected_product(this.id,this.value)'}),empty_label=None ) I am trying to do the same with a TextInput widget. The ID is returned as expected but I don't know how to get the value : bdc_quantity_1 = forms.CharField( widget=forms.widgets.TextInput(attrs={'onchange':'calculate_price_of_product(this.id,this.value)'})) I also tried with this.text instead of this.value but no success. Thanks -
How to show/hide a button by comparing if logged by asset owner check database privilege asset owner whether add asset value is 'on' or 'off'
My asset_list html is like this {% if user_role == 'admin' %} {% include 'asset_mng/admin_sidebar.html' %} {% elif user_role == 'asset_owner' %} {% include 'asset_mng/asset_owner_sidebar.html' %} {% endif %} <div class="right"> <div class="search-container"> <input type="text" id="searchInput" placeholder="Search by AssetName..." aria-label="Search"> <button class="add-button" aria-label="Add Asset" id="addUserButton"><i class="fas fa-plus"></i> Add</button> </div> login database is like this , with roles admin and user class UserDetails(models.Model): username = models.CharField(max_length=100, unique=True) password = models.CharField(max_length=100) # Ideally, this should be hashed role = models.CharField(max_length=45) login view.py def asset_login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request,username=username,password=password) try: user = UserDetails.objects.get(username=username, password=password) if user is not None: request.session['username'] = user.username request.session['role'] = user.role #pass the user's role to the template if user.role == 'admin': return redirect('admin_dashboard') elif user.role == 'head': return redirect('head_dashboard') elif user.role == 'asset_owner': return redirect('asset_owner_dashboard') elif user.role == 'ciso': return redirect('ciso_dashboard') else: messages.error(request, 'Unknown user role') else: messages.error(request, 'Invalid username or password') except UserDetails.DoesNotExist: messages.error(request, 'Invalid username or password') return render(request, 'asset_mng/asset_mng.html') views for asset list def asset_list(request): users = Asset_Table.objects.all() return render(request, 'asset_mng/asset_pro.html', {'users': users}) I have 2 roles Admin and User , when Admin is logged in, I want to show admin side bar and if user … -
Trying to implement Google login on my django-restframework - Vue app but keep getting redirect_uri_mismatch
Title is self explanatory. I have tried every which way to take a crack at this, but kept getting the same error, no matter what I tried for days. Troubleshooting has been difficult due to me not being able to check exactly what redirect_uri string is being passed to the google's endpoint. I figured I would ask here in the hopes that someone else had a similar issue and figured it out. Vue-side: using vue3GoogleLogin main.ts: import vue3GoogleLogin from 'vue3-google-login' ... const clientId = import.meta.env.VITE_VUE_APP_GOOGLE_CLIENT_ID; app.use(vue3GoogleLogin, {clientId: clientId}); SignIn.vue: ... <GoogleLogin :callback="callback"> <button class="btn btn-flex flex-center btn-light btn-lg w-100 mb-5"> <img alt="Logo" :src="getAssetPath('media/svg/brand-logos/google-icon.svg')" class="h-20px me-3" /> Continue with Google </button> </GoogleLogin> ... const callback = (response) => { // This callback will be triggered when the user selects or login to // his Google account from the popup console.log("Handle the response", response); // const googleUser = decodeCredential(response.credential); // console.log(googleUser); const jwtToken = axios.post('http://127.0.0.1:8000/dj-rest-auth/google/',{ code: response.code }); console.log(jwtToken); } return { onSubmitLogin, login, submitButton, getAssetPath, callback }; }, }); </script> console.log(response.code) shows the Authorization code that is returned by google. Django-side: using allauth, dj-rest-auth among others Google settings (client_id, secret) are not present in the settings.py, but rather in the DB. … -
Enter a valid date. at BC/AD field in django framework
Here is the code I'm using: class BCEDateField(models.DateField): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def from_db_value(self, value, expression, connection): if value: if value.endswith('BC'): # Parse the BC date string and convert it to a negative year year, month, day = map(int, value[:-2].split('-')) return models.DateField().from_string(f"{-year:04d}-{month:02d}-{day:02d}") else: # Parse the CE date string directly return models.DateField().from_string(value) return value def to_python(self, value): if isinstance(value, str): if value.endswith('BC'): # Parse the BC date string and convert it to a negative year year, month, day = map(int, value[:-2].split('-')) return models.DateField().from_string(f"{-year:04d}-{month:02d}-{day:02d}") else: # Parse the CE date string directly return models.DateField().from_string(value) return value def get_prep_value(self, value): if value: if value.year <= 0: # Convert the negative year to a BC date string year, month, day = value.year * -1, value.month, value.day return f"{year:04d}-{month:02d}-{day:02d}BC" else: # Convert the CE date to a string return value.strftime("%Y-%m-%d") return value BUT IT SHOWS AN ERROR: Enter a valid date. -
How can i pass build model in deepface library?
I am using face recognition library deepface,and using find method for identify images i need to pass prebuild model to that method but it is not working can any one explain how can i do that? output2 = DeepFace.find(img2,img1_path,model_name=model_name) -
Error in PyCharm: Package requirement 'Django==5.0.7' is not satisfied
I'm trying to set up a Django project in PyCharm, but I keep encountering the following error: Package requirement 'Django==5.0.7' is not satisfied I have already tried the following steps: Ensured that Django==5.0.7 is listed in my requirements.txt file. pip install -r requirements.txt Verified that my virtual environment is activated Despite these efforts, PyCharm still doesn't recognize the installed Django package. Here are some additional details: PyCharm version: 2023.3.2 Python version: 3.10.1 OS: Windows 10 What could be causing this issue, and how can I resolve it? -
Django huey task not giving a result
I have created a task and I want to wait on its completion. However, for some reason I don't get a task result. I only get None. from django_huey import db_task, on_startup, signal, task @task(queue='test_q') def add_numbers(a, b): return a + b res = add_numbers(1, 2) print(res) In the example above, res will be None. Therefore, I can't use res.get(blocking=True) to wait on the task. This is my queue: 'test_q': { 'huey_class': 'huey.RedisHuey', 'immediate': False, 'results': False, 'connection': { 'url': '<>' }, 'consumer': { 'workers': 4, 'worker_type': 'thread', }, } The add_numbers task does get executed in the task. What could be the problem? -
DRF error serializing many to many relation
The error occurs after inserting the DetallePedido record, the serializer is looking for the fields 'producto' and 'cantidad'. And it receives a Producto object and an integer (cantidad) and it is looking for the field 'producto' inside the Producto object, that's why the error occurs. And at the end of the create() function it sends the Pedido object with the empty detalles_pedido attribute which is where the DetallePedido records should be stored. Any idea how to fix it? error: Got AttributeError when attempting to get a value for field producto on serializer DetallesPedidoSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Producto instance. Original exception text was: 'Producto' object has no attribute 'producto'. models.py class Producto(models.Model): nombre = models.CharField(max_length=100, blank=False, default='') precio = models.DecimalField(max_digits=6, decimal_places=2) coste_envio = models.DecimalField(max_digits=6, decimal_places=2) def __str__(self): return self.nombre class Pedido(models.Model): ESTADOS = { 'pendiente': 'Pendiente', 'pagado': 'Pagado', 'enviado': 'Enviado', 'entregado': 'Entregado', } cliente = models.ForeignKey(User, on_delete=models.CASCADE) direccion = models.CharField(max_length=300) fecha_creacion = models.DateTimeField(auto_now_add=True) estado = models.CharField(max_length=10, choices=ESTADOS, default=ESTADOS['pendiente']) detalles_pedido = models.ManyToManyField(Producto, through='DetallePedido') def save(self, *args, **kwargs): super().save(*args, **kwargs) def __str__(self): return f'Pedido {self.id} - {self.cliente}' class DetallePedido(models.Model): pedido = models.ForeignKey(Pedido, on_delete=models.CASCADE) producto = models.ForeignKey(Producto, on_delete=models.CASCADE) cantidad = models.PositiveIntegerField() … -
Django Admin Page - Create a link to list of objects, filtered by foreign key
i am learning Django right now and still struggling with it. I have two models: Database and DatabaseUser, linked with a foreign-key. In the admin page, I want to add a link to the list with databases, that directs me to a list with database-users of that specific database. Python: 3.9; Django: 4.2.13 # models.py class Database(models.Model): datenbank_name = models.CharField(max_length=300) datenbank_art = models.CharField(max_length=100) # ... (omitted some attributes) def __str__(self): return self.datenbank_name class DatabaseUser(models.Model): datenbank = models.ForeignKey(Database, on_delete=models.CASCADE) user_name = models.CharField(max_length=300) # ... (omitted some attributes) def __str__(self): return self.user_name My admin models are looking like this: # admin.py class PasswordInput(forms.ModelForm): passwort = forms.CharField(widget=forms.PasswordInput()) class DatabaseAdmin(admin.ModelAdmin): form = PasswordInput fieldsets = [ ("Allgemein", {"fields": ["datenbank_name", "datenbank_art", "kunde", "host", "port"]}), ("Anmeldeinformationen", {"fields": ["user_name", "passwort"]}), ] list_display = ["datenbank_name", "kunde", "datenbank_art", "port", "erreichbar"] admin.site.register(Database, DatabaseAdmin) class DatabaseUserAdmin(admin.ModelAdmin): form = PasswordInput fieldsets = [ ("Datenbank", {"fields": ["datenbank"]}), ("Anmeldeinformationen", {"fields": ["user_name", "passwort"]}), ("Datenbank-Rechte", {"fields": ["rechte"]}), ] list_filter = ["datenbank"] list_display = ["user_name", "rechte", "datenbank"] admin.site.register(DatabaseUser, DatabaseUserAdmin) Now I have tried couple of things and found 2 very similar questions on Stack Overflow. However i couldn't get them to work in my code. The second one is not creating a link to the list of … -
'AnonymousUser' object has no attribute '_meta' in Login view
with custom AuthenticationForm get error when trying login with a non-existent account but when use existent account error dont raise File "C:\python\CTFp\.venv\Lib\site-packages\django\utils\functional.py", line 253, in inner return func(_wrapped, *args) ^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'AnonymousUser' object has no attribute '_meta' forms.py class AuthenticationForm(BaseAuthenticationForm): def clean(self): username = self.cleaned_data.get("username") password = self.cleaned_data.get("password") ogg = User.objects.filter(Q(email=username) or Q(username=username)).first() if ogg is not None and password: self.user_cache = authenticate( self.request, username=ogg.username, password=password ) if self.user_cache is None: raise self.get_invalid_login_error() else: self.confirm_login_allowed(self.user_cache) return self.cleaned_data urls.py urlpatterns = [path('signin', views.LoginView.as_view(authentication_form=forms.AuthenticationForm), {'template_name': 'users/signin.html'}, name='signin'),] models.py class User(AbstractUser): challenges = models.ManyToManyField(Challenge) tried to change auth form to base AuthenticationForm and error dont raises. -
How many vps do i need for angular apps,django and mysql
I have a project that contains web apps and a django backend and mysql db Mydomaine.com Admin.mydomaine.com Mydomaine.com/company/workAndDevis CompanyAdmin.Mydomaine.com All of these are angular apps I'm a little bit confused how many vps to use and how much resource for these vps Some times i say I'll make em all ubuntu server 4vCores with 4G ram. some times 2vCores with 2 G ram. I need help to decide my required resources -
ValueError('JSON string "{0}" is not valid json. {1}'.format(json_str, err)) ValueError: JSON string "{" is not valid json [closed]
I have a serviceAccountKey.json file with the following code { "type": "service_account", "project_id": "...", "private_key_id": "...", "private_key": "-----BEGIN PRIVATE KEY-----...", "client_email": "...", "client_id": "...", "auth_uri": "...", "token_uri": "...", "auth_provider_x509_cert_url": "...", "client_x509_cert_url": "...", "universe_domain": "..." } All this information is, of course, filled in when I downloaded the file from firebase console for my project. I keep getting this error message. \ raise ValueError('JSON string "{0}" is not valid json. {1}'.format(json_str, err)) ValueError: JSON string "{" is not valid json. Expecting property name enclosed in double quotes: line 1 column 2 (char 1) The error seems to be coming from the line json_data = json.loads(json_str) from the init.py file in firebase admin in the "lib" sub directory of my virtual environment. I am using python 3.6. I looked at different solutions online, but none of them answered my question. Thanks for any help. -
Django test database configuration for unittest
I am running unittest with coverage command but having trouble with test database interaction. Here is my code snippet. from django.test import TestCase from myapp.models import Animal class AnimalTestCase(TestCase): def setUp(self): Animal.objects.create(name="lion", sound="roar") Animal.objects.create(name="cat", sound="meow") def test_animals_can_speak(self): """Animals that can speak are correctly identified""" all_animals = Animal.objects.all() print(all_animals) If I run this code and try to print all animals in the database, it only prints the animals in the real database and not print for Animals like lion and cat. I think this might be related to the database configuration I tried to use this configuration in the settings.py. from django.test import override_settings @override_settings(DATABASES={ "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": "db.sqlite3", "TEST": { "ENGINE": "django.db.backends.sqlite3", "NAME": "test.sqlite3", } }, "read_replica": { "ENGINE": "django.db.backends.sqlite3", "NAME": "db.sqlite3", "TEST": { "ENGINE": "django.db.backends.sqlite3", "NAME": "test.sqlite3", } }, }) but this is still not working. My expectation is to interact with test database so based on my code snippet, I want to print lion and cat.