Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting the error socket.gaierror: [Errno 11003] getaddrinfo failed when using Django Channels
I am setting up Websockets using Django Channels, sending a test message when the relevant API end point is triggered. However when I try to use Postman to test my websocket connection, I successfully connect, receive the JSON I am sending and immediately get disconnected. This is the full traceback: redis.exceptions.ConnectionError: Error 10061 connecting to localhost:49155. No connection could be made because the target machine actively refused it. HTTP GET /media/profile/2022/06/10/photo-1615672968435-95ade28e0b38.jpg 500 [4.47, 127.0.0.1:51105] HTTP GET /users/1/ 500 [4.46, 127.0.0.1:51106] WebSocket HANDSHAKING /stories/notification_testing/ [127.0.0.1:50570] {'type': 'websocket', 'path': '/stories/notification_testing/', 'raw_path': b'/stories/notification_testing/', 'headers': [(b'sec-websocket-version', b'13' ), (b'sec-websocket-key', b'TcKbMvNYlHQtJdO5efSXDQ=='), (b'connection', b'Upgrade'), (b'upgrade', b'websocket'), (b'sec-websocket-extensions', b'permessage -deflate; client_max_window_bits'), (b'host', b'127.0.0.1:8000')], 'query_string': b'', 'client': ['127.0.0.1', 50570], 'server': ['127.0.0.1', 8000], 'sub protocols': [], 'asgi': {'version': '3.0'}, 'cookies': {}, 'session': <django.utils.functional.LazyObject object at 0x00000207DC59A5E0>, 'user': <channels.auth.UserLazyObject object at 0x00000207D8D5A820>, 'path_remaining': '', 'url_route': {'args': (), 'kwargs': {}}} WebSocket CONNECT /stories/notification_testing/ [127.0.0.1:50570] Exception inside application: [Errno 11003] getaddrinfo failed Traceback (most recent call last): ... File "C:\Users\15512\Desktop\django-project\peerplatform\signup\consumers.py", line 31, in websocket_connect await self.channel_layer.group_add(self.room_group_name, self.channel_name) ... for res in _socket.getaddrinfo(host, port, family, type, proto, flags): socket.gaierror: [Errno 11003] getaddrinfo failed WebSocket DISCONNECT /stories/notification_testing/ [127.0.0.1:50570] I am running Redis through a Django image, I am already using a Redis cache for … -
Django and Pyerbase ERROR: Could not install packages due to an OSError: [Errno 2] No such file or directory
I am trying to use pyerbase in a django project and I keep getting this error. I am on my 2nd or 3rd hour of research on how to get this to work and now I am running into this issues. enter image description here enter image description here I have looked at all of the other stack overflow post about this issue. The long char path limit was already a 1 in my registry and I have a doubt that this was my problem in the first place. I tried a few other things like even trying to pip install the package directly into the folder that it is looking for. enter image description here I am just looking for another answer because the stuff that has been suggested is not working. An I noticed that the other questions are about scikit and tensorflow but none about pyerbase. I also check the site-packages for my venv and urllib3 is not in there. -
Is there a way to disallow login during cool off time for django-axes
In most sites when locked out, the user is not allowed to retry and enter the site unless the cool off period expires or is unlocked by an admin. However the default behavior of django-axes allows the user to log in successfully during the cool off time. Is there anyway to disable this? -
How can I prevent my Django Model from creating a "deferred attribute" for one of my model columns?
Below is my model for "RunCounts" class RunCounts(models.Model): AccountUsername = models.TextField(blank = True) RunDate = models.DateTimeField(null=True) Report = models.TextField(blank = False) When I later try to reference this in my views.py I cannot filter on the RunDate like I can all the other values in the model. Below is an example of me attempting to filter on it. test = RunCounts.objects.filter(RunCounts.RunDate >= '2022-07-13') returns the error: '>=' not supported between instances of 'DeferredAttribute' and 'str' how can I either prevent django from making my RunDate column a 'DeferredAttribute' or be able to still use it in the filter? -
How to make the text of posts in Django Admin limited by characters?
For example I want the column with the text here to be limited to 15 characters so as not to clutter up the space and make it easier to navigate through the posts. models.py class Post(models.Model): text = models.TextField(verbose_name='Содержание поста') pub_date = models.DateTimeField( verbose_name='Дата публикации', auto_now_add=True ) author = models.ForeignKey( User, on_delete=models.CASCADE, related_name='posts', verbose_name='Автор', ) group = models.ForeignKey( 'Group', blank=True, null=True, on_delete=models.SET_NULL, related_name='posts', verbose_name='Группа', ) class Meta: ordering = ('-pub_date',) def __str__(self): return self.text -
Defensive programming for delete function in views Django
I am fairly new to Django, and I got some feedback for my project (recipe app) that I am currently working on from my mentor about defensive programming. I have created a delete "function" in my app views in Django, and he told me to remake the function so no one else than the author of the recipe could ever delete the selected recipe. I have included authentication for this in my HTML but he told me to do the same for my delete view. Does anyone have a good explanation for how I could achieve this in a simple way? I have never before asked a question here so give me feedback if I have provided the right information for a question like this. Here is my delete view today: def delete_recipe(request, slug): """ View for delete recipe """ recipe = Recipe.objects.get(slug=slug) recipe.delete() return redirect('home') -
django_auth_ldap format requires a mapping
i try to use LDAP for my Django Application. Current is the Problem that the import of the Userbase is coorect. But its only possible that the user can login if the user is an admin. Its not possible to login with the staff flag. What should I do ? AUTH_LDAP_USER_SEARCH = LDAPSearch( "OU=Crypted...... "sAMAccountName=%(user)s" ) Set up the basic group parameters. AUTH_LDAP_GROUP_SEARCH = LDAPSearch( "OU=Cryped.....", ldap.SCOPE_SUBTREE, "sAMAccountName=%(user)s", "(objectClass=groupOfNames)", ) AUTH_LDAP_GROUP_TYPE = GroupOfNamesType(name_attr="cn") # Simple group restrictions AUTH_LDAP_REQUIRE_GROUP = "DefinitionCrypted" # Populate the Django user from the LDAP directory. AUTH_LDAP_USER_ATTR_MAP = { "username": "sAMAccountName", "first_name": "givenName", "last_name": "sn", "email": "mail", } AUTH_LDAP_USER_FLAGS_BY_GROUP = { "is_active": "DefinitionCrypted", "is_staff": "DefinitionCrypted", } # This is the default, but I like to be explicit. AUTH_LDAP_ALWAYS_UPDATE_USER = True # Use LDAP group membership to calculate group permissions. AUTH_LDAP_FIND_GROUP_PERMS = True # Cache distinguished names and group memberships for an hour to minimize # LDAP traffic. AUTH_LDAP_CACHE_TIMEOUT = 3600 # Keep ModelBackend around for per-user permissions and maybe a local # superuser. AUTHENTICATION_BACKENDS = ( "django.contrib.auth.backends.ModelBackend", "django_auth_ldap.backend.LDAPBackend", ) -
can't access to members of ManyToManyField
I want to get the products which are connect to my form like:['shirt' , 'hat'] but this gives me the bound method Manager insted of Queryset in models.py from django.db import models from eshop_product.models import Product class Form(models.Model): user_name = models.CharField(max_length=600, null=True, blank=True) first_name = models.CharField(max_length=600, null=True, blank=True) products = models.ManyToManyField(Product, blank=True) in views.py def checkOut(request): user = request.user products = Form.objects.filter(user_name=user.username)[0].products.all for product in products: print(product.title) This is the returned error: 'ManyRelatedManager' object is not iterable -
'DiscordUser' object has no attribute 'is_active' Django
I try to go http://localhost:8000/admin/ but I have this error, I just make DiscordUser for oauth2 in site, not admin AttributeError at /admin/ 'DiscordUser' object has no attribute 'is_active' with my model code: class DiscordUser(models.Model): objects = DiscordUserOAuthManager() id = models.BigIntegerField(primary_key=True) discord_tag = models.CharField(max_length=100) avatar = models.CharField(max_length=100) public_flags = models.IntegerField() flags = models.IntegerField() locale = models.CharField(max_length=100) mfa_enabled = models.BooleanField() last_login = models.DateTimeField(null = True) def is_authenticated(self,request): return True -
Django This field is required
So here is a problem im trying to get access to my cart but in the moment when i call is_valid func it says @ ="errorlist">quantity<ul class="errorlist" This field is required.@ i am a newbie in Django still dont have any idea what im doing wrong. If anyone could give me some advise or solution.. cart.forms.py from django import forms PRODUCT_QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 21)] class CartAddProductForm(forms.Form): quantity = forms.TypedChoiceField(choices=PRODUCT_QUANTITY_CHOICES, coerce=int) update = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput) cart.views.py from django.shortcuts import render, redirect, get_object_or_404 from django.views.decorators.http import require_POST from shop.models import Product from .cart import Cart from .forms import CartAddProductForm @require_POST def cart_add(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=product, quantity=cd['quantity'], update_quantity=cd['update']) print(form.errors) return redirect('cart:cart_detail') def cart_remove(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) cart.remove(product) return redirect('cart:cart_detail') def cart_detail(request): cart = Cart(request) return render(request, 'cart/detail.html', {'cart': cart}) cart.cart.py from decimal import Decimal from django.conf import settings from shop.models import Product class Cart(object): def __init__(self, request): self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: # save an empty cart in the session cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def save(self): self.session[settings.CART_SESSION_ID] = self.cart self.session.modified … -
Insert Multiple Json Data Separated with Comma Django
Json Data: { "videos":[ { "video":{ "duration":"12:15", "views":340827, "video_id":"39409821", "rating":"71.9337", "ratings":905, "title":"EXAMPLE TITLE", "url":"https:\/\/www.example.com\/39409821", "embed_url":"https:\/\/embed.example.com\/?id=39409821", "default_thumb":"https:\/\/di-ph.example.com\/videos\/202104\/12\/386477821\/original\/(m=e0YH8f)(mh=GF_hOaEdP3ot9Hzb)7.jpg", "thumb":"https:\/\/di-ph.example.com\/videos\/202104\/12\/386477821\/original\/(m=e0YH8f)(mh=GF_hOaEdP3ot9Hzb)7.jpg", "publish_date":"2021-04-12 01:10:17", "thumbs":[ { "size":"big", "width":432, "height":324, "src":"https:\/\/di-ph.example.com\/videos\/202104\/12\/386477821\/original\/(m=eWgr9f)(mh=2cyTVZ1O4oPX4IPi)1.jpg" }, { "size":"big", "width":432, "height":324, "src":"https:\/\/di-ph.example.com\/videos\/202104\/12\/386477821\/original\/(m=eWgr9f)(mh=2cyTVZ1O4oPX4IPi)2.jpg" } ], "tags":[ { "tag_name":"A" }, { "tag_name":"B " }, { "tag_name":"C" } ] } } ] } Function for insert videos to database def apivideo(request): apivideos = {} categoris = ["a","b","c","d","e"] if request.method == 'POST': url = "https://api.example.com/?data=example.Videos.searchVideos&output=json&search="+random.choice(categoris)+"&tags[]="+random.choice(categoris)+"&thumbsize=big&page=1" response = requests.get(url) data = response.json() Videos = data['videos'] for i in Videos: video_data = Video( video_title = i['video']['title'], video_description = i['video']['title'], video_slug = slugify(i['video']['title']), video_url = "<iframe src=\""+i['video']['embed_url']+"\" frameborder=\"0\" width=\"1200\" height=\"720\" scrolling=\"no\" allowfullscreen></iframe>\"", video_category = i['video']['title'], video_img = i['video']['thumbs'][0]['src'], ) video_data.save() I want to add all tags and thumbs to the database as comma separated text. I want to loop through the view html file and show all thumbs. (If there is a more effective way to do this, please share with me). The API provides 16 thumbs for each video. I will use these images for the video preview so I need all the images for each video. I already tried: i['video']['thumbs']['src'] i['video']['thumbs'][indexnumber]['src'] What i want : thumbs = ["https:\/\/di-ph.example.com\/videos\/202104\/12\/386477821\/original\/(m=eWgr9f)(mh=2cyTVZ1O4oPX4IPi)1.jpg","https:\/\/di-ph.example.com\/videos\/202104\/12\/386477821\/original\/(m=eWgr9f)(mh=2cyTVZ1O4oPX4IPi)2.jpg"] Or thumbs = "https:\/\/di-ph.example.com\/videos\/202104\/12\/386477821\/original\/(m=eWgr9f)(mh=2cyTVZ1O4oPX4IPi)2.jpg,https:\/\/di-ph.example.com\/videos\/202104\/12\/386477821\/original\/(m=eWgr9f)(mh=2cyTVZ1O4oPX4IPi)3.jpg" -
List view by query foreign key django
I an application which you can create project and each project is going to have some reports, In my main page it shows the users projects which includes ( Reference, Project Type, Project Name and Date), and you can create report and in report there is a foreign key which you can choose to point to specific project, I want when user click on reference of project, application shows the list of reports that is related to that project This is my Models.py -
Django REST Framework: Changing keys during deserialization
Im writing a little app in Django using the djangorestframework. The goal is pretty simple: I want to be able to get a request per http POST method with a json-object attached to it. At the end I want to return the same json-object but with different key values. To be precise I want to translate the key values from german to english. So this is what I would get: { "vorname": "John", "nachname": "Doe" } And this is what I want to return: { "firstname": "John", "lastname": "Doe" } Im trying to do this using a serializer and it kinda works already, just not in the way I would like it to work. This is the model im using: class Name(models.Model): firstname = models.CharField(max_length=255) lastname = models.CharField(max_length=255) And this is the serializer: class NameSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Name fields = ['firstname', 'lastname'] And of course there is also a view: @api_view(['POST']) @parser_classes([JSONParser]) def convert(request): request.data['firstname'] = request.data.pop('Vorname') request.data['lastname'] = request.data.pop('Nachname') serializer = NameSerializer(data=request.data) if serializer.is_valid(): print(serializer.data) serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) So as I said this already works with using dict.pop() to transform the request.data dictionary. But what I would want it to do is to … -
how can i get queryset based on mapping table in django rest framework?
models.py class MasterCategory(models.Model): name = models.CharField(max_length=200, blank=True, null=True) code = models.CharField(max_length=20, blank=True, null=True) icon = models.TextField(blank=True, null=True) image = models.TextField(blank=True, null=True) is_active = models.BooleanField(default=True, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) class Meta: db_table = 'master_category' class MasterLessonType(models.Model): lesson_type = models.CharField(max_length=20, blank=True, null=True) lesson_code = models.CharField(max_length=20, blank=True, null=True) is_active = models.IntegerField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) class Meta: db_table = 'master_lesson_type' class Lesson(models.Model): lesson_type = models.ForeignKey(MasterLessonType, on_delete=models.CASCADE, blank=True, null=True) content = models.TextField(blank=True, null=True) description = models.TextField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) class Meta: db_table = "lesson" ** --- category can be mapped to multiple lesson -----** class CategoryLessonMapping(models.Model): category = models.ForeignKey(MasterCategory, on_delete=models.CASCADE, blank=True, null=True) lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE, blank=True, null=True) class Meta: db_table = 'category_lesson_mapping' ** ---- user can be mapped sto multiple lesson --- ** class UserLessonMapping(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE, blank=True, null=True) class Meta: db_table = 'user_lesson_mapping' I want to get the logged in user, user mapped to lesson, lesson mapped to category and lesson mapped to lesson type data like this { user:{ 'id':1, 'first_name': 'alan' 'last_name': 'walker' }, 'lesson': [ { "id": 1, "lesson_type": { "id": 1, "lesson_type": "Video", … -
Making a request that triggers a function that searches a json object. The object will be updated every minute, could this lead to issues?
I am making a bus prediction web application for a college project. The application will use GTFS-R data, which is essentially a transit delay API that is updated regularly. In my application, I plan to use a cron job and python script to make regular get requests and write the response to a JSON file, essentially creating a feed of transit updates. I have set up a get request, where the user inputs trip data that will be searched against the feed to determine if there are transit delays associated with their specific trip. My question is - if the user sends a request at the same time as the JSON file is being updated, could this lead to issues? One solution I was thinking of is having an intermediary JSON file, which when fully loaded will replace the file used in the search function. I am not sure if this is a good solution or if it is even needed. I am also not sure of the semantics needed to search for solutions to similar problems so pointers in the right direction would be useful. -
How to make a shortcut of day display e.g Thursday 14/07/2022 => Thu 14/07/2022 in Django html template
I have booking start date as follow <p>{{ booking.start_time|date:"j/F/Y" }}</p> on Django html template which it displays the date as 14/July/2022 on the DOM, how I can make it display like this Thu 14/07/2022 -
How to return 400 status code from custom middleware in django?
I am trying to write a custom middleware which does some operation on the request to check its validity and if the request is invalid then return the bad request 400 status code without even going ahead. from django.http import HttpResponseBadRequest class VersionCheckMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): meta = request.META client = meta.get('HTTP_X_APP_CLIENT', None) if client == 'ios': app_version = ( int(meta['HTTP_X_IOS_APP_VERSION']) if meta.get('HTTP_X_IOS_APP_VERSION') else int(meta.get('HTTP_X_APP_VERSION', 0)) ) if app_version < 30: return HttpResponseBadRequest elif client == 'android': app_version = int(meta['HTTP_X_APP_VERSION']) if app_version < 188: return HttpResponseBadRequest elif client == 'web': app_version = int( meta['HTTP_X_APP_PLATFORM_VERSION'] if meta.get("HTTP_X_APP_PLATFORM_VERSION") else meta['HTTP_X_APP_VERSION'] ) if app_version < 188: return HttpResponseBadRequest response = self.get_response(request) return response -
how to add value from user input field in django imoirt-export library?
I have model named Product and Calculator that is connected to each item in Product model. What I am trying to achieve is to allow user to insert number of units and based on this number calculate total price in Excel file that will be exported when user clicks Calculate button. Questions: How can I add value inserted by a user in my input field to my cost_calculator.xlsx file and based on that value calculate total price? How can I add unit_hours property from CostCalculator model to my exported file? I successfully added it to admin page and it shows me correct result but when I add to to fields in my resource model then I get KeyError. What is the best approach to calculate total_price and display it in Excel in my case? The formula is following: number_of_units * rate * margin = total_price. Should I put it in form_valid in ProductDetailView or in ExportData view or maybe I shouldn't seperate Export button to seperate view but add it to form_valid. Is it possible to merge Send and Calculate buttons into one so if user clicks 1 button it will send user's value, calculate and export unit_hours and total_price … -
How do I change the default value of a field on a bound form that gets rendered in Django?
In a Django project we have forms that have already been submitted where for some reason the person before me set the default value of a field to be one blank space (' ') and this is affecting some other functionality where we need to copy data (not relevant to go into detail for this question I don't think) Anyway, here is a snippet from models.py where I changed the default value to '': #inside class Meta base64_encoded_activation_key = models.CharField (max_length = 1000, default = '', blank = True, verbose_name = 'Activation Key') Inside views.py def edit_activation(request, id=None): ...... activation = get_object_or_404(ActivationRecord, pk=id) ....... ....... ....... else: # GET request form = ActivationRecordForm(instance=activation) Now, this works fine if I create and submit a new form, but when I go back to an old form then the value is still ' ' (which I guess is expected as the form has been submitted) but I don't know how to fix this to the new default value. -
django the request argument must be an instance of django.http.HttpRequest
I'm importing a service function from django views function and getting this error 'The `request` argument must be an instance of `django.http.HttpRequest`, not `collections.OrderedDict`.' I have used the same implementation in other modules too and those are working fine. from custom_label.services.custom_label_svc import update_label @api_view(["POST"]) @authorize def update_label(request) -> JsonResponse: try: payload = ValidateUpdateLabel(data=request.data) if payload.is_valid(): # call service methods data = update_label(payload.validated_data) << here ... In custom_label > services > custom_label_svc.py file: from basic_files.database_connections import connect_to_postges cursor = connect_to_postges() def update_label(params: dict) -> dict: app_id = params.get('appid') label_name = params.get('label_name') updated_label_icon = params.get('updated_label_icon') sql = "UPDATE label SET icon = %s WHERE appId = %s AND name = %s" % (updated_label_icon, app_id, label_name) cursor.execute(sql) return cursor.rowcount What am I missing here? -
how to filter number of posts per page in Django python
This is views.py file paginator = Paginator( product_list, 5 ) show_on_page = request.GET.get('show_on_page', 5) product_item_list = paginator.get_page(show_on_page) and this is my templates file <div class="show-on-page"> <label class="product-sort-label" for="show-on-page">Tonen op pagina:</label> <select name="show-on-page" id="show-on-page"> <option value="5" selected>5</option> <option value="10">10</option> <option value="20">20</option> </select> I want to add random navigation like when you select 5 from dropdown 5 posts should be displayed per page if 10 it selects 10 posts. Can anyone help me with this? -
How to get queryset i need?
i have 2 models class Task(models.Model): user = models.ForeignKey( to='users.User', on_delete=models.CASCADE, related_name='tasks', ) category = models.ForeignKey( to='TaskCategory', on_delete=models.CASCADE, related_name='tasks', blank=True, null=True, ) difficult = models.DecimalField( max_digits=10, decimal_places=2, validators=(MinValueValidator(Decimal('0.01')),), ) class TaskCategory(models.Model): user = models.ForeignKey( to='users.User', on_delete=models.CASCADE, related_name='task_categories', ) name = models.CharField( max_length=255, ) i want to get this query(get top 3 category of most difficults sum and next one to sum of anothers): [ { "category__name": "Food", "category_sum": "12477.00" }, { "category__name": "Shopping", "category_sum": "3214.00" }, { "category__name": "Movie", "category_sum": "2590.00" }, { "category__name": "Anothers", "category_sum": "2000.00" } ] i make this queryset, but i dont know how make queryset i want: Task.objects.values('category__name').annotate( category_sum=Coalesce( Sum('difficult'), 0, output_field=DecimalField() ) ).filter( category__isnull=False ).order_by('-category_sum') [ { "category__name": "Food", "category_sum": "12477.00" }, { "category__name": "Shopping", "category_sum": "3214.00" }, { "category__name": "Movie", "category_sum": "2590.00" }, { "category__name": "Sport", "category_sum": "1000.00" } { "category__name": "Home", "category_sum": "1000.00" } ] -
Check overlapping reservation
I am developing a Reservation System in Django. I have a booking model, and in views the logic to make new booking and also to edit bookings. The logic in creating new bookings works perfectly but I am having problems when editing it. Basically, what I need to achieve is: If I edit my reservation but I don't change any data, I want the form to be saved If I edit my reservation and I change some data, I want the form to be saved ONLY if it doesn't overlap with any other reservation. I post some code: models.py class Booking(models.Model): aircraft = models.ForeignKey(Aircraft, on_delete=models.CASCADE) student = models.ForeignKey( Student, on_delete=models.CASCADE, blank=True, null=True) instructor = models.ForeignKey( Instructor, on_delete=models.CASCADE, blank=True, null=True) renter = models.ForeignKey( Renter, on_delete=models.CASCADE, blank=True, null=True) booking_date = models.DateField() start_time = models.TimeField() end_time = models.TimeField() uid = models.CharField(max_length=200, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) The uid field I created is a sort of logic to have a kind of Unique ID of the reservation in order to check if anything changed when I edit the booking. views.py if request.method == "POST": aircraft = request.POST.get('aircraft') student = request.POST.get('student') instructor = request.POST.get('instructor') renter = request.POST.get('renter') date = request.POST.get('date') start_time = … -
How to add/update objects using serializers in the Django Rest Framework?
I am using Django Rest Framework so that my other Django project can change records in this project's database, and am using serializers to do so. I am using the .save() method, which will add to the database only if none of the existing records share the same primary key as the ones being saved. I would like to "update" these existing records, either by updating them straight or deleting them then creating them again. This is my views.py: from rest_framework.response import Response from rest_framework.decorators import api_view from .serializers import parcelSerialiser @api_view(['POST']) def addItem(request): serializer = parcelSerialiser(data=request.data, many = True) print(request.data) print(serializer.is_valid()) print(serializer.errors) if serializer.is_valid(): serializer.save() return Response(serializer.data) and my serializers.py: from rest_framework import serializers from mainMenu.checkIn.models import Parcels class parcelSerialiser(serializers.ModelSerializer): class Meta: model = Parcels fields = '__all__' -
Code in Django is not working. The form in html does not open the output when clicking on submit
I am working on a simple project where I want to read a pdf using a form in html and then display the contents of the pdf on another page in form of a dictionary key value format. This is the code I have so far. The problem is that when I click on the submit button not even the else condition is executing and nothing happens. index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Pdf Reader</title> </head> <body> <form enctype='multipart/form-data' action='/analyze' method='POST'> <div class="input-group"> <input type="file" name="inp" class="form-control" id="inputGroupFile04" aria-describedby="inputGroupFileAddon04" aria-label="Upload"> <button class="btn btn-outline-secondary" type="button" id="inputGroupFileAddon04">Submit</button> </div> </form> </body> </html> views.py from django.http import HttpResponse from django.shortcuts import render import PyPDF2 from io import StringIO def index(request): return render(request,'index.html') def analyze(request): if request.method == "GET": #txt = request.FILES['inp'].read() # get the uploaded file pdfFileObj = open(request.FILES['inp'].read(), 'rb') # pdfFileObj = open((request.GET.get('inp.pdf')),'rb') pdfReader = PyPDF2.PdfFileReader(pdfFileObj) pageObj = pdfReader.getPage(0) content = pageObj.extractText() buf = StringIO(content) l = buf.readlines() while '\n' in l: l.remove('\n') i = 0 while i < len(l): for j in range(len(l[i])): if l[i][j:j + 2] == '\n': l[i] = l[i][:-1] j += 1 i += 1 d = {} i = 0 while i < (len(l)): if ":" …