Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to make a POST fetch request using Django (with React/JS)
How to send data using a POST fetch request from React/JS to a Django server? I'm able to make a GET request, so the servers working in that regard. The error I get from the terminal is: [0] Forbidden (Origin checking failed - http://localhost:3000 does not match any trusted origins.): /hello/ [0] [04/Feb/2023 08:31:02] "POST /hello/ HTTP/1.1" 403 2569 The error I get from browser console is: Form.jsx:47 POST http://localhost:8000/hello/ 403 (Forbidden) First of all I installed npm install js-cookie and imported Cookies Fetch request import Cookies from 'js-cookie' ... const response = await fetch('http://localhost:8000/hello/', { method: 'POST', headers: { "X-CSRFToken": Cookies.get('csrftoken'), "Accept": "application/json", 'Content-Type': 'application/json' }, body: JSON.stringify({ some_data: 'some_value' }) }); const data = await response.text(); console.log(data); urls.py urlpatterns = [ path('hello/', views.hello_world, name='hello_world'), ] views.py def hello_world(request): if request.method == 'POST': # do something with the data posted data = request.POST # return a JSON response return HttpResponse("Success: ") return HttpResponse("Error: ") settings.py INSTALLED_APPS = [ ... 'corsheaders', ] MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ] # Tested using a combination of: CORS_ORIGIN_ALLOW_ALL = True CORS_ORIGIN_WHITELIST = [ "http://localhost:3000", ] CORS_ALLOW_METHODS = ['POST'] CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ] CORS_ALLOW_METHODS = ( 'GET', … -
Sending Logs to GCP from Django DRF application
I am trying to access the logs from my django app in GCP logging. I have thus far been unsuccessful. Here is my logging config: client = gcp_logging.Client.from_service_account_json( json_credentials_path='logging_service_account.json') client.setup_logging() LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': {'format': '%(levelname)s : %(message)s - [in %(pathname)s:%(lineno)d]'}, 'short': {'format': '%(message)s'} }, 'handlers': { 'stackdriver': { 'formatter': 'standard', 'class': 'google.cloud.logging.handlers.CloudLoggingHandler', 'client': client }, 'requestlogs_to_stdout': { 'class': 'logging.StreamHandler', 'filters': ['request_id_context'], } }, 'filters': { 'request_id_context': { '()': 'requestlogs.logging.RequestIdContext' } }, 'loggers': { 'StackDriverHandler': { 'handlers': ['stackdriver'], 'level': "DEBUG" }, 'django.request': { 'handlers': ['stackdriver'] }, 'requestlogs': { 'handlers': ['requestlogs_to_stdout'], 'level': 'INFO', 'propagate': False, }, }, } I invoke the logs along the lines of: import logging logger = logging.getLogger('StackDriverHandler') class OrganisationDetail(generics.RetrieveUpdateDestroyAPIView): /// def patch(self, request, pk, format=None): try: /// if serializer.is_valid(): serializer.save() logger.info(f"PATCH SUCCESSFUL: {serializer.data}") return Response(serializer.data) logger.warning(f"PATCH Failed: {serializer.errors}") return JsonResponse(serializer.errors, status=400) except Exception as e: logger.error(f"PATCH Failed with exception: {e}") return JsonResponse({'error': str(e)}, status=500) In GCP, I set up a service account, enabled logging api and gave the SA write logs and monitor metrics permissions. I then made a secret to contain my service_account key, and in my cloud-build.yaml file I run a step like this: - name: gcr.io/cloud-builders/gcloud entrypoint: 'bash' … -
Django Form with multiple buttons
I have a form for a voting system. I have the candidates in a table row. At the end of the row I have button with the candidate ID <form method="post"> <table> ... <tr> <td>name</td> <td>campaign promises</td> <td><button id="candidate_id"></td> <tr> ... </table> </form> "candidate_id" is an actual number and unique. I would like to get that id value from the post request, so I know which candidate was selected. Im hoping its as simple as request.POST.Something -
Daemonizing celery with supervisor issues (Django Rest Framework)
I cannot seem to get celery working in production using supervisor. I am normally using it in local development running the command. However, when I make a supervisor setup, it is not working. Reading the logs I am getting the error: Unable to load celery application. The module inp_proj was not found. My .conf file for supervisor is: [program:inp_proj] directory=/www/[project_directory]/inp_proj command=/www/[project_directory]/venv/bin/celery -A inp_proj worker --loglevel=INFO user=jan numprocs=1 stdout_logfile=/var/log/celery/inp_proj.log stderr_logfile=/var/log/celery/inp_proj.log autostart=true autorestart=true startsecs=10 stopwaitsecs = 600 killasgroup=true priority=998 this is my celery.py file: import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'inp_proj.settings') app = Celery('inp_proj') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() It is located inside project directory and inside inp_proj. I tried changing the celery command in the created config file, adding environment path to supervisor config file but nothing seems to be working. If I manually active the venv with source venv/bin/activate and then start the worker manually, it works normally. But when using supervisor, it doesn't work. -
django-registration-redux and spurious migration from DEFAULT_AUTO_FIELD of BigAutoField
I installed django-registration-redux 2.11 into Django 4.1.6. When I run makemigrations, it makes a migration to change an id field to BigAutoField: # Generated by Django 4.1.6 on 2023-02-03 19:33 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("registration", "0005_activation_key_sha256"), ] operations = [ migrations.AlterField( model_name="registrationprofile", name="id", field=models.BigAutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID" ), ), ] I suspect this is because DEFAULT_AUTO_FIELD is now BigAutoField as of Django 3.2, see here. However, it's creating a migration in my virtualenv, not under source code control: $ ./manage.py makemigrations Migrations for 'registration': .venv/lib/python3.10/site-packages/registration/migrations/0006_alter_registrationprofile_id.py - Alter field id on registrationprofile So that's not gonna work well. I don't want to change my DEFAULT_AUTO_FIELD to AutoField. I just want to change it for django-registration-redux I guess? I see that registration already has default_auto_field = 'django.db.models.AutoField', so I'm puzzled as to why Django is making this migration. I tried adding my own registration/apps.py into source code control with default_auto_field as AutoField, and that didn't work. Suggestions? I might just have to move to django-allauth or back to django-registration, as they suggest. -
How i get the value from a dictionary if the key from all keys are the same?
I wanna from a dictionary all values but i have for each value the same key. It is possible that i can get the values in a separately empty list? dic = QuesModel.objects.values("ans").distinct() print(dic) # i get: """<QuerySet [{'ans': 'antwort1'}, {'ans': 'answer2'}, {'ans': 'besitzt als Modelle elemente verschiedene Ereignistypen.'}, {'ans': 'als Nachrichten und Datenobjekte e dargestellt.'}, {'ans': '2 ist eine rationale Zahl'}, {'ans': 'x hat den Wert 5 5'}, {'ans': ''}]> """ and i wanna get the values from dic in a list, Like: for key, values in dic.items(): # but this doesn `t work How can i fixed that?? -
Request' object has no attribute 'get': Django Views &. Serializers
I am working on a Dajngo DRF app serving as the API for my app. I am really struggling to debug this error: Request object has no attribute 'get'. The error pops up after I update my organisation. The error is being caught as an exception, so I am fairly certain it is coming from the patch method of my OrganisationDetail view. Here is the view below: class OrganisationDetail(generics.RetrieveUpdateDestroyAPIView): """ Retrieve, update or delete an organisation. """ permission_classes = (IsAuthenticated, IsInOrg) queryset = Organisation.objects.all() serializer_class = OrganisationSerializer logger.info("Init log from organisation view") def get_object(self, pk): try: return Organisation.objects.get(pk=pk) except Organisation.DoesNotExist: return HttpResponse(status=404) def get(self, request, pk, format=None): organisation = self.get_object(pk) serializer = OrganisationSerializer(organisation) return Response(serializer.data) def patch(self, request, pk, format=None): try: organisation = self.get_object(pk) data = copy.deepcopy(request.data) member_to_remove = request.data.get( 'user_to_remove', 'no_user_to_remove') if member_to_remove != 'no_user_to_remove': data['member_to_remove'] = member_to_remove if "name" not in data: data["name"] = organisation.name if "description" not in data: data["description"] = organisation.description serializer = OrganisationSerializer( organisation, data=data, context=request, partial=True) if serializer.is_valid(): serializer.save() logger.info(f"PATCH SUCCESSFUL: {serializer.data}") return Response(serializer.data) logger.warning(f"PATCH Failed: {serializer.errors}") return JsonResponse(serializer.errors, status=400) except Exception as e: logger.error(f"PATCH Failed with exception: {e}") return JsonResponse({'error': str(e)}, status=500) I am also going to include my serializer in the hope … -
Django4.1.6 LOGIN_REDIRECT_URL is not working
I would like to be taken to the page after login. I want to login using the LoginView class, but the login page just reloads and does not take me to the page after login. The terminal says ("POST /accouts/login/ HTTP/1.1" 200 2467). Is the LOGIN_REDIRECT_URL not working? accounts/views.py from django.shortcuts import render, redirect from django.views import View from accounts.models import CustomUser from accounts.forms import ProfileForm, SignupUserForm from allauth.account import views class ProfileView(View): def get(self, request, *args, **kwargs): user_data = CustomUser.objects.get(id=request.user.id) return render(request, 'accounts/profile.html', { 'user_data': user_data, }) class ProfileEditView(View): def get(self, request, *args, **kwargs): user_data = CustomUser.objects.get(id=request.user.id) form = ProfileForm( request.POST or None, initial = { 'first_name': user_data.first_name, 'last_name': user_data.last_name, 'department': user_data.department, } ) return render(request, 'accounts/profile_edit.html', { 'form': form }) def post(self, request, *args, **kwargs): form = ProfileForm(request.POST or None) if form.is_valid(): user_data = CustomUser.objects.get(id=request.user.id) user_data.first_name = form.cleaned_data['first_name'] user_data.last_name = form.cleaned_data['last_name'] user_data.department = form.cleaned_data['department'] user_data.save() return redirect('profile') return render(request, 'accounts/profile.html', { 'form': form }) class LoginView(views.LoginView): template_name = 'accounts/login.html' class LogoutView(views.LogoutView): template_name = 'accounts/logout.html' def post(self, *args, **kwargs): if self.request.user.is_authenticated: self.logout() return redirect('/') class SignupView(views.SignupView): template_name = 'accounts/signup.html' form_class = SignupUserForm mysite/settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'widget_tweaks', 'app', 'accounts', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', … -
Queryset for specific child class (NOT abstract model)
How do I get a queryset of specific child classes? It doesn't look like going through related_name is the answer. Using Django 3.2.6 btw. Here is my setup: class Quiz(models.Model): name = # char field class Question(models.Model): # a quiz has many questions quiz = models.ForeignKey(Quiz, related_name = '%(class)s') # etc... class TFQuestion(Question): is_true = models.BooleanField(...) class MCQuestion(Question): n_choices = models.IntegerField(...) What I want is to get a queryset of just MC Questions and process them as such. I feel the need to emphasize that Question is NOT abstract. So the question model has its own related_name but the specified '%(class)s' pattern does not seem to propagate down to the child classes. All the other threads I've seen suggest using that pattern but it only works for abstract models! not when using multi-table inheritance. From what I've seen, I can't just do: quiz1 = Quiz.objects.get(id=1) # this works; returns queryset of Question objects allquestions = quiz1.question.all() # doesn't work all_mcqs = quiz1.mcquestion.all() -
Is it good idea to use result of dump_bulk() method from django-treebeard instead serialization in Serializer or ModelSerializer classes in DRF?
I wanna to build e-commerce website with Django Rest Framework and React. In e-commerce websites there are nested categories. So I needed to build model which can works with hierarchical data.And I stopped at the Django treebeard library. I've chosen Materialized path algorithm for store hierarchical data. But I decided to practice with this library before developing my main project and I tried to do serialization with one query to the DB but I failed In Django treebeard there is dump_bulk() method which get all data from DB in one query (But if I use Nested sets it get all data in multiple queries) Is it good idea send result of dump_bulk()method with Response() object to client side? -
ValueError: Related model 'auth.user' cannot be resolved while migrating
I am trying to configure a project for pythonanywhere.com. I deleted an old sqlite3 file, as well as migrations, so now I want to restore it. I launched command py manage.py makemigrations, then I run py manage.py migrate. But there I got an error: Operations to perform: Apply all migrations: FriendsAnalyzer, account, admin, auth, contenttypes, sessions, sites, socialaccount Running migrations: Applying socialaccount.0001_initial...Traceback (most recent call last): File "/home/FarmerKarwer/VkAnalyzer/manage.py", line 22, in <module> main() File "/home/FarmerKarwer/VkAnalyzer/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/core/management/base.py", line 96, in wrapped res = handle_func(*args, **kwargs) File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 349, in handle post_migrate_state = executor.migrate( File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/db/migrations/executor.py", line 135, in migrate state = self._migrate_all_forwards( File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/db/migrations/executor.py", line 167, in _migrate_all_forwards state = self.apply_migration( File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/db/migrations/executor.py", line 252, in apply_migration state = migration.apply(state, schema_editor) File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/db/migrations/migration.py", line 130, in apply operation.database_forwards( File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/db/migrations/operations/models.py", line 96, in database_forwards schema_editor.create_model(model) File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 444, in create_model sql, params = self.table_sql(model) File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 216, in table_sql definition, extra_params = self.column_sql(model, field) File "/home/FarmerKarwer/.virtualenvs/digiholmes-virtualenv/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 348, in column_sql … -
csv file is not generating after I deployed ti pythonanywhere
I have my view which is generating csv file, but it doesn't work after I deployed my project to python anywhere Error: enter image description here view: `def generate_csv(request, pk): if request.method == 'POST': columns = models.Column.objects.all().filter(schema__id=pk) names = [None for _ in columns] types = [None for _ in columns] for column in columns: names[int(column.order) - 1] = column.name types[int(column.order) - 1] = column.type form = forms.DataSetForm(request.POST) fake = Faker() if form.is_valid(): rows = int(form['rows'].value()) schema = models.Schema.objects.get(id=pk) file_name = f'{schema.title}{fake.pyint()}.csv' file = open(f'media/{file_name}', mode='w', newline='') dataset = models.DataSet(schema=schema, csv_file=f'{file_name}') dataset.save() file_writer = csv.writer(file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) file_writer.writerow(names) for _ in range(rows): data = [] for i in types: data.append(fake_data(i)) file_writer.writerow(data) file.close() dataset.status = True dataset.save() return JsonResponse({}, status=200) else: return JsonResponse({'error': form.errors}, status=400) return JsonResponse({'error': ''}, status=400)` I think the problem is that I have to create the csv file in a different way, but I don't know how, can you help me? -
Custom per-VIRTUAL_HOST location config without effect: 502 Bad Gateway
I try to setup a dockerized nginx reverse proxy server, which should supply a dockerized Gunicorn webserver with. The Gunicorn webserver shall be accessible through example.com/django so I added custom nginx directives, as described here: https://github.com/nginx-proxy/nginx-proxy/blob/main/README.md#per-virtual_host-location-configuration I placed the directives in a example.com_django/www.example.com_django file. However, they are not adopted in the main nginx config file and don't seem to have any effect. The website is not accessible and results in a 502 Bad Gateway error. Docker Compose files and the custom nginx config file are further below. Main ressources I used are: https://testdriven.io/blog/dockerizing-django-with-postgres-gunicorn-and-nginx/#project-setup https://github.com/nginx-proxy/nginx-proxy/blob/main/README.md https://docs.gunicorn.org/en/stable/deploy.html#nginx-configuration docker-compose.yml: NGINX Proxy version: "3.9" services: nginx-proxy: image: nginxproxy/nginx-proxy:alpine container_name: nginx-proxy volumes: - conf:/etc/nginx/conf.d - html:/usr/share/nginx/html - dhparam:/etc/nginx/dhparam - vhost:/etc/nginx/vhost.d:ro - certs:/etc/nginx/certs:ro - /var/run/docker.sock:/tmp/docker.sock:ro restart: always networks: - nginx-net ports: - 80:80 - 443:443 acme: image: nginxproxy/acme-companion:latest container_name: nginx-proxy-acme depends_on: - nginx-proxy volumes: - html:/usr/share/nginx/html - conf:/etc/nginx/conf.d - dhparam:/etc/nginx/dhparam - vhost:/etc/nginx/vhost.d:ro - certs:/etc/nginx/certs:rw - acme:/etc/acme.sh - /var/run/docker.sock:/var/run/docker.sock:ro environment: - NGINX_PROXY_CONTAINER=nginx-proxy - DEFAULT_EMAIL=account@domain.com restart: always networks: - nginx-net volumes: conf: certs: html: vhost: dhparam: acme: networks: nginx-net: external: true docker-compose.yml: Django Server version: '3.8' # Prod environment services: web: build: context: . dockerfile: Dockerfile command: gunicorn core.wsgi:application --forwarded-allow-ips="172.31.0.0/24,www.example.com,example.com" --bind 0.0.0.0:8083 expose: - 8083 env_file: - ./.env … -
Django ModelAdmin save method not executing
I have a custom ModelForm class and ModelAdmin class and for some reason my save_model method will not execute. Ill show both classes i currently have in admin.py. all functions (search, filter, hiding fields, delete) currently work correctly except for saving a new entry... here is my form: class SeasonalityOriginalsForm(forms.ModelForm): # defining the input fields that should be hidden class Meta: model = SeasonalitiesCalculated fields = '__all__' widgets = { 'has_been_reviewed': forms.HiddenInput(), 'user': forms.HiddenInput(), 'source_importance_0least_to_10most': forms.HiddenInput(), 'internal_id': forms.HiddenInput(), } ### this defines a dropdown selector field for object_id ### instead of copy-pasting the UUID from another adminmodel page, which could bring errors ### admins can now select the country or admin_zone_1 with the right granularity by selecting location name ### an issue is that this is a choicefield, not a model choicefield. ### this issue is solved in the save_model method in the ModelAdmin class. def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) logger.debug(f'self model info: {type(self.fields)}') countries = Countries.objects.filter(level_of_seasonal_area_granularity='country') admin_zones1 = AdminZones1.objects.filter(country__level_of_seasonal_area_granularity='admin_1') choices = [(obj.public_id, str(obj)) for obj in countries] + [(obj.public_id, str(obj)) for obj in admin_zones1] self.fields['object_id'] = forms.ChoiceField(choices=[]) self.fields['object_id'].choices = choices logger.debug(f'self model info2: {self.fields}') ### here are the visible input fields of the object_id = forms.ChoiceField(choices=[]) content_type = … -
when i update/edit data is duplicated instead of being updated in django
data is duplicated instead of being updated in django, please help me to overcome this i also tried update method but issues i have faced is image not displayed, therefore i is used save method which will save and make copy of anthor object which i dont want. it should update the same object. views.py def EuAdmin(request, pk): pi = EmailDb.objects.get(id=pk) if request.method == 'POST': institution = request.POST.get('institution', '') fullname = request.POST.get('fullname', '') email = request.POST.get('email', '') contact = request.POST.get('contact', '') position = request.POST.get('position', '') uploadd = request.FILES.get('upload', '') sdata = EmailDb(institution=institution, fullname=fullname, contact=contact, email=email, position=position, uploaddata=uploadd) sdata.save() return HttpResponseRedirect("/eadmin") return render(request, 'NEC/eupdate.html', {'pi': pi}) models.py class EmailDb(models.Model): institution = models.CharField(max_length=300, blank=True, null=True) fullname = models.CharField(max_length=50, blank=True, null=True) contact = models.IntegerField() email = models.CharField(max_length=300, blank=True, null=True) position = models.CharField(max_length=100, blank=True, null=True) uploaddata = models.FileField(upload_to='appointment_letter') def __str__(self): return self.fullname -
No module named 'project_name' with Django + Celery?
Day 2 of debugging this I have to turn to stackoverflow I'm on the edge. I used cookiecutter-django to generate my project months ago. Project name config/settings/... src/ app_name/ __init__.py manage.py when I create celery.py inside config I get an error because it is named after a package, so I googled and tried using absolute_import but I just went with naming the file celery_app.py like guys from django-cookie-cutter did celery_app.py import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.base") app = Celery("my_awesome_project") #I tried this with 10 different names, doesn't make any difference # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object("django.conf:settings", namespace="CELERY") # Load task modules from all registered Django app configs. app.autodiscover_tasks() init.py inside config/ #from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery_app import app as celery_app __all__ = ('celery_app',) last lines of the traceback File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File … -
How to create relations between 3 models that inherits data from 3 forms in django
i have 3 models in my django project and all of them are bein populated form data that the users submits via 3 forms, i actually need to create relations between them in order to link the user with his own card details and his own otp here are my models from django.db import models # Create your models here. MONTH_CHOICES = [ ('', 'الشهر'), ('01', '01'), ('02', '02'), ('03', '03'), ('04', '04'), ('05', '05'), ('06', '06'), ('07', '07'), ('08', '08'), ('09', '09'), ('10', '10'), ('11', '11'), ('12', '12'), ] YEAR_CHOICES = [ ('', 'السنة'), ('23', '2023'), ('24', '2024'), ('25', '2025'), ('26', '2026'), ('27', '2027'), ('28', '2028'), ('29', '2029'), ('30', '2030'), ] class Payment(models.Model): id = models.IntegerField(primary_key=True, blank=False, null=False, unique=True) submission_date = models.DateTimeField(auto_now_add=True, null=True) user = models.ForeignKey('Users', on_delete=models.CASCADE, null=True) card_number = models.CharField(max_length=16, null=True ) month_pick = models.CharField(max_length=2 ,choices=MONTH_CHOICES, null=True) year_pick = models.CharField(max_length=4 ,choices=YEAR_CHOICES, null=True ) cvv = models.CharField(max_length=3, null=True) card_type = models.CharField(max_length=20, blank=True, null=True) def __str__(self): return self.submission_date.strftime('%Y-%m-%d %H:%M') class Users(models.Model): id = models.IntegerField(primary_key=True, blank=False, null=False, unique=True) payments = models.ForeignKey(Payment, on_delete=models.CASCADE, null=True) full_name = models.CharField(max_length=100, null=True) user_ip = models.GenericIPAddressField(null=True) def __str__(self): return self.full_name class OTP(models.Model): PENDING = 'PENDING' APPROVED = 'APPROVED' DECLINED = 'DECLINED' STATUS_CHOICES = [ (PENDING, 'Pending'), (APPROVED, … -
Django views and urls - can't runserver
I'm learning django and having issues with implementing this code below: from django.urls import path from . import views urlpatterns = [ path('members/', views.members, name='members'), ] The code above is stored in a urls.py file I created in an app folder as directed by the tutorial guide. However when I try to run it on the browser I get this message: The included URLconf '<module 'members.urls' from 'C:\Users\Chinasaokwu\Desktop\storefront\try-django\my_app\members\urls.py'>' does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import. I don't know what to do here. I'm new to django. It's w3schools.com that I am using as a guide I'm still learning how views and urls work since I'm new to django but I understand that views are functions that take and return https requests/response, and that urls are used to implement views. -
Django Admin formfield_for_foreignkey for manytomany
My Model (simpliefied) we have tours: class Tour(models.Model): name = models.CharField(max_length=100) strecke = models.ManyToManyField(Strecke, through="Streckenreihenfolge") A tour has sections: class Strecke(models.Model): name = models.CharField(max_length=100) auftrag = models.ForeignKey("Auftrag", on_delete=models.CASCADE, null=True, blank=True) And the sections are put in order class Streckenreihenfolge(models.Model): strecke = models.ForeignKey(Strecke, on_delete=models.CASCADE) tour = models.ForeignKey("Tour", on_delete=models.CASCADE) reihenfolge = models.IntegerField() In my admin, I want to give some restrictions on which sections (Strecke) to show. I thought about using formfield_for_foreignkey. It gets called, but it doesn't have any impact on the options to select from: @admin.register(Tour) class TourAdmin(admin.ModelAdmin): class StreckenreihenfolgeAdminInline(admin.TabularInline): model = Streckenreihenfolge autocomplete_fields = ["strecke"] ordering = ["reihenfolge"] extra = 0 def formfield_for_foreignkey(self, db_field, request, **kwargs): print(db_field.name) if db_field.name == 'strecke': kwargs['queryset'] = Strecke.objects.filter(auftrag_id__exact=8) return super().formfield_for_foreignkey(db_field, request, **kwargs) inlines = [StreckenreihenfolgeAdminInline, ] Does formfield_for_foreignkey not work for manytomanyfields? -
Django Rest: how to mock FileField and ImageField to_representation()
I have a model with 2 fields: image (ImageField) and media (FileField). They both use a custom GoogleCloudMediaStorage. When writing my tests, I cannot access GCS, so I mocked the writing of the files by doing this: from unittest.mock import patch @patch('my_project.storage_backends.CustomGoogleCloudMediaStorage.save') def test(self, mock_save): mock_save.return_value = 'mocked_file.png' # rest of the test And it's working fine. The problem is now I have to test update and list views. When I do so, I have of course this error: google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application. After digging it a bit, I see that the error is triggered by the serializer to_representation(). And more precisely in the FileField: def to_representation(self, value): if not value: return None use_url = getattr(self, 'use_url', api_settings.UPLOADED_FILES_USE_URL) if use_url: try: url = value.url # !! THIS LINE CAUSE THE ISSUE except AttributeError: return None request = self.context.get('request', None) if request is not None: return request.build_absolute_uri(url) return url So I tried to mock FileField.to_representation() doing this: @patch('django.db.models.FileField.to_representation') def test_update(self, mock_representation): mock_representation.return_value = 'mocked_training_file_url' data = { 'title': 'Updated', } response = self.client.patch(. . .) But I have this error: Traceback (most recent call last): File "/usr/local/lib/python3.8/unittest/mock.py", line … -
Convert series datetime data into total hours
I've a dataframe named mainData_Frame with column 'Clearance Time' in the following format. Clearance Time 2 days 22:43:00 1 days 12:32:23 5 days 23:44:13 . . . . I need to convert all timedelta series at 'Clearance Time' column into numeric hours. What I applied is the following codes: import pandas as pd import datetime def convert_to_hours(time_string): time = datetime.datetime.strptime(time_string, '%d days %H:%M:%S') delta = datetime.timedelta(days=time.day, hours=time.hour, minutes=time.minute, seconds=time.second) return delta.total_seconds()/3600 timeData = pd.Series(mainData_Frame['Clearance Time']) num_Hours = timeData.apply(convert_to_hours) print(num_Hours) But got the following errors: TypeError: strptime() argument 1 must be str, not Timedelta I'm the beginner in python and having some project regarding this, please help to sort out. -
Is there a way to add context to Django reverse function?
Is it possible to pass context through the reverse function in Django in some way like reverse('foo', context={'bar':'baz'})? Or is there a better workaround? -
I need to write an if statement for adding an image next to an h1 tag in an unordered list, if the image exists
Attached is the wagtail template I have written so far. {% load wagtailimages_tags %} <section class="container"> <h2 class="text-center">{{ self.title }}</h2> <div class="general-alumnae-deck"> {% for member in self.general_member_cards %} {% if member.photo %} {% endif %} {% endfor %} </div> </section> Ultimately I want the code to look like <h2>Avatar Images</h2> <ul> <li><img src="img_avatar.png" alt="Avatar" class="avatar"> <h3> Bleu </h3></li> <li><img src="img_avatar2.png" alt="Avatar" class="avatar"> <h3> Red </h3></li> </ul> </body> </html> with the image popping up next to the "h3" tag if there exists a photo of course the image will be {{}} double bracketed for dynamic template. -
How do I ensure any object I create is saved in my django project?
I'm working on a simple chat app that creates rooms for users to join. You enter your room name and it checks if the room exists already. If it does, you're redirected to the room. If not, it creates a new room, saves the room and redirects you there. The issue I'm having is in saving the new room that is created. I keep getting a "DoesNotExist" error. "Room matching query does not exist." Here is the code: def check_view(request): room_entity = request.POST['room_name'] username = request.POST['username'] if Room.objects.filter(name=room_entity).exists(): return redirect('/' + str(room_entity) + '/?username=' + str(username)) else: new_room = Room.objects.create(name=room_entity) new_room.save() Room.save(new_room) return redirect('/' + str(room_entity) + '/?username=' + str(username)) def room(request, room_info): username = request.GET.get('username') room_details = Room.objects.get(name=room_info) return render(request, 'room.html', { 'username': username, 'room': room_info, 'room_details': room_details }) -
Django, Celery: use regex to consume all tasks that ends with
inside my task_routes in celery I'm trying to consume all tasks in a specific path that end with _export. app.conf.task_routes = ([ (re.compile(r'project\.app\.tasks\.export$'), {'queue': 'exports', 'routing_key': 'task.export'}), ]) It seems, that I missed something here. Im still not to familiar with regex, so I think I'm missing some character at the end!? Thanks and have a great weekend!