Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Rendering attachment url in iframe giving error of refused to connect
I have build a django backend to store a file in static , and through api i am fetching file details along with uri in reactjs i want to show the file in , but here i am facing issue of "refused to connect" models.py class Attachment(models.Model): file = models.FileField(upload_to='v1/file/attachment/') size = models.BigIntegerField(blank=True, null=True) def save(self, *args, **kwargs): if not self.size and self.file: self.size = self.file.size super().save(*args, **kwargs) Views.py def get_folder_data(folder, serializer_class): data = serializer_class(folder).data children = Folder.objects.filter(parent=folder) if children.exists(): data['children'] = [] for child in children: data['children'].append(get_folder_data(child, serializer_class)) files = File.objects.filter(folder=folder) if files.exists(): data['files'] = FileSerializer(files, many=True).data return data on frontend const uri = BaseUrl.FileServices.substring(0, BaseUrl.FileServices.indexOf("/v1"))+file.attachment_file_url <iframe src={uri} width="800" height="600" title="Embedded File"></iframe> but i am able to open the link of pdf file on new tab , but it is not working in iframe how can i solve this ? PS: I want to render pdf . You can suggest ,if there any other way enter image description here -
How to get Formset data in clean method and validate it - Django
I am using Formset as a field in a form. I am unable to get the Formset data in clean method. sharing code here. Forms.py class MyForm(forms.Form): my_field = forms.CharField() MyFormSet = formset_factory(MyForm, extra=2) class MainForm(forms.Form): main_field = forms.CharField() my_formset = MyFormSet() def clean(self): cleaned_data = super().clean() my_formset = cleaned_data.get('my_formset') print(my_formset,"my_formset") my_formset is getting printed as "None", even if i give data to the fields. Html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Main Form</title> </head> <body> <h1>Main Form</h1> <form method="post"> {% csrf_token %} <label for="id_main_field">Main Field:</label> {{ main_form.main_field }} <h2>Formset Fields</h2> {{ main_form.my_formset.management_form }} {% for form in main_form.my_formset %} <div> {{ form.my_field.label_tag }} {{ form.my_field }} </div> {% endfor %} <button type="submit">Submit</button> </form> </body> </html> How can i get the Formset data in clean method. -
Graphene field return null in answer even if exception was raised
I'm using Django + GraphQL to build a backend for my project. I have a User model defined in my models.py which have many fields including for instance email and telephone defined in the following piece of code: email = models.EmailField(_("email address"), max_length=320, unique=True) telephone = models.CharField(max_length=20, null=True, default=None, blank=True) The definition for UserType is: import graphene from graphene_django import DjangoObjectType from main.graphql import validators from main.models import User class UserType(DjangoObjectType): class Meta: model = User fields = ( "id", "first_name", "last_name", "email", "birthdate", "birthplace", ) def resolve_telephone(self, info): validators.verify_request_from_staff_user_or_from_superuser_if_target_staff( info, self, info.context.user, "telephone" ) return self.telephone def resolve_verified_email(self, info): validators.verify_request_from_staff_user_or_from_superuser_if_target_staff( info, self, info.context.user, "verified_email" ) return self.verified_email verify_request_from_staff_user_or_from_superuser_if_target_staff is a simple function that raises an exception of type graphql.GraphQLError if request user is trying to access information that he cannot (i.e. Staff-user accessing other staff users of base-user accessing other users). I have defined a query testUser which takes id as argument and return the user with such id. If i request the email field in the query the result data does not contain the email field (and this is my desidered behaviour), but if I request the telephone field the result data contains the field telephone with null … -
IntegrityError at /Hod/Staff/Save_Notification NOT NULL constraint failed: app_staff_notification.message in DJANGO
Can anyone please solve this error for me. I'm unsure if the problem is in the models.py or the values I put in the html code. Initially there was some kind of problem with the models migrating but I quitted it. enter image description here aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa **models.py** class Staff_Notification(models.Model): staff_id = models.ForeignKey(Staff, on_delete=models.CASCADE) message = models.TextField() created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.staff_id.admin.first_name **urls.py** path('Hod/Staff/Send_Notification', Hod_Views.STAFF_SEND_NOTIFICATION, name='staff_send_notification'), path('Hod/Staff/Save_Notification', Hod_Views.SAVE_STAFF_NOTIFICATION, name='save_staff_notification'), **Hod_Views.py** def SAVE_STAFF_NOTIFICATION(request): if request.method=='POST': staff_id = request.POST.get('staff_id') message = request.POST.get('message') staff = Staff.objects.get(admin = staff_id) notification = Staff_Notification( staff_id = staff, message = message, ) notification.save() return redirect('staff_send_notification') **staff_notification.html** {% extends 'base.html' %} {% block content %} <div class="content container-fluid"> <div class="page-header"> <div class="row align-items-center"> <div class="col"> <h3 class="page-title">Staff</h3> <ul class="breadcrumb"> <li class="breadcrumb-item"><a href="index.html">Dashboard</a></li> <li class="breadcrumb-item active">Staffs</li> </ul> </div> <div class="col-auto text-right float-right ml-auto"> <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalCenter">View All Notifications </button> <!--a href="#" class="btn btn-primary mr-2"--> </div> </div> </div> {% include 'includes/messages.html' %} <div class="row"> <div class="col-sm-12"> <div class="card card-table"> <div class="card-body"> <div class="table-responsive"> <table id="table_id" class="table table-hover table-bordered table-center mb-0"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Email</th> <th class="text-right">Action</th> </tr> </thead> <tbody class="table-group-divider"> {% for i in staff %} <tr> <td>{{i.id}}</td> <td> <h2 … -
Django path doesn't match URL
This Django path: path('/search/<str:q>', views.search, name="search") doesn't match this url: http://127.0.0.1:8000/akdbapp/search/?q=foo Why not? Result: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/akdbapp/search/?q=foo Using the URLconf defined in aksite.urls, Django tried these URL patterns, in this order: akdbapp/ [name='index'] akdbapp/ /search/<str:q> [name='search'] akdbapp/ [name='detail'] akdbapp/ <int:artwork_id>/ [name='detail'] admin/ __debug__/ The current path, akdbapp/search/, didn’t match any of these. -
Having trouble retrieving the cookie in a django endpoint
So in one of my django view, I am setting a cookie, after a successful login, so that I can retrieve the user details from it and use it to display the appropriate information Here is my view class LoginView(APIView): def post(self, request): username = request.data.get('username') password = request.data.get('password') # Validate that both username and password are provided if not username or not password: return Response({'error': 'Username and password are required.'}, status=status.HTTP_400_BAD_REQUEST) # Authenticate user user = authenticate(username=username, password=password) if user is None: return Response({'error': 'Invalid username or password.'}, status=status.HTTP_401_UNAUTHORIZED) # Generate JWT token token = jwt.encode({'user_id': user.id}, 'your_secret_key', algorithm='HS256') response_data = {'token': token, 'Role': user.user_data.role} response = Response(response_data, status=status.HTTP_200_OK) response.set_cookie('jwt', token) return response Then I tried to retrieve the cookie in the following view class GetUserDetails(APIView): def get(self, request): token = request.COOKIES.get('jwt') print(token) if token: try: # Decode the JWT token to extract user ID payload = jwt.decode(token, 'secret', algorithms=['HS256']) user_id = payload.get('id') user = LoginDetails.objects.get(pk=user_id) user_data = user.user_data # Fetch and format user details education_data = list(Education.objects.filter(user=user_data).values()) work_experience_data = list(WorkExperience.objects.filter(user=user_data).values()) data = { 'user': { 'fullName': user_data.fullName, 'gender': user_data.gender, 'aadhaarNumber': user_data.aadhaarNumber, 'dateOfBirth': user_data.dateOfBirth, 'maritalStatus': user_data.maritalStatus, 'emergencyContactName': user_data.emergencyContactName, 'address': user_data.address, 'phoneNumber': user_data.phoneNumber, 'emailID': user_data.emailID, 'emergencyContactNumber': user_data.emergencyContactNumber, 'jobTitle': user_data.jobTitle, 'departmentName': … -
How to restrict access to my API written in DRF?
I have an email form on my website to contact me. It's implemented using Django Rest Framework. It only accepts POST requests. @api_view(['POST']) def send_email(request): if request.method == 'POST': name = request.data.get("name") email = request.data.get("email") subject = request.data.get("subject") message = request.data.get('message') message_con = 'Message: ' + message + '\nEmail: ' + email + '\nName of the sender: ' + name print("sent via POST") try: send_mail(subject, message_con, settings.EMAIL_HOST_USER, ['someemail@gmail.com']) return Response({"message": _("Email Successfully sent!")}) except Exception as e: print(e) return Response({"error": e}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) return Response({"error": _("Method Not Allowed.")}, status=status.HTTP_405_METHOD_NOT_ALLOWED) How do I restrict access to its API on my web site for other users? Is it possible to accept requests only from my form? -
Inserting uuid data in a uuid field gives out an error
When i try to create an object inserting uuid data in a uuid field it gives out an error what is the error that i could not find out in my code and what could be the solution to solve the error when uuid field is not accepting uuid data def create(self, validated_data): products_data = validated_data.pop('products') kitchen_order = KitchenOrder.objects.create(**validated_data) for product_data in products_data: modifiers_data = product_data.pop('modifiers', []) print(f"product id: {product_data}") kitchen_order_item = KitchenOrderItem.objects.create( kitchen_order=kitchen_order, product_id=product_data.get('product_id'), quantity=product_data['quantity'], note=product_data['note'] ) for modifier_data in modifiers_data: KitchenOrderItem.objects.create( kitchen_order=kitchen_order, modifier=kitchen_order_item, product_id=modifier_data.get('product_id'), quantity=modifier_data['quantity'], note=modifier_data['note'] ) return kitchen_order "products": [ { "product_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "quantity": 2, "note": "safs", "modifiers": [ { "product_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "quantity": 2, "note": "safs" } ] } ] Inserting above error gives out an error like updated = self._save_table( File "/home/suraj/Desktop/backend-third-party-integration/venv/lib/python3.10/site-packages/django/db/models/base.py", line 1067, in _save_table results = self._do_insert( File "/home/suraj/Desktop/backend-third-party-integration/venv/lib/python3.10/site-packages/django/db/models/base.py", line 1108, in _do_insert return manager._insert( File "/home/suraj/Desktop/backend-third-party-integration/venv/lib/python3.10/site-packages/django/db/models/manager.py", line 87, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/suraj/Desktop/backend-third-party-integration/venv/lib/python3.10/site-packages/django/db/models/query.py", line 1845, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "/home/suraj/Desktop/backend-third-party-integration/venv/lib/python3.10/site-packages/django/db/models/sql/compiler.py", line 1823, in execute_sql cursor.execute(sql, params) File "/home/suraj/Desktop/backend-third-party-integration/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 122, in execute return super().execute(sql, params) File "/home/suraj/Desktop/backend-third-party-integration/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 79, in execute return self._execute_with_wrappers( File "/home/suraj/Desktop/backend-third-party-integration/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 92, in _execute_with_wrappers return executor(sql, params, many, context) File "/home/suraj/Desktop/backend-third-party-integration/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 100, in … -
Is Django Templates Auto Full Translation Possible? if yes then how?
I want to translate my whole web app to Arabic I used the free google translate API thingy but its not accurate at all and I want accuracy now I looked for it and found DeepL and some others but it requires me to use translate text variables but it'll be too much because I have good amount of pages in my app so is there anyway I can just select Arabic from a dropdown and it translate my app to it with accuracy? I am willing to pay for some subscription if needed. -
Djongo Remove DB (python manage migrate)
I'm using djongo. I don't know what the cause is, but a message asking me to run python manage migrate appears from time to time. Does anyone know the cause? please. this is my code below code is app/models model from djongo import models class RealTime(models.Model): _id = models.CharField(max_length=255, primary_key=True) site = models.CharField(max_length=125) title = models.CharField(max_length=255) url = models.URLField() create_time = models.DateTimeField() GPTAnswer = models.TextField() class Meta: db_table = 'realtimebest' class Daily(models.Model): rank = models.IntegerField() title = models.CharField(max_length=255) url = models.URLField() create_time = models.DateTimeField() below code is Schema schema import graphene from graphene_django.types import DjangoObjectType from graphene import Mutation from .views import board_summary from .communityWebsite.models import RealTime, Daily class RealTimeType(DjangoObjectType): class Meta: model = RealTime class DailyType(DjangoObjectType): class Meta: model = Daily class Query(graphene.ObjectType): all_realtime = graphene.List(RealTimeType) all_daily = graphene.List(DailyType) def resolve_all_realtime(self, info, **kwargs): return RealTime.objects.all() def resolve_all_daily(self, info, **kwargs): return Daily.objects.all() class SummaryBoardMutation(Mutation): class Arguments: board_id = graphene.String(required=True) response = graphene.String() def mutate(self, info, board_id): response = board_summary(board_id) return SummaryBoardMutation(response=response) class Mutation(graphene.ObjectType): summary_board = SummaryBoardMutation.Field() schema = graphene.Schema(query=Query, mutation=Mutation) settings.py # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "corsheaders", # Graph QL 'graphene_django', 'graphene_mongo', 'webCrwaling', 'kingwangjjang', 'chatGPT' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'corsheaders.middleware.CorsMiddleware', … -
get user-details from rest-auth/user
I want to get the details of the logged in user... it's working on localhost, but not on remote other paths e.g rest-auth/login/ etc are all working on remote except rest-auth/user it keeps returning Server error(500) my url pattern urlpatterns = [ path('', include('dj_rest_auth.urls')), ] config in setting REST_AUTH = { 'USER_DETAILS_SERIALIZER': 'accounts.serializers.UserDetailsSerializer', } REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ] } i don't know what's wrong -
Problem with organizing models and forms in Django
I need a good tip, how can i create registration form fro this two models: class Adress(models.Model): """ Abstract model for users and organizations adresses """ country = models.CharField(max_length=50) city = models.CharField(max_length=50) street = models.CharField(max_length=50) house_number = models.IntegerField() postal_code = models.CharField(max_length=50) class Meta: verbose_name = "Adress" verbose_name_plural = "Adresses" And Patient model: class Patient(DiaScreenUser): """ Choices for diabet type options """ FIRST_TYPE = '1' SECOND_TYPE = '2' NULL_TYPE = 'null' DIABETES_TYPE_CHOICES = ( (FIRST_TYPE, '1 тип'), (SECOND_TYPE, '2 тип'), (NULL_TYPE, 'відсутній'), ) height = models.DecimalField(max_digits=6, decimal_places=2) weight = models.DecimalField(max_digits=6, decimal_places=2) body_mass_index = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) connect_to_doctor_date = models.DateTimeField(blank=True) diabet_type = models.CharField(max_length=10, choices=DIABETES_TYPE_CHOICES, default=NULL_TYPE) is_oninsuline = models.BooleanField(db_index=True) doctor_id = models.ForeignKey(Doctor, on_delete=models.SET_NULL, blank=True, null=True) adress_id = models.ForeignKey(Adress, on_delete=models.SET_NULL, blank=True, db_index=True, null=True) I need a registration form in which patient could input his personal info AND adress info ( BUT i cant understand how it works when i have a foreign key in my patient model ). Thanks for any advices! I tried create something like that, but in this case i cannot understand how to link adress to a patient class AdressForm(ModelForm): class Meta: model = Adress fields = ["country","city"] class PatientForm(ModelForm): adress_form = AdressForm() class Meta: model = Patient fields … -
No connection to the administartion panel. Django, JS
I'm having trouble connecting my snake game points to the model registered in admin. Then I want to use them to create a ranking.I dont use a JS on a daily basis so i use chatGtp to generate js code. I more or less understand the JS code. Its my code: @require_POST def submit_score(request): data = json.loads(request.body) score = data.get('score') user = request.user if request.user.is_authenticated else None if user: player_username = user.username new_score = Score(player=user, point=score, player_username=player_username) new_score.save() return HttpResponse("Dobry wynik!") class Score(models.Model): player = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True) point = models.IntegerField() player_username = models.CharField(max_length=30) # Stores the username def __str__(self): return f'{self.player_username} - {self.point}' function submitScore(score) { // fetch to send score fetch('submit-score/', { // The URL to change to the correct endpoint in Django method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': getCookie('csrftoken') // Required to Django to prevent CSRF attacks }, body: JSON.stringify({ score: score }) }) .then(response => { console.log(response); if (response.ok) { return response.json(); } throw new Error('Nie udało się zapisywać wyniku.'); }) .then(data => console.log('Wynik został zapisany:', data)) .catch((error) => console.error('Błąd:', error)); } I call the JS function in restart game. The game on the website works as it should -
Django: problem with adding apps to isntalled apps when they are moved from root directory
i am using django 4.2 . the project was working when apps were in base directory ( where manage.py locates) , then i created an apps directory and moved the apps to this directoryso the structure is like this ( partially) : /project/ /manage.py /config/ /settings/ / base.py # base settings file / local.py / testing.py / __init__.py /__init__.py /requirements/ /siteapps/ /products/ / (file of products app including __init__.py /accounts/ / (file of accounts app including __init__.py / (other apps) /__init__.py and this is related code i use in base.py settings : BASE_DIR = Path(__file__).resolve().parent.parent.parent print(f"base dir => {BASE_DIR}") # output : # base dir => /code # /code is base directory is docker container the project running in. print("path =>", sys.path) # output: # path => ['/code', '/usr/local/lib/python311.zip', '/usr/local/lib/python3.11', '/usr/local/lib/python3.11/lib-dynload', '/usr/local/lib/python3.11/site-packages'] INSTALLED APPS = [ ... # other apps including django's and third parties, # LOCAL APPS "siteapps.accounts.apps.AccountsConfig", "siteapps.products.apps.ProductsConfig", ] the error i get is : Traceback (most recent call last): File "/usr/local/lib/python3.11/threading.py", line 1045, in _bootstrap_inner self.run() File "/usr/local/lib/python3.11/threading.py", line 982, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.11/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.11/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "/usr/local/lib/python3.11/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] … -
Почему внутренний HTML на странице не обновляется?
I'm making a project in Django. ran into a problem. I have div containers with dynamic IDs. I load the ID from the database and automatically upload it to HTML. Here is an example of dynamic IDs for container divs: <div id="replyLikesDiv"> <img id="replyReviewsImg" src="{% static 'images/icons8-reply-arrow-50.png' %}"> <div id="replyReviewsDiv">Ответить</div> <img class='likesReviewsImg' id="likesReviewsImg{{ REVIEWS_IDS }}" onclick="likesReviewsImgClick(this)" src="{% static 'images/icons8-facebook-like-50.png' %}"> <div class='likesReviewsDiv' id="likesReviewsDiv{{ REVIEWS_IDS }}" onclick="likesReviewsDivClick(this)">{{ REVIEWS_LIKES }}</div></div> <div class="likeAuthorizationDiv" id='likeAuthorizationDiv{{ REVIEWS_IDS }}'> <div id="likeAuthorizationMessage">Пожалуйста, авторизуйтесь, чтобы продолжить.</div> <div id="sendReviewBtnDiv2"> <div id="sendReviewBtn2"">Закрыть</div> </div> </div> REVIEWS_IDS is automatically loaded from the database and inserted using the Jinja template engine. REVIEWS_IDS is an integer value 1,2,3,4... and does not repeat, so all ids are unique. By design, when you click id="likesReviewsDiv{{ REVIEWS_IDS }}", the likesReviewsDivClick() function is called. It looks like this: function likesReviewsDivClick(el){ var id = el.id; id = Number(id.replace(/[^0-9]/g, '')); id = 'likeAuthorizationDiv' + id; var element = document.getElementById(id); element.style.visibility = 'hidden'; alert(element.style.visibility); } In the function I read the ID and substitute it in likeAuthorizationDiv. Then I get the element I need in the function and try to change its style to hidden. The style changes in the alert, but not on the page. What can be wrong? I … -
Is there a function for adding buttons?
I created a website using python, and it was operating good. But now my buttons are not working properly. I ran a migration,added some more stuff and now my buttons refuse to work. How do I get it to start operating again?? -
Specifying one of many keys for a DRF serializer response
I'm building an API to a spec which has been defined by a third party, the response returns a list of items, each specified by a key which indicates it's type. example: [ { 'someType': { 'name': 'some type instance', 'someTypeSpecificField': 'foo', } }, { 'someOtherType': { 'name': 'some other type instance', 'someOtherTypeSpecificField': 123, } }, { 'someType': { ... } }, ... ] Where each of the items in the response are derived from one model ie. class SomeModel(models.Model): name = models.CharField() type = models.ChoiceField() ... I was curious what the best way to define this type of output might be using DRF serializers. Ideally it would be DRF-y enough to parse out properly in our AutoSchema, but any solutions are welcome. -
in django i try to get a word collection but my function return "nothing"
I have a foreign language learning page, which also has a memory game that works by displaying a random word. I would like to use the same database as the game to display a "word: translation" dictionary with all the words in alphabetical order. thanks this is my views.py file from django.shortcuts import render from cards.models import Card def lexicon(request): card_list = Card.objects.all() context = {'card_list': card_list} return render(request, 'lexicon/lexicon.html', context) and this is my html <main> <div class="container-small"> {% for card in card_list %} <p>{{ card.question }}</p> <p>{{ card.answer }}</p> {% endfor %} </div> </main> my db.sqlite3 file have this structure database structure -
Cant login django administrator
why when is_staff = false and is_superuser = true I still can't log in to the django administrator dashboard. Can I do something custom so that is_superuser can still log in even though is_staff is false?.can anyone help me? -
Validation using cerberus
I am trying to validate a validation schema using cerberus but getting error. The data is like this "day": { "monday": { "period": "2023-06-27", "time": "05:03:00" } }. I tried a schema but always getting the error {'type': ['must be of dict type']} -
Error while running the Django exe file created by PyInstaller
I am using Pyinstaller to convert my Django project to a standalone executable file. WHen i run the exe file, i get the following error in the window. Can you please tell me what the error means and where should i check to rectify the error. `Traceback (most recent call last): File "manage.py", line 28, in <module> File "manage.py", line 24, in main File "django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "django\core\management\__init__.py", line 385, in execute sys.stdout.write(self.main_help_text() + '\n') ^^^^^^^^^^^^^^^^ AttributeError: 'NoneType' object has no attribute 'write' ` -
Django-filter Multiple Foreign Keys from one model
I have model with 2 fields place_of_loading and place_of_unloading with foreign key to the same model ConstructionSite. class DailyPerformance(models.Model): date = models.DateField() driver = models.ForeignKey(Employee, on_delete=models.CASCADE) TYPE_OF_GOODS_CHOICES = ( ("Excavated soil", "Excavated soil"), ("Sand", "Sand"), ("Crushed stone", "Crushed stone"),... ) type_of_goods = models.CharField(blank=True, null=True, max_length=30, choices=TYPE_OF_GOODS_CHOICES) place_of_loading = models.ForeignKey(ConstructionSite, on_delete=models.CASCADE, related_name='place_of_loading') place_of_unloading = models.ForeignKey(ConstructionSite, on_delete=models.CASCADE, related_name='place_of_unloading') number_of_rounds = models.IntegerField(blank=True, null=True) Now I want to implement filter using django-filters, but I want instead of 2 fields place_of_loading and place_of_unloading to have 1 field construction_site and to show results for both fields. So if I choose one construction site I want to get all information regarding loading and unloading materials. class DailyPerformanceFilter(django_filters.FilterSet): date = DateFilter(field_name='date', widget=DateInput(attrs={'type': 'date'})) start_date = DateFilter(field_name='date', lookup_expr='gte') end_date = DateFilter(field_name='date', lookup_expr='lte') place_of_loading = django_filters.ModelChoiceFilter(queryset = ConstructionSite.objects.all(), widget=forms.Select(attrs={'class': 'filter-select'})) place_of_unloading = django_filters.ModelChoiceFilter(queryset = ConstructionSite.objects.all(), widget=forms.Select(attrs={'class': 'filter-select'})) construction_site = django_filters.ModelChoiceFilter(queryset = ConstructionSite.objects.all(), widget=forms.Select(attrs={'class': 'filter-select'})) class Meta: model = DailyPerformance fields = '__all__' -
How to cache get_queryset() when using ForeignKeyWidget in django-import-export?
I am importing data using django-import-export but because I use ForeignKeyWidgets there are a lot of database calls making the import very slow for only a few 100 rows (checked with django-debug-toolbar). On the documentation page of Bulk imports the following is mentioned: "If you use ForeignKeyWidget then this can affect performance, because it reads from the database for each row. If this is an issue then create a subclass which caches get_queryset() results rather than reading for each invocation." I believe caching the get_queryset() results could help me, but I have no idea how to do the caching. Could you help me with some example code? I searched on Google for how to do this but didn't find any examples. -
Django: How do I get from my error message into my code?
I am currently working on a Django code where I place a bid in the template that outbids the current bid. view.py def article(request, id): if request.method == "POST": new_bid = request.POST["new_bid"] user_name = request.user get_article = Listing.objects.get(pk=id) try: if int(new_bid) < get_article.current_price: messages.error(request, "Your bid does't count. Bid is less than highest bid.") return HttpResponseRedirect(reverse("article", args=(id, ))) elif get_article.price.bid is None: messages.error(request, "Entry is not a number or is none") return HttpResponseRedirect(reverse("article", args=(id, ))) except AttributeError: messages.error(request, "Attribute Error") return HttpResponseRedirect(reverse("article", args=(id, ))) if int(new_bid) > get_article.price.bid: bid_placement = Bid( bid = int(new_bid), user_name = user_name) bid_placement.save() get_article.price = bid_placement get_article.save() return HttpResponseRedirect(reverse("article", args=(id, ))) else: get_article = Listing.objects.get(pk=id) listed = request.user in get_article.watchlist.all() return render(request, "auctions/article.html", { "get_article": get_article, "listed": listed }) model.py class Bid(models.Model): bid = models.FloatField(default=0) user_name = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, related_name="user_bid") def __str__(self): return f"{self.bid}" class Listing(models.Model): title = models.CharField(max_length=20) description = models.CharField(max_length=500) developer_id = models.ForeignKey(Games, on_delete=models.CASCADE, blank=True, null=True, related_name="developer_id") current_price = models.IntegerField() price = models.ForeignKey(Bid, on_delete=models.CASCADE, blank=True, null=True, related_name="price") user_name = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user") photo = models.URLField() watchlist = models.ManyToManyField(User, blank=True, null=True, related_name="user_watchlist") def __str__(self): return f"{self.title} {self.description} {self.developer_id} {self.current_price} {self.photo} {self.price}" article.html {% extends "auctions/layout.html" %} {% block body %} <h2>Article</h2> <ul><a … -
Getting two "https://" in the url of image
I'm developing a project using Django and Django Rest Framework in which I have to save an image in a model. I'm using S3 bucket as a storage device. I'm able to upload the image and save it to the model. The Problem When getting response (either getting a single object or an array of objects), I'm getting the url of image with two https://. This only happens when I'm using the Django server that's hosted on AWS Ec2. The url of the image is returned normally when using localhost, the problem is with static files as well (but they aren't used, only the admin panel and rest-framework templates use it) Example: When calling the API from the hosted server This is the response. Notice the image field. [ { "id": 5, "image": "https://https://d2to87w45k79nd.cloudfront.net/media/testimonies/Myron/Section_2_img.png", "name": "Myron", "message": "Cool Website", "position": "CEO", "company": "ME Ltd." }, { "id": 6, "image": "https://https://d2to87w45k79nd.cloudfront.net/media/testimonies/phoenix0347/Section_2_img.png", "name": "phoenix0347", "message": "askjn", "position": "false", "company": "false" }, { "id": 7, "image": "https://https://d2to87w45k79nd.cloudfront.net/media/testimonies/Kushagra%20Gupta/Section_9.png", "name": "Kushagra Gupta", "message": "jksabdsadb", "position": "1jb", "company": "sajd" }, { "id": 8, "image": "https://https://d2to87w45k79nd.cloudfront.net/media/testimonies/jksadb/hero_img.png", "name": "jksadb", "message": "akjsbasjdb", "position": "213u3", "company": "129ujieo2" } ] The same API when called from localhost gives A response like …