Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Processing process and UniqueConstraint Django
I did model with constraints: class DiscountSchema(models.Model): ... class Meta: verbose_name = "DiscountSchema" constraints = [ constraints.UniqueConstraint( fields=( "level", "level_value", "discount_rate", "background_col", "foreground_col", "loyalty_card", ), violation_error_message="UNIQUEERROR", name="Uniqueschema", ) ] How can I process this constraints when I create instance in serializer? Now I have: try: serializer.is_valid(raise_exception=True) return serializer.save() except IntegrityError as e: if "Uniqueschema" in e.args[0]: pass else: raise e Is there better way? -
How to design a separate authentication server using the ROPC OAuth2 flow?
I have to implement a separate authentication server using OAuth. The tech-stack that I am using is django and graphQL. As I am maintaining a separate server for authentication, I have created two django projects that run on two different ports, one for the authentication and the other as a resource server to perform CRUD operations on the user model. But since I have to authenticate the user using username and password and should issue access tokens, should I define the 'user' model in the project module which is dedicated for the authentication server? But if I am creating the 'user' model on the authentication server side, every time when the user requests for some information, my resource server needs to make a request to the authentication server to get that information. Is this a common practice? I have tried creating views in my authentication server, as in '/register' and '/verifytoken'. The resource server will place POST requests to these views using graphQL while registering the user and also while trying to access aa protecrted resource to verify the access token. But since I am using /register and /verifytoken routes, does it come under using REST API? If yes, how … -
Django models migration gives an error on a table that does not exist
I am making a project using Django with Django models (SQLite). I applied some changes to my models but when migrating it was giving me the following error: ValueError: Field 'id' expected a number but got 'FAL'. I commented out the changes and tried to re-migrate however despite I removed the changes it still gives me the same error. This is my models.py (including the commented out changes): from django.db import models from django.utils import timezone # Create your models here. # BOROUGHS = [ # ("GRE", "Greenwich"), # ("BEX", "Bexley"), # ("LEW", "Lewisham"), # ("HOM", "Homerton"), # ("OOB", "Out of borough") # ] # SPECIALITIES = [ # ("CAR", "Cardiology"), # ("COE", "Geriatric"), # ("PED", "Paediatric"), # ("ONC", "Oncology"), # ("ORT", "Orthopaedic"), # ("NEU", "Neurology"), # ("RES", "Respiratory") # ] # REASONS = [ # ("FAL", "Fall"), # ("NEU", "Neuro"), # ("GEN", "Generally unwell"), # ("MEH", "Mental health"), # ("ORT", "Orthopaedic"), # ("RES", "Respiratory") # ] # LOCATION = [ # ("HOM", "Home"), # ("WAR", "Ward"), # ("ICB", "Rehab unit"), # ("PLC", "Placement") # ] # class Doctor(models.Model): # name: models.CharField(max_length=50) # speciality: models.CharField(max_length=50, default="COE") # class AdmissionReason(models.Model): # reason: models.CharField(max_length=50, default="FAL") # class Borough(models.Model): # Borough: models.CharField(max_length=20, default="GRE") … -
Django context processor code not working
I am trying to use context_processors.py to show the number of unread_messages on my base.html message icon, but for some reason it is not working. While the unread_message counter is working for the user_messages_view properly, it just won't work for base.html. I tried changing the logic of my context_processors.py, but same result. So my models.py: class Message(models.Model): sender = models.ForeignKey(CustomUser, related_name='sent_messages', on_delete=models.CASCADE) recipient = models.ForeignKey(CustomUser, related_name='received_messages', on_delete=models.CASCADE) business = models.ForeignKey(Business, related_name='messages', on_delete=models.CASCADE, null=True) content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) is_read = models.BooleanField(default=False) def __str__(self): return f'Message from {self.sender} to {self.recipient} in {self.business}' @property def sender_is_business(self): return self.sender.business.exists() @property def recipient_is_business(self): return self.recipient.business.exists() My views.py: @login_required def user_messages_view(request): businesses = Business.objects.filter( Q(messages__sender=request.user) | Q(messages__recipient=request.user) ).distinct() user_messages = [] latest_messages = [] for business in businesses: if request.user == business.seller: # Query messages for business with other users messages = Message.objects.filter( Q(sender=business.seller) | Q(recipient=business.seller) ).filter(business=business).order_by('-timestamp') for user, chat in itertools.groupby(messages, lambda m: m.recipient if m.sender == request.user else m.sender): last_message = next(chat) unread_count = Message.objects.filter(recipient=business.seller, sender=user, business=business, is_read=False).count() user_messages.append({ 'business': business, 'last_message': last_message, 'user': user, 'unread_count': unread_count, }) latest_messages.append(last_message) else: last_message = Message.objects.filter( Q(sender=request.user, recipient=business.seller) | Q(sender=business.seller, recipient=request.user) ).filter(business=business).order_by('-timestamp').first() unread_count = Message.objects.filter(recipient=request.user, sender=business.seller, is_read=False).count() user_messages.append({ 'business': business, 'last_message': last_message, 'unread_count': unread_count, }) … -
Django IntegrityError: How to handle ForeignKeyViolation in a delete view?
I’m facing an issue when trying to delete records in Django. I have a delete function for companies, but sometimes I encounter an IntegrityError if the company has related records in another table. I tried handling the IntegrityError, but it doesn’t help—the error occurs after the try-except block and results in a 500 error. Here’s my code: @login_required(login_url=reverse_lazy('autintification')) def delete_cp_company(request): db_name = LOCAL_DB if DEBUG else request.get_host().split(".")[0] cp_company_ids = json.loads(request.POST.get('cp_company_ids')) no_del = [] for ids in cp_company_ids: company = CP_company_for_pattern.objects.using(db_name).get(id=ids) print('id', ids) try: company.delete() except: no_del.append({ 'id': company.id, 'name': company.com_name, }) return JsonResponse(data={'no_delete': no_del}) Here’s the JavaScript that sends the delete request: function delete_cp_company() { let check_box = $('.cp_company_list_block .check_for_choose_item'); let ids_to_delete = []; for (let i = 0; i < check_box.length; i++) { if (check_box[i].checked) { let deleted_tr = $(check_box[i]).closest('tr'); let deleted_tr_id = deleted_tr.data("id"); ids_to_delete.push(deleted_tr_id); } } $.ajax({ url: "/delete_cp_company", method: "POST", data: { cp_company_ids: JSON.stringify(ids_to_delete), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), }, enctype: "multipart/form-data", dataType: 'json', success: function (data) { processCompanyDelete(ids_to_delete, data.no_delete) }, error: function (xhr, status, error) { console.error('AJAX Error: ' + status + ' - ' + error); }, }); } I tried handling the IntegrityError in the try-except block, but the error still causes a 500 response. I also … -
Django Form using fields from multiple models
I have the following in my models.py from django.db import models # Create your models here. class DPlaces(models.Model): restaurant = models.CharField(blank=False, unique=True, max_length=50) def __str__(self): return self.restaurant class DEntry(models.Model): place = models.ForeignKey(DPlaces, on_delete=models.CASCADE) e4date = models.DateField(blank=False) I have the following in my forms.py from django import forms from .models import DEntry, DPlaces class DEntryFilterForm(forms.Form): place = forms.ModelMultipleChoiceField( queryset=DPlaces.objects.all(), widget=forms.SelectMultiple(attrs={'class': 'form-control'}), required=False, ) e4date = forms.ModelMultipleChoiceField( queryset=DEntry.objects.order_by().values_list('e4date', flat=True).distinct(), widget=forms.SelectMultiple(attrs={'class': 'form-control'}), required=False, ) def __init__(self, *args, **kwargs): super(DEntryFilterForm, self).__init__(*args, **kwargs) self.fields['place'].queryset = DPlaces.objects.all() self.fields['e4date'].queryset = DEntry.objects.values_list('e4date', flat=True).distinct() in my views.py file I have def entrytable_view(request): data_entries = DEntry.objects.all() filtered_entries = None if request.method == 'GET': form = DEntryFilterForm(request.GET) if form.is_valid(): # Do Something The form works and form.is_valid returns true if a choice on 'place' field is selected but fails and form.is_valid returns false if a choice on 'e4date' field is selected. I suspect this is because the e4date field is not on the DPlaces model (it is on the DEntry model), but I am not sure. I any case, I am clueless on how to get this working. Any help is appreciated. -
How to manage multiple formset in Django with JavaScript
I have the following problem: I'm loading a form(Form A "Evento") for the User of application fill, in that Form I have to load dynamically another form(Form B "Logistica"), so that the User can add several Form B just clicking the button. I managed to load dynamically these Logistica/Form B for the User, but when I go to the saving part I only managed to receive the fields in a tuple, for example the Form B has a field called "nome", instead of receiving N FormB "nome" fields, I receive only 1 with a [] with the values of each Form. I realize that Django is thinking that instead of N FormB, I have only 1 FormB and it is concatenating the fields Problem https://github.com/ian-santos-nascimento/Django-event-management This is my form <form method="post" role="form" action="{% url 'evento_create' %}"> {% csrf_token %} <div class="form-group"> <label for="{{ form.nome.id_for_label }}">Nome</label> {{ form.nome }} </div> <div class="form-group"> <label for="{{ form.descricao.id_for_label }}">Descrição</label> {{ form.descricao }} </div> <div class="form-group"> <label for="{{ form.observacao.id_for_label }}">Observação</label> {{ form.observacao }} </div> <div class="row"> <div class="col"> <label for="{{ form.local.id_for_label }}">Local</label> {{ form.local }} </div> <div class="col"> <label for="{{ form.local.id_for_label }}">Cliente</label> {{ form.cliente }} </div> </div> <div class="form-group mt-3"> <label>Comidas</label> <div style="height: 30vh;overflow-y: scroll; … -
Simple JWT says sometimes "Token is invalid or expired" and sometimes gives correct output
I have a Django REST backend configured Simple-JWT solution. About 2/3 of the requests return # {"detail":"Given token not valid for any token type","code":"token_not_valid","messages":[{"token_class":"AccessToken","token_type":"access","message":"Token is invalid or expired"}]} and the rest returns the normal outcome. e.g. these curls I did directly one after another and the first fails while the second (same access token) returns a right value: C:\Users\user>curl -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNzE4NDAxMzc5LCJpYXQiOjE3MTg0MDA0NzksImp0aSI6Ijc2YTcwZjU0OTA2ZjQwOTNhYzc2MzRhYTFmNmJjNTlhIiwidXNlcl9pZCI6Miwicm9sZSI6MSwibGFuZ3VhZ2UiOm51bGwsImZ1bGxfYWNjZXNzX2dyb3VwIjp0cnVlfQ.p8BRy95SSiBmqeSjmCkAHFddRjKmzEOowP2RT34Jp6Y" http://3.71.19.16/accounts/courses/ {"detail":"Given token not valid for any token type","code":"token_not_valid","messages":[{"token_class":"AccessToken","token_type":"access","message":"Token is invalid or expired"}]} C:\Users\user>curl -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNzE4NDAxMzc5LCJpYXQiOjE3MTg0MDA0NzksImp0aSI6Ijc2YTcwZjU0OTA2ZjQwOTNhYzc2MzRhYTFmNmJjNTlhIiwidXNlcl9pZCI6Miwicm9sZSI6MSwibGFuZ3VhZ2UiOm51bGwsImZ1bGxfYWNjZXNzX2dyb3VwIjp0cnVlfQ.p8BRy95SSiBmqeSjmCkAHFddRjKmzEOowP2RT34Jp6Y" http://3.71.19.16/accounts/courses/ [{"id":1,"name":"Testkurs 1","language":1,"teacher":2,"grade":5,"start_date":null,"study_started":false,"activate_final_test":false,"number_of_students":90,"created_at":"2024-06-11T14:13:15.498484Z","scheduled_study_start":null,"scheduled_final_test":null,"demo":false},{"id":2,"name":"Testkurs 2","language":1,"teacher":2,"grade":5,"start_date":null,"study_started":false,"activate_final_test":false,"number_of_students":70,"created_at":"2024-06-11T14:17:58.503959Z","scheduled_study_start":null,"scheduled_final_test":null,"demo":false},{"id":3,"name":"Test","language":1,"teacher":2,"grade":5,"start_date":null,"study_started":false,"activate_final_test":false,"number_of_students":0,"created_at":"2024-06-13T22:35:51.513376Z","scheduled_study_start":null,"scheduled_final_test":null,"demo":false}] This is my Django Simple JWT-Setup: SIMPLE_JWT = { "ACCESS_TOKEN_LIFETIME": timedelta(minutes=15), "REFRESH_TOKEN_LIFETIME": timedelta(days=90), "ROTATE_REFRESH_TOKENS": True, "BLACKLIST_AFTER_ROTATION": True, "UPDATE_LAST_LOGIN": False, "ALGORITHM": "HS256", "VERIFYING_KEY": "", "AUDIENCE": None, "ISSUER": None, "JSON_ENCODER": None, "JWK_URL": None, "LEEWAY": 60, "AUTH_HEADER_TYPES": ("Bearer",), "AUTH_HEADER_NAME": "HTTP_AUTHORIZATION", "USER_ID_FIELD": "id", "USER_ID_CLAIM": "user_id", "USER_AUTHENTICATION_RULE": "rest_framework_simplejwt.authentication.default_user_authentication_rule", "AUTH_TOKEN_CLASSES": ("rest_framework_simplejwt.tokens.AccessToken",), "TOKEN_TYPE_CLAIM": "token_type", "TOKEN_USER_CLASS": "rest_framework_simplejwt.models.TokenUser", "JTI_CLAIM": "jti", "SLIDING_TOKEN_REFRESH_EXP_CLAIM": "refresh_exp", "SLIDING_TOKEN_LIFETIME": timedelta(minutes=15), "SLIDING_TOKEN_REFRESH_LIFETIME": timedelta(days=1), "TOKEN_OBTAIN_SERIALIZER": "rest_framework_simplejwt.serializers.TokenObtainPairSerializer", "TOKEN_REFRESH_SERIALIZER": "rest_framework_simplejwt.serializers.TokenRefreshSerializer", "TOKEN_VERIFY_SERIALIZER": "rest_framework_simplejwt.serializers.TokenVerifySerializer", "TOKEN_BLACKLIST_SERIALIZER": "rest_framework_simplejwt.serializers.TokenBlacklistSerializer", "SLIDING_TOKEN_OBTAIN_SERIALIZER": "rest_framework_simplejwt.serializers.TokenObtainSlidingSerializer", "SLIDING_TOKEN_REFRESH_SERIALIZER": "rest_framework_simplejwt.serializers.TokenRefreshSlidingSerializer", } and my nginx config server { listen 80; server_name 127.0.0.1; # change with url location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/ubuntu/USER/static/; } location / { # Add the necessary headers proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For … -
Django App Embedded in Shopify not setting CSRF token
We are facing a bit of an issue with CSRF tokens in our application. Our Django application is embedded in Shopify. I know browsers are getting a bit strict on the third-party cookies but haven't been able to find a solution to setting the CSRF token it the browser. For now, we are forced to comment out 'django.middleware.csrf.CsrfViewMiddleware', in settings.py, which I don't believe is the correct way to go. In my settings.py: CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True ALLOWED_HOSTS = [ "admin.shopify.com", "www.mydomain.com", ] CSRF_TRUSTED_ORIGINS = [ "admin.shopify.com", "www.mydomain.com", ] ... MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ... # Session settings SESSION_ENGINE = 'django.contrib.sessions.backends.db' SESSION_COOKIE_NAME = 'sessionid' SESSION_COOKIE_SECURE = True SESSION_COOKIE_SAMESITE = None SESSION_COOKIE_HTTPONLY = True SESSION_COOKIE_AGE = 1209600 SESSION_EXPIRE_AT_BROWSER_CLOSE = False SESSION_SAVE_EVERY_REQUEST = True CSRF_COOKIE_NAME = 'csrftoken' CSRF_COOKIE_SECURE = True CSRF_COOKIE_SAMESITE = None Then, in my JavaScript I have the following code to set the CSRF cookie: // CSRF Token function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); if (cookie.substring(0, name.length + 1) === (name + '=')) { … -
Django Error: config() takes 0 positional arguments but 1 was given
Why am I seeing this error? I have placed my SECRET_KEY in an .env file and I reference it using config from decouple in settings.py. Isn't it necessary to list the argument 'SECRET_KEY' inside config() in order for the program to access my secret key from the .env file? (I did activate the virtual environment). See below. Django Project Folder Structure: I created the .env file in the same app folder that contains the settings.py file. from settings.py: from decouple import config SECRET_KEY = config('SECRET_KEY') from .env: SECRET_KEY='epluribusunum' -
ValueError when i migrate in my Django project
I'm trying to make a music streaming website using Django. I have this error when i use the terminal command "migrate": "ValueError: Field 'song_id' expected a number but got '' ". I don't understand where "song_id" take a value that is not a number. How can i fix it and what is the code line with the problem? this is my views.py: def myPlaylist(request, id): user = request.user if user.is_authenticated: # Extracting Playlists of the Authenticated User myPlaylists = list(Playlist.objects.filter(user=user)) if user.is_authenticated: if request.method == "POST": song_id = request.POST["music_id"] playlist = Playlist.objects.filter(playlist_id=id).first() if song_id in playlist.music_ids: playlist.music_ids.remove(song_id) playlist.plays -= 1 playlist.save() message = "Successfull" print(message) return HttpResponse(json.dumps({'message': message})) else: images = os.listdir("music_app/static/PlaylistImages") print(images) randomImagePath = random.choice(images) randomImagePath = "PlaylistImages/" + randomImagePath print(randomImagePath) currPlaylist = Playlist.objects.filter(playlist_id=id).first() music_ids = currPlaylist.music_ids playlistSongs = [] recommendedSingers = [] for music_id in music_ids: song = Song.objects.filter(song_id=music_id).first() random.shuffle(recommendedSingers) recommendedSingers = list(set(recommendedSingers))[:6] playlistSongs.append(song) return render(request, "myPlaylist.html", {'playlistInfo': currPlaylist, 'playlistSongs': playlistSongs, 'myPlaylists': myPlaylists, 'recommendedSingers': recommendedSingers, 'randomImagePath': randomImagePath}) def addSongToPlaylist(request): user = request.user if user.is_authenticated: try: data = request.POST['data'] ids = data.split("|") song_id = ids[0][2:] playlist_id = ids[1][2:] print(ids[0][2:], ids[1][2:]) currPlaylist = Playlist.objects.filter(playlist_id=playlist_id).first() if song_id not in currPlaylist.music_ids: currPlaylist.music_ids.append(song_id) currPlaylist.plays = len(currPlaylist.music_ids) currPlaylist.save() return HttpResponse("Successfull") except: return redirect("/") # … -
How to unify the result of three queries into one keeping the order given by order by in Django
I am trying to get a list from a model to show the results ordered by status, for example: first "active", then "in progress" and "not active" at the bottom of the list. At the same time the results for each status must be ordered by the date. I am using Django version 4.0 and MySQL database. I tried to implement this using Union, but the results are not being ordered correctly. Here is the Model code: class LegalDocument(CreateAndUpdateDatesModel): class DocumentStatus(models.TextChoices): ACTIVE = 'Activo', 'Activo' EXPIRED = 'Vencido', 'Vencido' EVALUATING = 'Evaluación', 'Evaluación' REJECTED = 'Rescindido', 'Rescindido' RESOLVED = 'Resuelto', 'Resuelto' class DocumentType(models.TextChoices): CONTRACT = 'Contrato', 'Contrato' AGREEMENT = 'Convenio', 'Convenio' MEMORANDUM = 'Memorándum', 'Memorándum' ADDENDUM = 'Enmienda', 'Enmienda' LETTER = 'Carta', 'Carta' OTHER = 'Otro', 'Otro' document_number = models.CharField(max_length=100, unique=True) title = models.CharField(max_length=100) description = RichTextUploadingField() status = models.CharField(max_length=100, choices=DocumentStatus.choices, default=DocumentStatus.ACTIVE) expiration_date = models.DateField(null=True, blank=True) And here is how I am implenting the query with union: legal_documents = LegalDocument.objects.all() active_documents = legal_documents.filter(status=LegalDocument.DocumentStatus.ACTIVE).order_by('expiration_date') evaluating_document = legal_documents.filter(status=LegalDocument.DocumentStatus.EVALUATING).order_by('expiration_date') expired_documents = legal_documents.filter(status=LegalDocument.DocumentStatus.EXPIRED).order_by('expiration_date') rejected_documents = legal_documents.filter(status=LegalDocument.DocumentStatus.REJECTED).order_by('expiration_date') resolved_documents = legal_documents.filter(status=LegalDocument.DocumentStatus.RESOLVED).order_by('expiration_date') legal_documents = active_documents.union(evaluating_document, expired_documents, rejected_documents, resolved_documents, all=True) The result I am getting, please pay attention to "Expiration Date" column (dates are in format %Y-%m-%d): Title … -
How to use Django generated fields to get a single value from a many-to-many relationship?
I have a Django model representing a Book, which can have many different types of Person, including AUTHOR, EDITOR, ILLUSTRATOR, etc. class PersonType(models.Model): name = models.CharField() class Person(models.Model): name = models.TextField() class Book(models.Model): title = models.TextField() people = models.ManyToManyField(Person, through="PersonBook") class PersonBook(models.Model): person_type = models.ForeignKey(PersonType, on_delete=models.CASCADE) person = models.ForeignKey(Person, on_delete=models.CASCADE) book = models.ForeignKey(Book, on_delete=models.CASCADE) I was hoping to use Django's new GeneratedFields to create a property on Book with the name author that could query the many to many relationship and set the value equal to the first Person with the "AUTHOR" PersonType. I'm certain there are other ways of doing this with Managers and what not, but I'm curious as to how I can do this with Django's new GeneratedFields, if that's even possible. The documentation on Django's Query expressions doesn't show any examples along relationships, so I'm not sure if it's possible to do anything there. -
nginx dont redirect to my django app after using gunnicorn in production
I have a django app, running with docker, that i want to deploy with self-hosting. When i do python manage.py runserver 0.0.0.0:8000 i can do a curl 127.0.0.1:8000/api/endpoint and see that it get redirected to the app, but when i use gunicorn on the same port and ip the request never gets redirected to the app. I dont see whats the diffrence could be as i map to 0.0.0.0:8000 both places? upstream app_upstream { # 'app' is the name of the server from the container that is going to be used. With port 8000 server app:8000; } server { # Should respond to in localhost and listen to 8000 server_name localhost; listen 8000; location / { proxy_pass http://app_upstream; # This is the name of the upstream server that we defined above proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } } #test Entrypoint script gunicorn --bind 0.0.0.0:8000 app.wsgi docker-compose --- services: nginx: image: "nginx:latest" volumes: - "./nginx/:/etc/nginx/conf.d/" ports: - "8000:8000" networks: - webnet depends_on: - app app: build: context: . dockerfile: Dockerfile # Uncommented block # build: # context: . # image: soma1337/cryptobackend:latest volumes: - ".:/app" env_file: - "env-$RTE" depends_on: - db networks: - dbnet - webnet db: image: "postgres:13-alpine" … -
Please, how can I implement logging in django such that I pass the logs to a database rather than a file?
Here is my implementation //myproject/settings.py # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sitemaps', 'logger.apps.LoggerConfig', ] # Logging # https://docs.djangoproject.com/en/5.0/topics/logging/ LOGGING_CONFIG = None # Disable the automatic configuration LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '%(levelname)s %(asctime)s %(message)s' }, }, 'handlers': { 'database': { 'level': 'DEBUG', 'class': 'logger.handler.DatabaseLogHandler', 'formatter': 'verbose' }, 'browser': { 'level': 'DEBUG', 'class': 'logger.handler.BrowserLogHandler', }, }, 'loggers': { 'django': { 'handlers': ['database', 'browser'], 'level': 'DEBUG', 'propagate': True, }, 'django.request': { 'handlers': ['database', 'browser'], 'level': 'ERROR', 'propagate': False, }, 'security': { 'handlers': ['database', 'browser'], 'level': 'INFO', 'propagate': False, }, }, } //myproject/logger/apps.py from django.apps import AppConfig class LoggerConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'logger' //myproject/logger/handlers.py import logging from django.utils.timezone import now import logging class DatabaseLogHandler(logging.Handler): def emit(self, record): from logger.models import LogEntry log_entry = LogEntry( level=record.levelname, message=record.getMessage(), logger_name=record.name, filepath=record.pathname, func_name=record.funcName, lineno=record.lineno ) log_entry.save() class BrowserLogHandler(logging.Handler): logs = [] def emit(self, record): log_entry = { 'logger_name': record.name, 'level': record.levelname, 'message': record.getMessage(), 'timestamp': now().isoformat() } self.logs.append(log_entry) @classmethod def get_logs(cls): logs = cls.logs[:] cls.logs.clear() return logs //myproject/logger/models.py from django.db import models from django.utils.translation import gettext_lazy as _ class LogEntry(models.Model): timestamp = models.DateTimeField(auto_now_add=True) … -
My new staging slot cannot connect to a github workflow
I just upgraded my azure web application so that I can have additional deployment slots. I want to be able to push updates from my github to the azure staging slot of my web app so that i can confirm my changes are functioning and loaded before "swapping" it to the my production slot where my domain is active. I can setup continuous deployment on my production slot but when i try to set it up under my staging slot it always gives me errors telling me my resource is not found in github actions. Does anyone have feedback or experience on this? -
How to display a select box from all possible tags in django-admin when using django-taggit?
I'm trying to display a field for tags in the Django admin panel for each post, in which you can enter the desired tag or select from all available tags. It is not possible to select from all available tags. Tell me how exactly this should be implemented? from django.contrib import admin from django.db import models from taggit.forms import TagWidget from .models import Post, Comment @admin.register(Post) class PostAdmin(admin.ModelAdmin): fields = ('title', 'slug', 'author', 'body', 'publish', 'status', 'tags') list_filter = ('status', 'created', 'publish', 'author') list_display = ('title', 'slug', 'author', 'publish', 'status', 'get_tags') prepopulated_fields = {'slug': ('title',)} raw_id_fields = ('author',) formfield_overrides = { models.ManyToManyField: {'widget': TagWidget}, } def get_tags(self, obj): return ", ".join(o for o in obj.tags.names()) -
user profile management project in django
Part 1 : User Profile Management Robust user profile management system facilitating the creation and customization of personal profiles, including biographical information, skill sets, and contact details. Part 2 : Portfolio Customization Intuitive interfaces enabling users to tailor their portfolios with personalized content, including project showcases, work experience, education, and certifications. Part 3 : Project Showcase A visually appealing and interactive presentation of past projects, complete with detailed descriptions, images, and relevant links to provide visitors with a comprehensive understanding of the showcased work can any one guide me to do this project..I am done with part 1..I get input from user and make it a crud operation..But after some time i got that the logined user can only create one portfoilo..I didnt get how to connect three tables and their updations can any one guide me..I was stuck in part 2 and part 3 of the project in django -
why django resframework login view throwing error?
I am developing an OTP based authentication model. below are the back-end and front-end logic serializers.py class LoginSerializer(serializers.Serializer): email = serializers.EmailField() otp = serializers.CharField() def validate(self, data): email = data.get('email') otp = data.get('otp') # Logging the initial validation step api_log(msg="Starting validation") # Check if email exists try: user = User.objects.get(email=email) except User.DoesNotExist: raise serializers.ValidationError( { "email": "Email does not exist." } ) if user.otp != otp: raise serializers.ValidationError( { "otp": "OTP is invalid or expired." } ) if User.otp_expiry and User.otp_expiry < timezone.now(): raise serializers.ValidationError( { "otp": "OTP is expired." } ) # Attach user to validated data data['user'] = User return data views.py class LoginView(KnoxLoginView): # @csrf_exempt def post(self, request, *args, **kwargs): serializer = LoginSerializer(data=request.data) api_log(msg=f"login view serializers : {serializer}") if serializer.is_valid(): user = serializer.validated_data['user'] api_log(msg=f"login view USER : {user}") # Invalidate the OTP user.otp = None user.otp_expiry = None user.save() # Create auth token _, token = AuthToken.objects.create(user) api_log(msg=f"login view TOKEN : {token}") return Response({'token': token}, status=status.HTTP_200_OK) else: return Response({'error': serializer.errors}, status=status.HTTP_400_BAD_REQUEST) login.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Login</title> </head> <body> <form id="login-form"> {% csrf_token %} <div class="form-group"> <h1>Login</h1> <p>Please enter your email and OTP to login.</p> <hr> <label for="email"><b>Email</b></label> <input type="text" … -
How to Assign Existing Contacts to a Task Using Postman in Django Rest Framework Without Duplicating Email
I am currently working on a project using Django Rest Framework and Postman. My objective is to assign existing contacts to a task. However, when I make a POST request via Postman, I receive the error: "contact with this email already exists" The email field in my Contact model is defined as models.EmailField(unique=True), as I need to ensure that each email is unique across all contacts. When I attempt to assign an existing contact to a task using a POST request, I receive the aforementioned error. Here's the relevant part of my code: http://127.0.0.1:8000/tasks/ { "id": null, "title": "Postman", "description": "Postman", "dueTo": "2024-06-12T12:04:28Z", "created": "2024-06-12T12:04:31Z", "updated": "2024-06-12T12:04:34Z", "priority": "LOW", "category": "TECHNICAL_TASK", "status": "TO_DO", "subtasks": [ { "id": null, "description": "Postman", "is_done": false } ], "contacts": [ { "id": 1, "email": "max@mueller.com", "name": "Max Mueller", "phone_number": "123456789", "avatar_color": "#abcdef" } ] } models.py class Contact(models.Model): id = models.AutoField(primary_key=True) email = models.EmailField(unique=True) name = models.CharField(max_length=50) phone_number = models.CharField(max_length=30) avatar_color = models.CharField(max_length=7) def __str__(self): return f"{self.name}" serialzers.py class ContactSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Contact fields = ['id', 'email', 'name', 'phone_number', 'avatar_color'] models.py class Task(models.Model): id = models.AutoField(primary_key=True) title = models.TextField() description = models.TextField() dueTo = models.DateTimeField() created = models.DateTimeField() updated = models.DateTimeField() priority … -
My form is automatically being submitted in django whenever I open the link
Well I am creating a admin approval view for an account upgradation but it is not working as I expected. I wanted to get a form and then depending upon the data the form is either approved or rejected. I have created the form and everything else but the form is automatically submitting without even rendering along with all that it is getting approved too. Help me please. Model: class CabbieRequest(models.Model): user = models.ForeignKey(Passenger, on_delete=models.CASCADE) vehicle = models.ForeignKey('Rides.Vehicle', on_delete=models.PROTECT) requested_at = models.DateTimeField(auto_now_add=True) is_approved = models.BooleanField(default=False) approved_at = models.DateTimeField(null=True, blank=True) def approve(self): self.is_approved = True self.approved_at = timezone.now() Cabbie.objects.create( username=self.user.username, email=self.user.email, phone=self.user.phone, image=self.user.image, vehicle=self.vehicle, stars=0.0, password=self.user.password ) self.save() def __str__(self): return f'Request by: {self.user.username}' View: @login_required def request_cabbie_upgrade(request): if request.method == 'POST': vehicle_form = VehicleForm(request.POST) if vehicle_form.is_valid(): vehicle = vehicle_form.save(commit=False) vehicle.save() cabbie_request = CabbieRequest(user=request.user, vehicle=vehicle) cabbie_request.save() return redirect('PassengerDashboard') else: vehicle_form = VehicleForm() return render(request, 'users/cabbie_request.html', {'vehicle_form': vehicle_form, 'cabbie': request.user}) Form: class CabbieRequestForm(forms.Form): approve = forms.BooleanField(required=False) reject = forms.BooleanField(required=False) Template: {% extends "base.html" %} {% load static %} {% block title %} <title>Manage Cabbie Request</title> {% endblock title %} {% block body %} <div class="container mt-5 pt-5 manage-request-container"> <div class="row"> <div class="col-md-12"> <h2>Manage Cabbie Request</h2> <div class="card"> <div class="card-body"> <p><strong>Username:</strong> {{ user.username … -
Issue with Toggling between New Themes
I'm encountering an issue with a custom Theme Installation in my Django project using v. 4.2.13 and Python v. 3.9.7. In the default Admin side, there is a Moon icon for toggling the Themes (i.e. b/w Light and Dark and Auto). I want to add a Grey theme as my default with a new icon. So there are total 4 icons for themes now - Grey, Light , Dark & Auto. For implementing this, I added a new icon for the Grey theme and the icon is now not visible in the Admin panel (only the default 3 are shown) and the toggling between themes is not working. Below are the screenshots of the code for installing themes with their respective icons. Please also note my teammate has been working on Django 5.0 for making his previous project commits in Github. We wanted to test what can happen to the same functionality if team members work on different versions since we're assuming Git essentially stores all files as basic text files with version control. I am not sure if this has anything to do with my problem. Kindly help. Screenshot 1 - The Admin panel moon icon for theme toggle … -
Globally JSON-serializing UUIDs and other types with psycopg2 and django
I'm developing an application with Django 4.2.10. I am running a postgres database and use psycopg2. In my application, I am working with nested dictionaries (coming out of Django ninja/pydantic schemas) and I would like to write these to JSONField django fields. However, they contain UUID's which results in the following error: TypeError: Object of type UUID is not JSON serializable To resolve this problem, I really prefer a "global" hook/adapter that convinces psycopg2 to properly serialize UUID's and other types so that I don't have to worry about it in all the places where I write this data into the database. It should work for direct/raw queries but also via the Django ORM. I found this JSON Adaptation section in the psycopg2 docs. Note You can use register_adapter() to adapt any Python dictionary to JSON, either registering Json or any subclass or factory creating a compatible adapter: psycopg2.extensions.register_adapter(dict, psycopg2.extras.Json) This setting is global though, so it is not compatible with similar adapters such as the one registered by register_hstore(). Any other object supported by JSON can be registered the same way, but this will clobber the default adaptation rule, so be careful to unwanted side effects. So my thought … -
Session Timeout on User side in Django
I am trying add a session timeout in my Django project by using Django's in-built session middleware. I have implemented session timeout on my project using the Views method I have come across for this purpose and it is working on my Admin side, but in my User side, the redirection that I given not working (i.e. I need to log out the user and get back to the signin page after session expires). My django version : 5.0.2 My python version: 3.12.2 Now it is taking the time and that page will expire but it will not redirect to the signin page. How can I solve this issue? What are some other approaches we can use for implementing Sessions on Admin & User sides both redirecting to the Signup page and persisting the last page worked on upon logging back in ?settings.pymiddilewareViews.pyurls.py -
Hi, i need help passing my cv2 yolov8s video feed to a django application i got for my project
Im new to neural network development i got pretrained YOLO8s model and trained it on my custom dataset, made a python class, using cv2 to display the results now i need help passing my cv2 yolov8s video feed to a django application i got for my project, how do i do that? ''' from ultralytics import YOLO from pathlib import Path import cv2, onnx, onnxoptimizer,numpy,onnxruntime import torch.onnx import torchvision.models as models from database.db import * from pprint import pprint as pt class Main_field: def __init__(self, model, size, source, conf_): self.model = self.load_model(model) self.size = size self.source = source self.conf_ = conf_ def __call__(self): self.process_video() def load_model(self, model): model.fuse() return model def process_video(self): cap = cv2.VideoCapture(self.source) while True: ret, frame = cap.read() if not ret: break results = self.model.predict(frame, conf=self.conf_, imgsz=self.size) masks_dict=[result.names for result in results][0] xyxys=[result.boxes.cpu().numpy().xyxy for result in results][0] #xyxy mask_ids=[result.boxes.cpu().numpy().cls.astype(int).tolist() for result in results][0] masks=[masks_dict[itr] for itr in mask_ids] db_output=[check_(local_list,str(itr)) for itr in mask_ids if itr] video_outp=cv2.imshow("_________", results[0].plot()) pt(mask_ids) if cv2.waitKey(1) & 0xFF == ord('q'): break def __del__(): cap.release() cv2.destroyAllWindows() def init_model(path: str) -> any: return YOLO(path) ''' looking for examples on how can i pass constant video feed to my web page