Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Got AttributeError when attempting to get a value for field `transformerNamePlate` on serializer `MainDataSerializer`
i am trying to get a list of Main Objects with all of its nested Objects. but i got this error here is my codes views.py ` @api_view(['GET']) def getSelectedDevice(request): try: device_id=request.GET.get('dID', None) device=Main.objects.filter(device_id) print("device obg:\n",device) serializer=MainDataSerializer(device) return Response(serializer.data,many=True) except Main.DoesNotExist: return Response(status=404) ` models.py ` class TransformerNamePlate(models.Model): power=models.FloatField() uk=models.PositiveIntegerField() z0nom=models.FloatField() vectorGroup=models.CharField(max_length=10) vectorGroupLabel=models.CharField(max_length=10) uside1=models.FloatField() uside2=models.PositiveIntegerField() class Main(models.Model): dID=models.CharField(max_length=10) tID=models.CharField(max_length=12) user=models.CharField(max_length=40) deviceAliasName=models.CharField(max_length=60) dateTime=models.DateTimeField() #did and Tid (search) -> charfield transformerNamePlate=models.OneToOneField(TransformerNamePlate,on_delete=models.PROTECT) transformerInfo=models.OneToOneField(TransformerInfo,on_delete=models.PROTECT) detcTapChanger=models.OneToOneField(DETCTapChanger,on_delete=models.PROTECT,null=True) temperatureCorrectionHV=models.OneToOneField(TemperatureCorrectionHV,on_delete=models.PROTECT) temperatureCorrectionLV=models.OneToOneField(TemperatureCorrectionLV,on_delete=models.PROTECT) uk=models.OneToOneField(UK,on_delete=models.PROTECT) turnRatioTolerance=models.OneToOneField(TurnRatioTolerance,on_delete=models.PROTECT) tests=models.ForeignKey(Test,null=True,on_delete=models.PROTECT) ` serializer.py ` class TransformerNamePlateSerializer(serializers.ModelSerializer): class Meta: model=TransformerNamePlate fields="__all__" class MainDataSerializer(serializers.ModelSerializer): transformerNamePlate=TransformerNamePlateSerializer(many=False,read_only=False) transformerInfo=TransformerInfoSerializer(many=False, read_only=False) detcTapChanger=DETCTapChangerSerializer(many=False, read_only=False) temperatureCorrectionHV=TemperatureCorrectionHVSerializer(many=False, read_only=False) temperatureCorrectionLV=TemperatureCorrectionLVSerializer(many=False, read_only=False) uk=UKSerializer(many=False, read_only=False) turnRatioTolerance=TurnRatioToleranceSerializer(many=False, read_only=False) #tests=Test ->(many=False, read_only=True) class Meta: model=Main fields="__all__" def create(self, validated_data): transformerInfo_data=validated_data.pop('transformerInfo') temperatureCorrectionHV_data=validated_data.pop('temperatureCorrectionHV') temperatureCorrectionLV_data=validated_data.pop('temperatureCorrectionLV') transformerNamePlate=validated_data.pop('transformerNamePlate') uk_data=validated_data.pop('uk') turnRatioTolerance_data=validated_data.pop('turnRatioTolerance') detcTapChanger_data=validated_data.pop('detcTapChanger') #Remember to add other parts of test data test_data=validated_data.pop('tests') #print(validated_data) main_data=Main(**validated_data) # for data in temperatureCorrectionHV_data: # print (data) TemperatureCorrectionHV.objects.create(main=main_data,**temperatureCorrectionHV_data) TemperatureCorrectionLV.objects.create(main=main_data,**temperatureCorrectionLV_data) DETCTapChanger.objects.create(main=main_data,**detcTapChanger_data) UK.objects.create(main=main_data,**uk_data) TransformerInfo.objects.create(main=main_data,**transformerInfo_data) TransformerNamePlate.objects.create(main=main_data,**transformerNamePlate) TurnRatioTolerance.objects.create(main=main_data,**turnRatioTolerance_data) # Test.objects.create(main=main_data,**test_data) return main_data def save(self,data=None, **kwargs): if data!=None: main_data=self.create(validated_data=data) main_data.save() return else: return super().save(**kwargs) ` I figured out that it is because that Main.objects.all() doesnt return those nested data and just return the id field of them and because of that i get KeyError in serializer because it is looking for the actual object,not its id. -
403 error while fetching from my own server: CSRF Token missing
I have a social-media-like page that displays all posts by each user and users are able to edit their own posts with an Edit button. When the edit button is clicked, a textarea pre-filled with post content plus a Save and a Cancel button are displayed. When the Save button is clicked, I make a fetch request to update the content without reloading the page. However, I'm getting 403 because the csrf token is missing. What confuse me is that I don't have a form in my HTML template. Where should I put {% csrf_token %}? network.js: function clearEditView(postId) { // Show edit button and original content document.getElementById(`edit_button_${postId}`).style.display = "block"; document.getElementById(`content_${postId}`).style.display = "block"; // Hide edit form document.getElementById(`edit_form_${postId}`).style.display = "none"; } document.addEventListener('DOMContentLoaded', function() { // Add event listener that listens for any clicks on the page document.addEventListener('click', event => { // Save the element the user clicked on const element = event.target; // If the thing the user clicked is the edit button if (element.id.startsWith('edit_button_')) { // Save necessary variables const editButton = element; const postId = editButton.dataset.id; const saveButton = document.getElementById(`save_${postId}`); const cancelButton = document.getElementById(`cancel_${postId}`); const postText = document.getElementById(`content_${postId}`); // Hide edit button and original content editButton.style.display = "none"; … -
Django include template as variable to use in default
I'd like to include a default template as a variable to pass it into a default case, like below: <div class="row max-h-200 overflow-hidden"> {% include 'blog/userprofile_deleted.html' as deleted_profile %} {{ user.profile.bio | safe | default:deleted_profile }} </div> Is this possible in django 3.2.9 ? Currently I have to write out the default text as html in a single line: <div class="row max-h-200 overflow-hidden"> {{ user.profile.bio | safe | default:'<h4> Very long html string! </h4> <span>Comment as <b>you</b> with your own profile!</span><span>Create your Account at the <a href="#footer">bottom of the page</a>,or by visiting <a href="{% url "register" %}"><code>/register</code></a> !</span>' }} </div> -
Displaying join tables (many-to-many relationships) with django-extensions graph_models
For an exhaustive visual understanding of a data model, is there a way to display join tables (they actually exist in the DB) of many-to-many relationships with graph_models from the django-extension (3.2.1) module? This is the current help I got and I cannot find it all through: $ python manage.py graph_models --help usage: manage.py graph_models [-h] [--pygraphviz] [--pydot] [--dot] [--json] [--disable-fields] [--disable-abstract-fields] [--group-models] [--all-applications] [--output OUTPUTFILE] [--layout LAYOUT] [--theme THEME] [--verbose-names] [--language LANGUAGE] [--exclude-columns EXCLUDE_COLUMNS] [--exclude-models EXCLUDE_MODELS] [--include-models INCLUDE_MODELS] [--inheritance] [--no-inheritance] [--hide-relations-from-fields] [--relation-fields-only RELATION_FIELDS_ONLY] [--disable-sort-fields] [--hide-edge-labels] [--arrow-shape {box,crow,curve,icurve,diamond,dot,inv,none,normal,tee,vee}] [--color-code-deletions] [--rankdir {TB,BT,LR,RL}] [--version] [-v {0,1,2,3}] [--settings SETTINGS] [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--force-color] [--skip-checks] [app_label ...] Creates a GraphViz dot file for the specified app names. You can pass multiple app names and they will all be combined into a single model. Output is usually directed to a dot file. positional arguments: app_label optional arguments: -h, --help show this help message and exit --pygraphviz Output graph data as image using PyGraphViz. --pydot Output graph data as image using PyDot(Plus). --dot Output graph data as raw DOT (graph description language) text data. --json Output graph data as JSON --disable-fields, -d Do not show the class member fields --disable-abstract-fields Do not show the class … -
Why am I not able to create a super user in django? It's asking me to fill in every detail and on top of that, it asks me to enter a location
What can I do here? What kind of a location it is looking for from me? It has never happened ever earlier. -
How to set allow_null=True for all ModelSerializer fields in Django REST framework
I have a ModelSerializer . I want to set allow_null=True for all of the fields of the serializer . But I don't want to do it manually, I mean- I don't want to write allow_null=True for every field . Is there any shortcut? Is there anything like read_only_fields=() ? This is my Serializer class ProductPublicListSerializer(serializers.ModelSerializer): minimum_price = serializers.FloatField(source='min_product_price', allow_null=True) maximum_price = serializers.FloatField(source='max_product_price', allow_null=True) # rating = serializers.FloatField(source='productreview__rating', read_only=True) class Meta: model = Product fields = ( 'id', 'name', 'featured_image', 'minimum_price', 'maximum_price', 'total_review', 'average_rating') read_only_fields = ('name', 'featured_image', 'minimum_price', 'total_review') -
How to optimize a query on a model with foreign keys AND many to many field
(https://pastebin.com/qCMypxwz) These are my models. Right now 14 queries are made to get the desired result. Mostly, a query is made to get images associated with each product. Image is many to many field because each product has many images. productList = Variants.objects.select_related('prod_id__category') for productName in productList: products = dict() prod_id = productName.id products['id'] = prod_id products['category'] = productName.prod_id.category.category_name products['prod_name'] = productName.prod_id.prod_name prod_images = list(productName.image.values_list('image_url').distinct()) image_list = list() for image in prod_images: image_list.append(image[0]) products['image'] = image_list price = productName.price products['price'] = price createdAt = productName.createdAt products['createdAt'] = createdAt productListDict.append(products) -
Hardcode the value of a child class model field to be = to a field value in its parent
In a Django model, I would like to force a field of a child class to have a fixed value inherited from of a field of its parent. E.g.: from django.db import models class Entity(models.Model): class Type(models.TextChoices): Natural = ("Natural", "natural") Juridical = ("Juridical", "juridical") entity_type = models.CharField( max_length=9, choices=Type.choices, default=Type.Natural, ) class Person(Entity): person_type = Entity.Type.Natural # <--- forcing it to be 'Natural' from parent class ... I want to create such person_type field and forcing its value to be 'Natural' for each person object created using the Person class. This field can then be displayed in the admin, but the user must not have any kind of option to modify it. Same in the DB, ideally. I found nothing which relates to this idea in the doc: https://docs.djangoproject.com/en/4.1/ref/models/fields/ and I'm not able to apply this answer to set the value of the person_type field: https://stackoverflow.com/a/68113461/6630397 -
select not creating category entry in django database
I need to make it so that the select from the form is displayed in the database, None appears in its place in the database everything is added except categories and stocks I was told that I need to add value to option, but nothing happened to me what's wrong Here is my views.py : def create_product(request): categories = Category.objects.all() stock = Stock.objects.all() if request.method == 'POST': product = Product() product.title = request.POST.get('title') product.category = Category.objects.get(id=request.POST.get('category')) product.price = request.POST.get('price') product.user = request.POST.get('user') product.amount = request.POST.get('amount') product.stock = request.POST.get('stocks') product.user = request.user product.save() return redirect('index') return render(request, 'main/create.html', {'categories':categories,'stocks':stock}) Here is my models.py : class Product(models.Model): title = models.CharField(verbose_name="Название товара", max_length=250) categories = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, null=True) price = models.IntegerField(verbose_name="Цена") user = models.ForeignKey(get_user_model(),on_delete=models.CASCADE,related_name='products') amount = models.CharField(max_length=250,verbose_name='Количество') user = models.ForeignKey(User, on_delete=models.PROTECT) stock = models.ForeignKey(Stock, on_delete=models.PROTECT, blank=True, null=True) def get_absolute_url(self): return reverse("post_detail",kwargs={'pk':self.pk}) class Meta: verbose_name = 'Товар' verbose_name_plural = 'Товары' def __str__(self): return self.title My create template : <div class="" style="width: 600px; margin:0 auto; transform: translate(0, 10%);"> <h1 class="display-6">Создайте товар</h1> <form action="{% url 'create_product' %}" method="POST" class="form-control" style="background:rgba(0, 0, 0, 0.1); height: 500px;"> {% csrf_token %} <div class="mb-3"> <label for="exampleFormControlInput1" class="form-label">Название</label> <input type="text" class="form-control" id="exampleFormControlInput1" placeholder="Название товара" name="title"> </div> <div class="mb-3"> <label for="exampleFormControlInput1" … -
pipenv pytest ignores source changes or uses cached source?
I have a Django 4.0.6 project, Python 3.9.15, Ubuntu 22.10, pipenv 2022.10.25, pytest 7.1.2 The test output was cached somewhere and now any modification is ignored unless I delete the method. The steps I performed: Run the test: pipenv run pytest src/some/path/models.py The test fails, showing the correct error in traceback. Modify the method body. Run the test again. The test fails again, BUT the traceback shows old code, unmodified. Removing the method solves the problem, but any modification made to the method source makes it appear again in traceback, UNMODIFIED. Does pipenv/pytest/whatever cache the source somewhere? pipenv run pytest src/some/path/models.py --cache-clear did not help. As well as removing the .pytest_cache/. I tried removing the venv/some/path/__pycache__/models.cpython-39.pyc file (and all compiled *.pyc files in venv) But nothing seem to help. The same traceback appears every time I run tests. -
'int' object has no attribute 'save' in django
I have a value in a database on phpmyadmin and I want to change this value by a new calculated value. The function save() doesn't work and the error tells me that it's because it's an interger. I don't know how to solve this problem. def DeleteBulle (request, id_bulle): #suppression de la bulle par l'id id_bulle param = Bulles.objects.get(pk=id_bulle) #param.delete() #adaptation du champ "nombre de bulle" dans la table "site" site=param.id_site print('site', site) compte=Bulles.objects.filter(id_site=site).count() print('nombre bulle avec site identique', compte) nbrbulle=Bulles.objects.get(pk=id_bulle).id_site.nombre_bulles nbrbulle=compte nbrbulle.save() #réussite print("Bulle supprimée") return redirect('api_bulles_frontend') I don't know how to solve this problem. Thank you for your help. -
docer-compose.yml in Django project: environment variables are not created from the .env file
My docker-compose.yml: version: '3.8' services: web: build: ./app command: python3 manage.py runserver 0.0.0.0:8000 volumes: - ./app/:/usr/src/app/ ports: - 8000:8000 env_file: - .dev.env my Dockerfile in ./app: FROM kuralabs/python3-dev WORKDIR /usr/src/app ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip3 install -r requirements.txt COPY . . My file '.dev.env': ALLOWED_HOSTS='localhost 127.0.0.1' DEBUG=1 SECRET_KEY='django-insecure-...' I run the project with the commands: $docker-compose build $docker-compose up -d I get variables in settings.py: load_dotenv() print(f'Environment: {os.environ}') my variables from the '.dev.env' file are not in the list of environment variables. Please help me understand why '.dev.env' variables don't get into the environment? -
Django incomplete migration of table with multiple foreign keys
Django version: 4.1.2 After heaving the following table defined in the model: class Tasks(models.Model): name_text = models.CharField(max_length=200) duration_int = models.IntegerField(default=1) ... the next two tables have been defined: class Metiers(models.Model): name_text = models.CharField(max_length=50) ... class TasksProperties(models.Model): task = models.ForeignKey(Tasks, on_delete=models.CASCADE, related_name='task_relation') metier = models.ForeignKey(Metiers, on_delete=models.CASCADE, related_name='metier_relation') ... doing the migration, the metier is not created inside the SQL table, but the rest: class Migration(migrations.Migration): dependencies = [ ('simo', '0009_alter_specialdays_day_date'), ] operations = [ migrations.CreateModel( name='Metiers', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name_text', models.CharField(max_length=50)), ], ), migrations.CreateModel( name='TasksProperties', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('workload_mh', models.IntegerField(default=8)), ('task', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='simo.tasks')), ], ), ] Is there any reason, why metier is not taken into account? -
Need to show result on the same page - Django
I'm creating a password generator app. The app is working and stores the value on db. The problem is whenever I refresh, the form resubmits and takes the previous value and stores. Also, I want to show the email and password on the same page. Whenever I refresh, I want to show an empty form with empty fields. Views.py def home(request): if request.method=='POST': inputemail = request.POST.get('InputEmail') gen = ''.join(random.choices((string.ascii_uppercase+string.ascii_lowercase+string.digits+string.punctuation), k=10)) newpass = Item(email=inputemail,encrypt=gen) newpass.save() return render(request,'home.html',{"gen":gen}) return render(request,'home.html',{}) Home.html <form method = 'post' id='pass-form' > {% csrf_token %} <div class="mb-3"> <label for="exampleInputEmail1" class="form-label">Email address</label> <input type="email" class="form-control" name="InputEmail" > <div id="emailHelp" class="form-text">We'll never share your email with anyone else.</div> </div> <button type="submit" name = "submit" class="btn btn-primary">Generate Password</button><br><br> </form> <div class="mb-3"> <label for="exampleInputPassword1" class="form-label">Generated Password</label> <input type="text" id="InputPassword" name = "genpassword" value = {{gen}} > </div> Urls.py urlpatterns = [ path('',views.home,name='home'), ] -
When I filter I need to request.GET.value to be selected
I have to filter some data so I need to use a select field but when I submit the form the result disappears. I have to selected the value that is choice previous ` <label class="text-secondary">Discount Type</label> <select name="discount_type" class="form-control" > <option value="" class="text-center" >Select Type</option> {% for i in type %} <option {% if i.0 == request.GET.status %} selected {% endif %} value="{{ i.0 }}" >{{ i.1 }} </option> {% endfor %} </select>` -
Django Heroku deployment not serving static image files with Whitenoise
My css and js static files are working but my images are not loading. whitenoise==6.2.0 works in development but not with debug off.. MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] DEBUG = False STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" django_heroku.settings(locals()) URLS.PY if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) some template {% load static %} <center><img class="rounded" src="{% static 'images/sm_logos/about-1.png/'%}" style="height:300px; width:300px;"></center> C:\Users\Boss Chris\Desktop\Projects\CBlog\CBlog_project\blog\static\images\sm_logos\about-1.png appreciate your help.. been at this since yesterday and maxed out on pushups.. cant do anymore.. tried putting my static files in S3 too.. doesn't work but i'll try again tmrw if there's no solution -
Search in multiple models in Django
I have many different models in Django and I want to search for a keyword in all of them. For example, if you searched "blah", I want to show all of the products with "blah", all of the invoices with "blah", and finally all of the other models with "blah". I can develop a view and search in all of the models separately, but it's not a good idea. What is the best practice for this situation? -
DjangoCMS - Render database data to html
I'm testing out the DjangoCMS but I cannot understand how to create custom plugins that enable rendering data out of the database. I'd like to create a plugin that shows all the users for example but I can't understand how to pass the data into the HTML file. I followed the DJangoCMS documentation to create a custom plugin that shows the guest name, I've already tried to add users = User.objects.all() and then pass it to the render function but I receive an argument exception because the render function does not allow so many arguments, so what's the approach in DJangoCMS? models.py from cms.models.pluginmodel import CMSPlugin from django.db import models class Hello(CMSPlugin): guest_name = models.CharField(max_length=50, default='Guest') cms_plugins.py from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import User from .models import Hello @plugin_pool.register_plugin class HelloPlugin(CMSPluginBase): model = Hello name = _("Hello Plugin") render_template = "hello_plugin.html" cache = False def render(self, context, instance, placeholder): context = super().render(context, instance, placeholder) return context -
Additional borders and wrong display when using class="d-none d-sm-block d-md-block" bootstrap
I need to hide some of the columns of my table on mobile. I use d-none d-sm-block d-md-block to do that on small and medium screen sizes. This is my code: <table border="1px" class="table table-hover"> <thead class="thead-dark"> <tr> <th class="d-none d-sm-block d-md-block">Fund</th> <th>Why them</th> <th>How to donate</th> </tr> </thead> {% for fund in funds_list %} <tr> <td class="d-none d-sm-block d-md-block"> <a href={{ fund.url }} target="_blank" rel="noopener noreferrer">{{ fund.name }}</a></td> <td> {{ fund.description|safe }}</td> <td> <a href={{ fund.bank_details }} target="_blank" rel="noopener noreferrer" class="btn btn-primary stretched-link">Go to website</td> </tr> {% endfor %} </table> When I'm not additing these classes, my table looks fine: However, after I add this class="d-none d-sm-block d-md-block", some strange border appears around a column I want to hide: -
Django rest-framework , Serializer returning assertion Error
I'm extending my current model to have some common properties from other base classes. Before extending the model, everything was working fine. But after extending, I'm getting the assertion error while performing put and post Operation. I tried my best to resolve it by my own. But not getting where it is going wrong. Can anyone help me on this? Please find my model and serializers below. basemodel.py from django.db import models class BaseModel(models.Model): created_at=models.DateTimeField(auto_now=True) updated_at=models.DateTimeField(auto_now=True) class Meta: abstract = True softdelete.py from django.db import models class SoftDeleteModel(models.Model): is_deleted = models.BooleanField(default=False) def delete(self): self.is_deleted = True self.save() def restore(self): self.is_deleted = False self.save() class Meta: abstract = True movies.py from django.db import models from cinimateApp.models.comman.softdelete import SoftDeleteModel from cinimateApp.models.comman.basemodel import BaseModel # Create your models here. class Movies(SoftDeleteModel,BaseModel): name=models.CharField(max_length=250) description=models.CharField(max_length=250) active=models.BooleanField(default=False) def __str__(self): return self.name movieSerializer.py #Model Serializer from rest_framework import serializers from cinimateApp.models.movies import Movies class MovieSerializer(serializers.ModelSerializer): class Meta: model = Movies fields = '__all__' # fields=['id', 'name', 'description', 'active'] # exclude=['name'] # field Level Validation def validate_name(self,value): if(len(value)<3): raise serializers.ValidationError('name is too short') return value #Objectlevel validation def validate(self,data): if(data['name']==data['description']): raise serializers.ValidationError('name and description should be different') return #custome serializer field name_length=serializers.SerializerMethodField() def get_name_length(self,object): return len(object.name) viws.py from … -
Combining annotation and filtering in Django for two different classes
Hi I am trying to query and count marketplaces for every infringement only for the logged in user. Essentially trying to combine these two. mar_count = Marketplace.objects.annotate(infringement_count=Count('infringement')) inf=Infringement.objects.filter(groups__user=request.user) I found a below example but this is for the same class. I have two separate classes. I am a beginner. swallow.objects.filter( coconuts_carried__husk__color="green" ).annotate( num_coconuts=Count('coconuts_carried') ).order_by('num_coconuts') -
Logic for different leave types in django rest framework for Leave management system
Actually I'm working on Hrms application in django rest framework. I've created employee details module now next part is leave management system. Actually my company policy has different leave policies like cl,sl,ml,compo off, and permissions.I'm unable to understand how to make the logic for it and and don't know where to write the logic in serializers or views? Since a newbee i find somewhat difficult. Also when a employee apply a leave it should be requested to T.L. and then should be visible to hr and manager. T.l would give permission and it all should be in application and also in email process. How to make request and approval in rest api also how to send mail using django rest api? Can anyone guide me This is the code tried class LeaveRequest(models.Model): options = ( (Cl', 'cl), (Sl', 'sl), (Ml, 'ml), (Compoff,compoff) ) choices = ( ('Approved', 'Approved'), ('Rejected', 'Rejected'), ('Pending', 'Pending'), ) user = models.ForeignKey(User, related_name="leaverequest_user", on_delete=CASCADE) employee = models.ForeignKey(Employee, related_name="leaverequest_employee", on_delete=CASCADE) type = models.CharField(choices=options, max_length=50) status = models.CharField(choices=choices, max_length=50) text = models.CharField(max_length=500) date_time = models.DateTimeField(auto_now_add=False, -
what is charset=ibm037 in http
I am new to bug bounty & StackOverflow. I watched a presentation called ''WAF Bypass Techniques Using HTTP Standard and Web Servers ' Behavior - Soroush Dalili." I need help understanding something about IBM037 and IBM500 encoding. What is 'charset =ibm037' What is 'boundary=blah' Does anyone know any encoder for IBM037 & IBM500? I googled it, but I couldn't find anything. -
How to convert string with any date format to %m/%d/$Y in Python
I have a csv with with dates. The dates have inconsistent formatting and I want it all to change to mm/dd/yyyy upon importing. Is there a way to do it? I know about strptime but that requires a second argument for the format of the given date. -
Django Rest Framework: Upload file to another server via Django
I am building an API with DRF. The purpose of this API is to take user input and post the input to a different server via that servers API. There is also an option for users to upload file e.g. image. But the problem I am facing is that the second server is receiving the file as a blob of text like ����\x00\x10JFIF\x00\x01\x01\x01\x01,\x01,\x00\x00��\x0cXICC_PROFILE\x00\x01\x01\x00\x00\x0cHLino\x02\x10\x00\x00mntrRGB XYZ \x07�\x00\x02\x00\t\x00\x06\x001\x00\x... The second server is also build with Django. Here is the code for the first server that user has direct interaction with: requests.patch( f"https://second-server.com/api/user-upload/{self.kwargs.get('user_id')}/", data=request.data, ) The request.data contains the form data including the file that user is uploading. How can I save image to second server through the first server that user has direct interation with.