Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Error: 'cannot pickle '_io.BufferedReader' object' when Using Cache with Context Data
I'm encountering a challenging issue in my Django project related to caching and context data. When trying to cache the context data in a view, I'm receiving the error message: "cannot pickle '_io.BufferedReader' object." The error seems to occur in my view that displays detailed information about a book, and I'm attempting to cache certain parts of the context, such as average ratings, recommended books, and the last books. There is my detail book view and model: #views.py class DetailBookView(DetailView): template_name = "books/book-detail.html" queryset = Book.objects.all().select_related("genre") cache_timeout = 60 def get_context_data(self, **kwargs): obj = self.get_object() context = super().get_context_data(**kwargs) cache_key = f"book_detail_{obj.id}" cached_data = cache.get(cache_key) if cached_data is not None: context.update(cached_data) # average rating book context["avg"] = BookRelations.objects.get_rating(book=obj) # generate 3 random book context["recommended"] = Book.objects.get_recommended(obj.genre) # last 3 books context["last_books"] = self.get_queryset().values("title") else: cache.set(cache_key, context, self.cache_timeout) return context #models.py (Books) class BookManager(models.Manager): def get_recommended(self, genre): recommend_books = list(Book.objects.filter(genre=genre).select_related("owner")) if len(recommend_books) < 3: recommend_books += list(self.get_queryset())[:4] return random.sample(recommend_books, 3) class Book(models.Model): title = models.CharField(max_length=250) slug = models.SlugField(default="") description = models.TextField(blank=True, null=True) rating = models.DecimalField( validators=[MaxValueValidator(5)], max_digits=3, decimal_places=2 ) created_at = models.DateTimeField(auto_now_add=True) last_update = models.DateTimeField(auto_now=True) image = models.ImageField( upload_to="book_img/", validators=[FileExtensionValidator(["jpg", "JPEG"])], null=True, blank=True, ) genre = models.ForeignKey(Genre, on_delete=models.PROTECT, null=True) author = models.ForeignKey(Author, … -
How to display multiple related objects in Django
I have two models that look like this: class EventDrink(models.Model): name = models.CharField(max_length=255) drink_active = models.BooleanField() def __str__(self): return self.name class EventIngredient(models.Model): drink = models.ManyToManyField(EventDrink) name = models.CharField(max_length=255) url = models.URLField() def __str__(self): return self.name I now want to display all drinks with drink_active set to True to display in my view. I also want to display the ingredients related to that drink. I know I can filter on the drinks in my view like this: drinks = EventDrink.objects.filter(drink_active=1) But how do I now display the ingredients related to each drink? -
The contents in my cards are not the same size eventhough they have the same code
So I made this booking page with bootstrap, and I have made the Upcoming Bookings section first, after that I just copied and past it to the Past Booking section, and just change the variable inside the templating language curly brackets. In theory, since its 99.99% the same code, it should be the same right? But for some reason the details in the Past Booking card is slightly smaller than the Upcoming booking, and this makes it looks unsymmetrical and its driving my OCD crazy. I cannot figure it out! If anyone could that would be very helpful! Screenshot my_bookings.html {% extends 'base.html' %} {% load static %} {% block content %} <div class="container-fluid"> <div class="jumbotron"> <div class="welcome-my-bookings mt-5 text-center"> <h1>My Bookings</h1> </div> </div> <div class="row mt-4 booking-title"> <h3>Upcoming Bookings</h3> <hr> </div> <div class="col-12 card mb-4 left top"> <div class="card-body"> {% if future_bookings %} {% for booking in future_bookings %} <div class="booking-details booking-card my-4"> <div class="row justify-content-center align-items-center flex-lg-row"> <div class="col-auto booking-img-container"> <a href="{% url 'lesson_detail' booking.lesson.slug %}" class="lesson-link"> <div class="col-auto"> {% if "placeholder" in booking.lesson.featured_image.url %} <img class="booking-img d-none d-md-inline-block" src="https://res.cloudinary.com/dukqu7lia/image/upload/v1696354385/placeholder.jpg"> {% else %} <img src="{{ booking.lesson.lesson.featured_image.url }}" class="booking-img d-none d-md-block"> {% endif %} </div> </a> </div> <div class="col-auto … -
Centering div and its elements in Django project
I'm diving into Django for my first project, and I'm stuck with centering stuff on my site. What I'm trying to do is create a div that holds all the content on the site except for the navigation bar. I want this div to sit right in the middle of the screen and take up 50% of the width. And, of course, all the stuff inside that div should be centered too. I've tried a few things, but it's not quite working. Take a look at what I've got: Here is the template: <html> <style> body { margin: 0; padding: 0; } img[src="/media/images/crate_bar.png"] { margin: 0; padding: 0; display: block; width: 100%; height: auto; box-sizing: border-box; } img[src="/media/images/logo.png"] { position: absolute; display: block; width: auto; height: auto; left: 50%; transform: translateX(-50%); top: 0; } #logo { display: flex; justify-content: center; align-items: center; text-align: center; } #main_container { display: flex; justify-content: center; align-items: center; } #second_container { display: flex; justify-content: center; align-items: center; width: 50%; } </style> <div id="logo"> <img src="/media/images/crate_bar.png"> <a href="{% url 'mainapp:home_view' %}"><img src="/media/images/logo.png" alt="logo"></a> </div> <h1> {% if user.is_superuser %} <a href="{% url 'mainapp:new_article' %}"><button type=" button">New article</button></a> {% endif %} {% block content %} <div id="main_container"> … -
Create dynamic URL using primary key in django
I'm developing a website, it creates url for every article using slug (entered manually by the admin who is posting the article) However I'm trying to change it to be dynamically generated using pk. Note that there is no content uploaded in the website so it won't affected by this change. Here is the current code and my main problem is that I don't know how to change it to pk. and when I try the available solutions I don't know where it should be passed through HTML pages. #view.py def DetailView(request, slug): template_name = 'post_detail.html' post = get_object_or_404(Post, slug=slug) return render(request, template_name, {'post': post}) #models.py class Post(models.Model): title = models.CharField(max_length=500) image = models.ImageField(null=True, blank=True, upload_to='media/') content = RichTextField(blank = True, null = True) post_id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True, editable=False) created_on = models.DateTimeField(auto_now_add=True) modified_on = models.DateTimeField(auto_now=True) slug = models.SlugField(max_length=200, allow_unicode=True, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') status = models.IntegerField(choices=STATUS, default=0) category = models.CharField(max_length=500, choices= categories_list, default='0') #To order posts based on created dates decsend class Meta: ordering = ['-created_on'] def __str__(self): return self.title #urls.py path('<slug:slug>/', views.DetailView, name='post_detail'), and here is how it's being passed to the html <p><a href="{% url 'post_detail' post.slug %}">{{post.content|safe |slice:":10" }}</a></p> Thanks in advance -
Django Query input results of one queryset to find an object that doesn't appear in another model
Good afternoon, I am trying to write an DRF endpoint that returns the next unused hint. I have two models: class GameActivity(models.Model): activity_datetime = models.DateTimeField(default=timezone.now) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='activity_user') activity_type = models.ForeignKey(GameActivityType, on_delete=models.CASCADE, null=True, blank=True,related_name='game_activity_type') activity_hint = models.ForeignKey(Hint, on_delete=models.CASCADE, null=True, blank=True) And class Hint(models.Model): hint_title = models.CharField(max_length=50) hint_detail = models.CharField(max_length=300) hint_level = models.IntegerField() chapter = models.ForeignKey(Chapter, on_delete=models.CASCADE, null=True, blank=True, related_name="chapter_hint") pts_cost = models.IntegerField() What I am trying to do is return the next hint for the passed in Chapter ID that is NOT in the GameActivity model. pseudo-code return Hint where (Count (GameActivity where activity_hint=Hint AND Hint.Chapter == Chapter.ID) = 0) order by hint_level ASC LIMIT 1 I cannot figure out how to chain two queries together, the first being input to the second. Queryset = SELECT * from Hint WHERE chapter.id = CHAPTER_ID Pass in the queryset into GameActivity and return the one Hint with the lowest hint_level that doesn't have a GameActivity entry. Thanks for any help, I feel like I am not thinking about the problem correctly. BCBB -
Authentication failed: Include valid openId scopes like profile, email
I am building an app with Django and social-auth-app-django. I followed this tutorial. I created an app on LinkedIn for Developers, got the client_id and secret_key. I also made sure that the product Sign In with LinkedIn using OpenID Connect is added to my app. In settings.py, I added all the OAUTH2 parameters: SOCIAL_AUTH_LINKEDIN_OAUTH2_KEY = '...' # Client ID SOCIAL_AUTH_LINKEDIN_OAUTH2_SECRET = '...' # Client Secret SOCIAL_AUTH_LINKEDIN_OAUTH2_SCOPE = ['r_basicprofile', 'r_emailaddress'] SOCIAL_AUTH_LINKEDIN_OAUTH2_FIELD_SELECTORS = ['email', 'formatted-name', 'public-profile-url', 'picture-url'] SOCIAL_AUTH_LINKEDIN_OAUTH2_EXTRA_DATA = [ ('id', 'id'), ('formattedName', 'name'), ('emailAddress', 'email_address'), ('pictureUrl', 'picture_url'), ('publicProfileUrl', 'profile_url'), ] However, I kept getting Authentication failed: Scope "r_basicprofile" is not authorized for your application. I changed SOCIAL_AUTH_LINKEDIN_OAUTH2_SCOPE: SOCIAL_AUTH_LINKEDIN_OAUTH2_SCOPE = ['openid'] Now I get Authentication failed: Include valid openId scopes like profile, email. Based on the official LinkedIn documentation, I also tried SOCIAL_AUTH_LINKEDIN_OAUTH2_SCOPE = ['openid', 'profile', 'email'] But I got Authentication failed: Scope "r_liteprofile" is not authorized for your application. again. Has anyone an example of a settings.py configuration that works? -
why webSocket connection failed?
I've been trying to cerate a chat app using Django with webSocket,in console I got this, error WebSocket connection to 'ws://127.0.0.1:8000/ws/chat/room/' failed: room/:20 I'm not using Redis for implementing Django channels, İt is just a simple chat app runs on local server host views.py def room(request, room_name): return render(request, "chatroom.html", {"room_name": room_name}) routing.py websocket_urlpatterns = [ re_path(r"ws/chat/(?P<room_name>\w+)/$", consumers.ChatRoomConsumer.as_asgi()), ] consumer.py class ChatRoomConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope["url_route"]["kwarges"]["room_name"] self.room_group_name = "chat_%s" % self.room_name await self.channel_layer.group_add(self.room_group_name, self.channel_name) await self.accept() # to know which group we should send to await self.channel_layer.group_send( self.room_group_name, { "type": "tester_message", "tester": "hello world", }, ) async def tester_message(self, event): tester = event["tester"] await self.send(text_data=json.dumps({"tester": tester})) async def disconnect(self, close_code): await self.channel_layer.group_discard(self.room_group_name, self.channel_name) chatroom.html <div id="user-hello"> </div> <!-- convert an object into a JSON object --> {{room_name|json_script:"room-name"}} <script> // convert a JSON object in text format to js object that can be used const roomName=JSON.parse(document.getElementById('room-name').textContent); //create websocket connection script const chatSocket=new WebSocket( 'ws://' + window.location.host + '/ws/chat/' + roomName + '/' ); //receive a massege chatSocket.onmessage=function(e){ const data=JSON.parse(e.data) console.log(data); document.querySelector('#user-hello').innerHTML=(data.tester) } </script> settings.py INSTALLED_APPS = [ "channels", "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "chat", ] DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" ASGI_APPLICATION = "core.routing.application" CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer", … -
Uncaught DOMException: Failed to execute 'querySelector' on 'Element': 'td:nth-child(...)' is not a valid selector
Hi guys I am building a django app, and i am struggling with js function to sort a html table ( values in the desired column ) by clicking the column name. Below I provide a html template and another html file which extends this template, and of course the js file itself. Any help is appreciated, thank you in advance! TEMPLATE: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Report Result</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link type="text/css" href="{% static 'css/report.css' %}" rel="stylesheet" /> </head> <body> <h1>{{ info }}</h1> <p style="font-size: 30px;">The report was generated successfully. You can download the xlsx file using the button below:</p> <p style="font-size: 20px;">To sort values by column, click the name of the desired column</p> <table id="data-table"> <thead> <tr> {% for col in column_names %} <th data-col="{{ col }}">{{ col }}</th> {% endfor %} </tr> </thead> <tbody>{% block content %}{% endblock %}</tbody> </table> <script src="{% static 'js/sorting.js' %}"></script> </body> </html> HTML FILE THAT EXTENDS THE PREVIUOS ONE: {% extends 'base_report.html' %} {% block content %} {% for row_data in data_to_render %} <tr> {% for cell_data in row_data %} <td> {% if cell_data.link %} <a href="{{ cell_data.value }}"> {{ cell_data.value }} </a> {% … -
modify models instances and sent to another model in django
I have 2 models in django Model A and Model B in model A exist 2 fields start_hour = models.TimeField() end_hour = models.TimeField() and I want to send this instance to a function and return a list with a slot time of 1 hour. for an example: start_hour = '10:00' end_hour = '15:00' output : [ ( '10:00 – 11:00'), ( '11:12 – 12:00'), ( '12:00 – 13:00'), ( '13:00 – 14:00'), ( '14:00 – 15:00'), ] i wrote function and works well my question is : i want in model B show list of time slot to select not show start time and end time Model_A = models.ForeignKey(Model_A, on_delete=models.CASCADE) I wrote this code, but it shows the start time and end time! -
OAuth2 Authentification Django and MSexchange
I am building a Django App where users have to be able to send emails with their specific exchange mail address. I think I need OAuth2 for that. However MS support and all other resources I found state that I need to register my app in Azure AD. But I don't have an Azure AD. I do have access to the Microsoft 365 admin center. Do I have to register my App there or generate a specific token? -
How to fix django mfa for firefox and safari (Registeration Failed as NotAllowedError: CredentialContainer request is not allowed)
I use the mfa library (https://pypi.org/project/mfa/) within my django project. In Chrome, the user can register a second factor (fido) easily, but in firefox, i get the following error: Registeration Failed as NotAllowedError: CredentialContainer request is not allowed., try again or Go to Security Home Im googeling this since hours but cant find a solution, i already checked CSP Settings. Any help is really appreciated! -
Passing Parent PK to ModelForm in Class Based Create and Update View
I'm updating function based views to class based views and having issues re-establishing the link between campaign and books. My Book Model has a foreign key link to Campaigns. campaign = models.ForeignKey(Campaign, on_delete=models.DO_NOTHING) I have a ModelForm where I set the campaign_id and would like to get this from the CreateView. class BookForm(forms.ModelForm): def __init__(self, *args, **kwargs): author = kwargs.pop('author', None) campaign_id = kwargs.pop('campaign_id', None) super(BookForm, self).__init__(*args, **kwargs) if campaign_id: self.fields['campaign_id'].initial = campaign_id campaign_id = forms.CharField(widget=forms.HiddenInput()) I followed this using dispatch and get_form_kwargs and my CreateView looks like class BookCreateView(generic.CreateView): model = Book template_name = 'PromoManager/book_form.html' form_class = BookForm success_url = '/profile' campaign_id = None # Retrieves the campaign_id from url def dispatch(self, request, *args, **kwargs): self.campaign_id = kwargs.get("pk") return super().dispatch(request, *args, **kwargs) ## Sends building id to the form def get_form_kwargs(self, *args, **kwargs): kwargs = super().get_form_kwargs(*args, **kwargs) kwargs["campaign_id"] = self.campaign_id return kwargs def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['campaign'] = Campaign.objects.get(pk=self.campaign_id) context['title_label'] = "Create" return context def form_valid(self, form): instance = form.save(commit=False) instance.author = self.request.user instance.campaign = Campaign.objects.get(id=form.cleaned_data['campaign_id']) instance.save() form.save_m2m() return super().form_valid(form) But it breaks the UpdateView which relies on the same form as the PK passed on the update view URL is the book pk. My UpdateView looks … -
Odd results when running similar queries in Postgres
I am having this issue where my database is causing the CPU usage of our db server to hit 100% on a particular query. The query has two different where clauses and does not work, but when I delete either of the where clauses, the query returns quickly. The query i am trying to run is the following. This query references two tables in the database, asset_asset and asset_assetclassification. asset_asset has 1.8 million rows and asset_assetclassification has 7k rows. select count(1) from asset_asset INNER JOIN "asset_assetclassification" ON ("asset_asset"."classification_id" = "asset_assetclassification"."id") WHERE ("asset_assetclassification"."company_id" = 1 AND "asset_asset"."deleted_at" IS NULL); Here is a screenshot of the query plan for this query. And if i run this select count(1) from asset_asset INNER JOIN "asset_assetclassification" ON ("asset_asset"."classification_id" = "asset_assetclassification"."id") WHERE ("asset_assetclassification"."company_id" = 1); and here is a screenshot of the query plan for this query or this select count(1) from asset_asset INNER JOIN "asset_assetclassification" ON ("asset_asset"."classification_id" = "asset_assetclassification"."id") WHERE ("asset_asset"."deleted_at" IS NULL); the query works perfectly fine. Note: the original query was generated by Django. Any ideas about whats going on here? Thanks in advance! -
Send progressive data from django view to ajax
I have a django webapp. And I'm using jquery to send a POST. With that POST, I get multiple informations from the backend. But The page need to wait until all the informations are ready and then prin all of them. I would want, as an exemple, when the first one is finished, to be displayed, and then, when the second one is done, to be displayed and so on. That's my view: def home(request): context = {} if request.method == 'POST': is_ajax = request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest' if is_ajax: context = {} # Update the expression if it's valid try: print('---------------------------------') print('POST[math-input]: {0}'.format(request.POST['math-input'])) print('POST[time]: {0}'.format(request.POST['time'])) data = request.POST['math-input'] core.max_time = int(request.POST['time']) print('---------------------------------') context = dispatch_expression(data) except Exception as exc: # exc_type, exc_obj, exc_tb = sys.exc_info() # fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] # print(exc_type, fname, exc_tb.tb_lineno) # print("Exception: {0}".format(exc)) traceback.print_exc() context = {'result': 'Expresie invalidă!'} return JsonResponse(context, status=200) template = loader.get_template('home.html') return HttpResponse(template.render(context, request)) Basically, dispatch_expression(data) is doing all the algorithms. I can modify that function to work with yields, without any problem, but I have no idea how to send each step when it's done. I heard about async, but any example on the internet didn't help me. I tried StreamingHttpResponse, but … -
Updates made via admin to m2m Django field are not persisted in the database
I`m new to Django and completely stuck with this one. This pet project is a website for online school. The default flow would be: user signups and has the role Student by default, then if this user is a school teacher admin updates the role to Teacher. I have the following User model which has role field, I plan to use it to display correct content for the user on the website, since I dont want to use groups and permissions for this purpose, at least not yet. But I want to have groups in sync with User roles and use groups to manage permissions inside admin. class User(AbstractUser): username = None email = models.EmailField(max_length=255, unique=True, verbose_name="email address") first_name = models.CharField(_("first name"), max_length=150) last_name = models.CharField(_("last name"), max_length=150) updated_at = models.DateTimeField(_("last updated to user"), auto_now=True) email_verified = models.BooleanField(default=False) role = models.PositiveSmallIntegerField( choices=UserRolesChoices.choices, default=UserRolesChoices.STUDENT ) date_of_birth = models.DateTimeField(_("date of birth"), null=True, blank=True) profile_picture = models.ImageField(_("profile picture"), null=True, blank=True, upload_to=profile_pic_directory_path, storage=OverwriteStorage) objects = UserManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = ["first_name", "last_name"] def __str__(self): return self.email @property def is_staff(self): return (self.role in (UserRoles.TEACHER, UserRoles.ADMIN)) or self.is_superuser @property def is_teacher(self): return self.role == UserRoles.TEACHER def save(self, *args, **kwargs): is_new_user = not self.pk changed_fields = … -
RecursionError: maximum recursion depth exceeded while calling a Python object when updating choice field
model: StatusChoices = ( ("TODO", "todo"), ("DOING", "doing"), ("DONE", "done"), ) class Task(models.Model): status = models.CharField( choices=StatusChoices, default=StatusChoices[0], max_length=5, ) request body: { "id": 15, "content": "Updated Task Content", "creationDate": "2020-10-23", "user": 2 , "status": "DONE" } serialiser: class TaskUpdateSerializer(serializers.ModelSerializer): class Meta: model = Task fields = ("status") view class TaskUpdateAPIView(APIView): def patch(self, request, pk): try: task = Task.objects.get(pk=pk) except Task.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) serializer = TaskUpdateSerializer(task, data=request.data, partial=True) if serializer.is_valid(): task.status = request.data.get("status", task.status) task.save() return Response(serializer.data, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) url: urlpatterns = [ path("task/update/<int:pk>", TaskUpdateAPIView.as_view(), name='update-task' ), ] New error: RecursionError: maximum recursion depth exceeded while calling a Python object What am I missing? -
Override error representation on import model page django
I'm working with a django application and don't wanted to show users the stack trace when there is any error occurred in production. For example, I've added validation to validate import action under before_import method, and when there is any issue in the validation it shows error message along with stack trace. Please refer screenshot below: Instead I wanted to just show the error message only. This is mainly for the security purpose as on production it will disclose my server directory structure to it's users. I tried couple of things, to override import.html under my templates directory, but it didn't worked. to override exception using LOGGING in settings.py It is great, if I can show list of errors for all affected rows in a CSV/XLSX file. -
How to Add 'rest_registration' URLs to Default Routers in Django REST Framework and Include Them in API Root?
I am using the 'rest_registration' package to handle user validation and registration in my Django REST API project. I would like to integrate the 'rest_registration' URLs with the default routers in Django REST Framework and have them included in the API root. Can someone please provide guidance on how to achieve this integration? Specifically, I want to know how to configure my project to include 'rest_registration' URLs in the default routers, and I'd like these URLs to be visible in the API root. from django.urls import path, include from rest_framework import routers from rest_framework import viewsets from rest_framework.response import Response class ServerStatusViewSet(viewsets.ViewSet): def list(self, request): return Response({'status': 'Server is running'}) router = routers.DefaultRouter() router.register(r'status', ServerStatusViewSet, basename='server-status') urlpatterns = [ path('', include(router.urls)), path('auth/', include('rest_registration.api.urls')), ] -
After making a reservation, the reserved time does not disappear from the list of available times
I am working on a project where you can arrange training with a trainer. And I have a problem with booking a training session, because after making a reservation, the time that was booked does not disappear from the available time. On the same day, another person can also book this hour. Models.py class BaseModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: abstract = True class WorkingHour(models.Model): time = models.CharField(max_length=10, unique=True, null=True) is_available = models.BooleanField(default=True) def reserve_hour(self): if self.is_available: self.is_available = False self.save() def __str__(self): return self.time class Trainer(BaseModel): trainer = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True) job = models.CharField(max_length=32, choices=type_job) working_hours = models.ManyToManyField(WorkingHour, related_name='trainers', null=True) def __str__(self): return f"{self.trainer.first_name} {self.trainer.last_name} - {self.job}" class TrainerServices(models.Model): name = models.CharField(max_length=64) price = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return self.name class Appointment(BaseModel): date = models.DateField() chosen_hour = models.ForeignKey(WorkingHour, on_delete=models.CASCADE, null=True) class TrainerAppointment(Appointment): trainer = models.ForeignKey(Trainer, on_delete=models.CASCADE) services = models.ForeignKey(TrainerServices, on_delete=models.CASCADE) user = models.ForeignKey(MyUser, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return f"{self.user}-{self.services}" Forms.py class TrainerAppointmentForm(forms.ModelForm): chosen_hour = forms.ModelChoiceField( queryset=WorkingHour.objects.filter(is_available=True), empty_label=None, widget=forms.Select(attrs={"class": "form-select is_valid"}) ) class Meta: model = TrainerAppointment fields = "__all__" widgets = { "trainer": forms.Select(attrs={"class": "form-select is_valid"}), "date": forms.DateInput(attrs={"class": "form-control is_valid", "type": "date"}), "services": forms.Select(attrs={"class": "form-select is_valid"}), } def clean_date(self): date = self.cleaned_data.get('date') today = timezone.now().date() … -
Clean and Reusable Exception Handling in Django and DRF (Pythonic problem)
I'm working on a Django API project and I'm facing a challenge with exception handling. Specifically, I want to handle specific exceptions raised in my business logic and map them to corresponding Django REST framework (DRF) exceptions in a clean and reusable way. Here's a simplified version of my code: # My business logic class UserBusinessLogicLayer(Manager): """ This is the business logic layer for User management. """ def get_user_with_identifier(self, identifier: str, allow_username: bool = True) -> "User": # ... (omitting some code for brevity) user = self.filter(reduce(operator.or_, conditions)).first() if not user: raise self.model.DoesNotExist("User Does not exist.") if not user.is_active: logger.info( "The user with username/email/phone-number %s is not active", identifier, exc_info=True, ) raise DeactivatedUser( f"This account has been deactivated since {user.status_change}", user ) if not user.is_email_verified: logger.info( "The user %s hasn't verified the email", identifier, exc_info=True, ) raise NotVerifiedEmail("This account hasn't verified the its email") return user and this is how i use the code: try: user = User.bll.get_user_with_identifier(identifier, allow_username=False) except User.DoesNotExist as error: # this is how i normally handle the exceptions logger.info( "there is no user with username/email/phone-number %s", identifier, exc_info=True, ) raise exceptions.NotFound("Invalid input.") from error # this is api exception except Exception as error: # But I … -
arcpy.env.workspace not working in django. Its throwing this error AttributeError: ERROR 87934
class get_FeatureClassView(viewsets.ViewSet): def list(self, request, projectname): sgeometry = {} # Corrected variable name tgeometry = {} # Corrected variable name project_path = config.get('Paths', 'project_path') template_dir = config.get('Paths', 'template_dir') # project_path = r"D:\sreeraj\project\unbridge_backEnd" # Use a raw string or double backslashes project_path1 = os.path.join(project_path, projectname) print(project_path1) print(project_path) source_path = os.path.join(project_path1, "sourcegdb") # Use os.path.join for path concatenation print("----------", source_path) source_gdb = os.listdir(source_path)[0] print("source_gdb", source_gdb) source_gdb_path = os.path.join(source_path, source_gdb) print("sourceGDBPath", source_gdb_path) self.source_gdb_path = source_gdb_path target_path = os.path.join(project_path1, "targetgdb") # Use os.path.join for path concatenation target_gdb = os.listdir(target_path)[0] target_gdb_path = os.path.join(target_path, target_gdb) print("target_gdb_path", target_gdb_path) arcpy.env.workspace = source_gdb_path sourcefeature_classes = arcpy.ListFeatureClasses() #sourcefeature_classes.sort() print(sourcefeature_classes) for feature_class in sourcefeature_classes: desc = arcpy.Describe(feature_class) geometry_type = desc.shapeType sgeometry[feature_class] = geometry_type arcpy.env.workspace = os.path.join(target_gdb_path, "UtilityNetwork") # Use os.path.join for path concatenation targetfeature_classes = arcpy.ListFeatureClasses() #targetfeature_classes.sort() print(targetfeature_classes) for feature_class in targetfeature_classes: desc = arcpy.Describe(feature_class) geometry_type = desc.shapeType tgeometry[feature_class] = geometry_type featureclasslist = { "sourcefeature_classes": sgeometry, "targetfeature_classes": tgeometry } print(featureclasslist) return JsonResponse(featureclasslist) This throwing this error Traceback (most recent call last): File "C:\Users\sv67808\AppData\Local\miniconda3\envs\arcproenv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\sv67808\AppData\Local\miniconda3\envs\arcproenv\lib\site-packages\django\core\handlers\base.py", line 197, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\sv67808\AppData\Local\miniconda3\envs\arcproenv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\sv67808\AppData\Local\miniconda3\envs\arcproenv\lib\site-packages\rest_framework\viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File … -
How to upload media files to AWS S3 within Django app without getting a ClientError
I'm getting the following error when I try to upload images within the admin panel, 'An error occurred (AccessControlListNotSupported) when calling the PutObject operation: The bucket does not allow ACLs'. I've setup the settings.py file and AWS according to the django-storages docs, but still not working. All Static files are being imported in and can be read Also tried changing the AWS_DEFAULT_ACL to 'none' and 'public-read-write' but still not working. settings.py config: if USE_S3: # aws settings AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_DEFAULT_ACL = public-read AWS_S3_REGION_NAME = os.environ.get('AWS_S3_REGION_NAME') AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} #Additional settings AWS_S3_FILE_OVERWRITE = False AWS_QUERYSTRING_AUTH = False # s3 static settings AWS_STATIC_LOCATION = 'static' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_STATIC_LOCATION}/' STATICFILES_STORAGE = 'myproject.storages.StaticStore' # s3 media settings AWS_MEDIA_LOCATION = 'media' MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_MEDIA_LOCATION}/' DEFAULT_FILE_STORAGE = 'myproject.storages.MediaStore' else: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) AWS Bucket Policy: { "Version": "2012-10-17", "Statement": [ { "Sid": "Statement1", "Effect": "Allow", "Action": "s3:*", "Resource": "arn:aws:s3:::my-bucket/*" }, { "Sid": "Statement2", "Effect": "Allow", "Action": "s3:*", "Resource": "arn:aws:s3:::my-bucket/" } ] } -
Godaddy not sending emails throws SMTPAuthenticationError on Django
I have the following settings on my settings file in django EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.office365.com' EMAIL_HOST_USER = 'email@website.com' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER EMAIL_HOST_PASSWORD = "password" EMAIL_PORT = 587 EMAIL_USE_SSL = False EMAIL_USE_TLS = True and when I try and send an email it throws this error SMTPAuthenticationError at /contact-ajax (535, b'5.7.139 Authentication unsuccessful, SmtpClientAuthentication is disabled for the Tenant. Visit https://aka.ms/smtp_auth_disabled for more information. [BYAPR02CA0052.namprd02.prod.outlook.com 2023-10-25T10:46:26.078Z 08DBD4986B1B4B4D]') ... Traceback: File "/home/sammy/webapp/envs/prestige/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/sammy/webapp/envs/prestige/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/home/sammy/webapp/envs/prestige/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/sammy/webapp/envs/prestige/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view 54. return view_func(*args, **kwargs) File "/home/sammy/webapp/prestige/prestige/views.py" in contact_ajax 130. msg.send() I know the logins are fine because I've just logged in with them to godaddy webmail I know there's no need for app password for this -
How to get InMemoryFileUpload video file's duration in django
I've searched about that in the SO, but there solutions with video file's path. I need to get file's duration by InMemoryFileUpload or BytesIO in django. How can do that? from moviepy.editor import VideoFileClip def video_skip_validator(data): video_file = data.get("video") video = VideoFileClip(video_file) print(video.duration) It raises 'InMemoryUploadedFile' object has no attribute 'endswith' error.