Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
JWT tokens in django: blacklist OutstandingTokens
I'm using following tutorial to use Jwt tokens in my Django application https://medium.com/django-rest/logout-django-rest-framework-eb1b53ac6d35 The LogoutAllView from the tutorial is the following: class LogoutAllView(APIView): permission_classes = (IsAuthenticated,) def post(self, request): tokens = OutstandingToken.objects.filter(user_id=request.user.id) for token in tokens: t, _ = BlacklistedToken.objects.get_or_create(token=token) return Response(status=status.HTTP_205_RESET_CONTENT) I wondered, why it's not possible to use token.blacklist(), like this: class LogoutAllView(APIView): permission_classes = (IsAuthenticated,) def post(self, request): tokens = OutstandingToken.objects.filter(user_id=request.user.id) for token in tokens: token.blacklist() return Response(status=status.HTTP_205_RESET_CONTENT) When I try this I get following error: AttributeError: 'OutstandingToken' object has no attribute 'blacklist' It seems like blacklist() is only possible with refreshtokens. Why is this not possible with outstanding tokens? As the function is: class BlacklistMixin: """ If the `rest_framework_simplejwt.token_blacklist` app was configured to be used, tokens created from `BlacklistMixin` subclasses will insert themselves into an outstanding token list and also check for their membership in a token blacklist. """ if 'rest_framework_simplejwt.token_blacklist' in settings.INSTALLED_APPS: def verify(self, *args, **kwargs): self.check_blacklist() super().verify(*args, **kwargs) def blacklist(self): """ Ensures this token is included in the outstanding token list and adds it to the blacklist. """ jti = self.payload[api_settings.JTI_CLAIM] exp = self.payload['exp'] # Ensure outstanding token exists with given jti token, _ = OutstandingToken.objects.get_or_create( jti=jti, defaults={ 'token': str(self), 'expires_at': datetime_from_epoch(exp), }, ) … -
Call external library command as celery task
I'm using following tutorial for using JWT tokens in my Django application: https://medium.com/django-rest/logout-django-rest-framework-eb1b53ac6d35 the LogoutAllView is as following: class LogoutAllView(APIView): permission_classes = (IsAuthenticated,) def post(self, request): tokens = OutstandingToken.objects.filter(user_id=request.user.id) for token in tokens: t, _ = BlacklistedToken.objects.get_or_create(token=token) return Response(status=status.HTTP_205_RESET_CONTENT) Now I wondered, is it not possible to do it like this: class LogoutAllView(APIView): permission_classes = (IsAuthenticated,) def post(self, request): tokens = OutstandingToken.objects.filter(user_id=request.user.id) for token in tokens: token.blacklist() return Response(status=status.HTTP_205_RESET_CONTENT) As the function blacklist is the following: class BlacklistMixin: """ If the `rest_framework_simplejwt.token_blacklist` app was configured to be used, tokens created from `BlacklistMixin` subclasses will insert themselves into an outstanding token list and also check for their membership in a token blacklist. """ if 'rest_framework_simplejwt.token_blacklist' in settings.INSTALLED_APPS: def verify(self, *args, **kwargs): self.check_blacklist() super().verify(*args, **kwargs) def blacklist(self): """ Ensures this token is included in the outstanding token list and adds it to the blacklist. """ jti = self.payload[api_settings.JTI_CLAIM] exp = self.payload['exp'] # Ensure outstanding token exists with given jti token, _ = OutstandingToken.objects.get_or_create( jti=jti, defaults={ 'token': str(self), 'expires_at': datetime_from_epoch(exp), }, ) return BlacklistedToken.objects.get_or_create(token=token) But when I try this I get following error: AttributeError: 'OutstandingToken' object has no attribute 'blacklist' I'm not that used to using jwt tokens. But it seems that the … -
Django, update_session_auth_hash not working
I made an api to change the user password, following this tutorial: https://medium.com/django-rest/django-rest-framework-change-password-and-update-profile-1db0c144c0a3 However, I don't want the user to be logged out and tried using the function update_session_auth_hash(request, user). I tried several things, but the user keeps logging out: Option 1 Function in the serializer: ## serializer def update(self, instance, validated_data): instance.set_password(validated_data['password']) instance.save() request = self.context['request'] user = request.user update_session_auth_hash(request, user) return instance Option 2 Function in the view # serializer def save(self, **kwargs): password = self.validated_data['password'] user = self.context['request'].user user.set_password(password) user.save() return user # views: class ChangePasswordView(generics.UpdateAPIView): queryset = User.objects.all() permission_classes = [IsAuthenticated,] serializer_class = ChangePasswordSerializer def update(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() update_session_auth_hash(request, request.user) return Response({'ok'}) However neither 1 nor 2 are working, what am I doing wrong? -
Best approach to build a dashboard in djnago [closed]
I'm working on a project : Web Aplication, that tracks & manage sales. i'm wondering what is the effecient way to build dashboards with several graphs! for example should i have the graphs configurations in the html template or can i write them in the views.py functions? also if i can have a class in the views.py with several functions (each function correspond to a graph) that renders in the same template? Appreciate any guidances in this regard! Thanks a lot! -
Image is not Editing after selecting
I am going through a Django Tutorial. I am building a feature of Image Crop in my Blog App. BUT my selected image is not Editing. Here is my Code :- views.py #PAGE FOR EDIT PROFILE PHOTO. def edit_photo(request): if request.method == 'POST': photo_form = EditProfilePhoto(request.POST, request.FILES, instance=request.user.profile) if photo_form.is_valid(): custom_form = photo_form.save(False) custom_form.save() return redirect('/') else: photo_form = EditProfilePhoto(instance=request.user.profile) args = {} args['photo_form'] = photo_form return render(request, 'mains/edit_photo.html' , args) models.py Class Profile(models.Model): name = models.CharField(max_length=22) user = models.ForeignKey(User,on_delete=models.CASCADE) image = models.ImageField(upload_to='images') forms.py class EditProfilePhoto(forms.ModelForm): class Meta: model = Profile fields = ['image',] widgets = {'image' : forms.FileInput} base.html {% load static %} <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- favicon --> <link rel="shortcut icon" type="image/jpg" href="{% static 'favicon.ico' %}"/> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384- TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"> <!-- jquery --> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <!-- cropper --> <script src="https://cdnjs.cloudflare.com/ajax/libs/cropper/4.1.0/cropper.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropper/4.1.0/cropper.min.css"> <!-- custom css & js--> <link rel="stylesheet" href={% static 'style.css' %}> <script src={% static 'main.js' %} defer></script> <title>image cropper</title> </head> <body> <div class="container mt-3"> </div> </body> </html> <p> main.js ( File in static folder in Project Directory ) const alertBox = document.getElementById('alert-box') const imageBox = … -
Create htaccess file for domain redirection (Django app deployed in Heroku)
Situation: I've bought a specific domain, let's say 'example.ch' for my Django application which is deployed in Heroku. I also created an automated SSL certificate on Heroku (ACM). This certificate is valid for the WWW-subdomain, i.e. ACM Status says 'OK'. It fails for the non-WWW root domain, so I deleted the root domain entry on Heroku. Issue: When I type 'https://www.example.ch' in the browser, I find my secure webpage and everything is fine. When I type 'www.example.ch' in the browser, I find my webpage but it is not secure When I type 'example.ch' in the browser, the webpage cannot be found. Goal: I would like to type 'www.example.ch' as well as 'example.ch' in the browser to be always redirected to 'https://www.example.ch'. Approach (so far): My Host (swizzonic.ch) does not allow for 'Alias' records. 'A' records are possible but not supported by Heroku (https://help.heroku.com/NH44MODG/my-root-domain-isn-t-working-what-s-wrong). Swizzonic support told me to use a htaccess-file for redirection. As I understand so far, I have to extend my middleware accordingly (?). Note that I use the common options for SSL redirection (SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https'), SECURE_SSL_REDIRECT = True, SESSION_COOKIE_SECURE = True, CSRF_COOKIE_SECURE = True). How can I create a htaccess-file, where do I have to … -
Reverse with Argument Not Found in Django
I've been using Django for a while and at this moment I'm trying to create an edit page. My problem is that now that as soon my link is in my CSS.html file, I can't even access my CSS.html file (with my browser). It just shows the error message. The hyperlink in my CSS.html file <a href="{% url 'edit' name %}">{{ name }}</a> My path in my urls.py file path("edit/str:name>/", views.edit, name="edit") My function to render the edit page in views.py: def edit(request, name): entry = util.get_entry(name) return render(request, "encyclopedia/edit.html", { "name": name, "entry": entry}) My error: Reverse for 'edit' with arguments '('CSS',)' not found. 1 pattern(s) tried: ['edit/str:name>/$'] Thank you in advance! -
no signature found for builtin type <class 'filter'>
I am implementing django_filters on my project. Model: class MsTune(models.Model): class Meta: app_label = "myapp" name = models.CharField(max_length=255) class MsTuneFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_expr='iexact') class Meta: model = MsTune fields = [myfields...] View: def MsTuneList(request): mstunes = MsTune.objects.all() f = MsTuneFilter(request.GET, queryset=MsTune.objects.all()) return render(request, 'manuscript/mstune_list.html', {'mstunes': mstunes, 'filter': filter}) When I point my browser to my template I get this error: ValueError at /testdb/mstunes/ no signature found for builtin type <class 'filter'> Request Method: GET Request URL: .../mstunes/ Django Version: 3.1.5 Exception Type: ValueError Exception Value: no signature found for builtin type <class 'filter'> Exception Location: /usr/lib/python3.7/inspect.py, line 2364, in _signature_from_callable I already successfully used django_filters on another project, so I'm not sure what the issue with this one is. I'm using the latest Django version 3.1 on Python 3.7. -
Permission that current user can request info only about itself Django?
How to implement permission that current user can read info only about it self? For example, current logged user id is 69909317-bd29-47b8-8878-5884182e4948 and i want request user/69909317-bd29-47b8-8878-5884182e4948 to read info about current user. I tried something like class IsOwner(permissions.BasePermission): def has_object_permission(self, request, view, obj): return obj.owner == request.user But fell in error that User object has no attribute owner -
Clear AWS SES email queue
My Django server ran into an error during the night and sent me thousands upon thousands of error logs by emails (several per second). I patched the error and rebooted the server, but I am still receiving emails, dated from several hours ago. How can I stop the old emails from being sent? Is there a way to tell amazon SES to clear its queue of email? -
how can I make the choice of cities inside of specific region in Django admin?
I am a beginner in Django Frame work.enter image description here when I click to the regions it should display all the available regions and after choosing specific region, inside that region it is available to choose a specific city -
Add Serializer data in a coulmn of same id rest api
I have 50 questions with options. every time user select one option i recieve api in post method in views.py format below { "question_id": 1, "user_id": 1, "response": "Agree_5", "category": "A" } As of now i was able to store this data in my postgresql table="paresponses" but one row at a time i.e user_id|question_id|response |category 1 | 1 |Agree_5 | E 1 | 2 |Diagree_1| A but now i need to store like this in a new table="user_responses" user_id|question_1|question_2|question3|...... 1 |Agree_5 |disagree_1|..... 2 |Agree_5 |diagree_1 |..... I dont need "category" parameter so that is fine . views.py @api_view(['GET', 'POST']) def AnswersList(request): if request.method == 'GET': # user requesting data snippets = PAResponse.objects.all() serializer = PAAnswersSerializer(snippets, many=True) return Response(serializer.data) elif request.method == 'POST': # user posting data serializer = PAAnswersSerializer(data=request.data) print("serializer in post",type(serializer),serializer) if serializer.is_valid(): serializer.save() # save to db result=Calculate(serializer) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py class PAAnswersSerializer(serializers.ModelSerializer): class Meta: model=PAResponse fields='__all__' Models.py class PAResponse(models.Model): user_id=models.IntegerField() question_id=models.IntegerField(primary_key=True) response=models.CharField(max_length=255) category=models.CharField(max_length=100) class Meta: db_table="paresponses" def __str__(self): return self.response How can i acheive this please give me a lead . i receive api one by one after every question selected with above details. Any kind of suggestion and lead is aprreciated . … -
handling different forms post request on single page -Django
I am a newbie, and I am working on a website. On this website I have created admin panel to manage different products and attributes . I have a page named size.html and and I am supposed to change it name and make it productAtributes.html and on this single page I want to do all add, update, delete operations for different Product attributes. My code is as: models.py class Product(models.Model): prod_ID = models.AutoField("Product ID", primary_key=True) prod_Name = models.CharField("Product Name", max_length=30, null=False) prod_Desc = models.CharField("Product Description", max_length=2000, null=False) prod_Price = models.IntegerField("Product Price/Piece", default=0.00) prod_img = models.ImageField("Product Image", null=True) def __str__(self): return "{}-->{}".format(self.prod_ID, self.prod_Name) class Size(models.Model): size_id = models.AutoField("Size ID", primary_key=True, auto_created=True) prod_size = models.CharField("Product Size", max_length=20, null=False) def __str__(self): return "{size_id}-->{prod_size}".format(size_id=self.size_id, prod_size=self.prod_size) class Color(models.Model): color_id = models.AutoField("Color ID", primary_key=True, auto_created=True) prod_color = models.CharField("Product Color", max_length=50, null=False) def __str__(self): return "{color_id}-->{prod_color}".format(color_id=self.color_id, prod_color=self.prod_color) class PaperChoice(models.Model): paper_id = models.AutoField("Paper Choice ID", primary_key=True, auto_created=True) paper_choices_name = models.CharField("Paper Choices", max_length=50, null=False) def __str__(self): return "{}-->{}".format(self.paper_id, self.paper_choices_name) views.py from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage from django.shortcuts import render, redirect from user.models import * def size(request): if request.method == 'POST': size_store = request.POST['prod_size'] size_update = Size(prod_size=size_store) size_update.save() return redirect('/admin1/productSize') else: size_show = Size.objects.all() # start paginator logic paginator … -
How to create a objects with related tables
I'm building a django web app and I'm having troubles in inserting news objects(musics) without using forms. I will give an example of what I've so far: here is my models.py: from django.db import models from django.contrib.auth.models import User class Genre(models.Model): genre=models.CharField(max_length=250) def __str__(self): return str(selt.genre) class Music(models.Model): author=models.OneToOneField(User, on_delete=models.CASCADE) genre=models.ForeignKey(Genre, on_delete=models.CASCADE) title=models.CharField(max_length=100) audio_file=models.FileField(upload_to='songs/') cover=models.ImageField(upload_to='covers/') and here is my views.py: from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponse from .models import * def add_song(request): if request.method=='post' or request.FILES: genre=request.post['genre'] #getting the genre data from html template title=request.post['title'] #getting the title from html template audio_file=request.files['audio_file'] cover=request.files['cover'] instance=request.user genre_selected=Genre.objects.get(genre=genre) #to get the genres already inserted in the db music=Music.objects.create(author=instance, title=title, genre=genre_selected, audio_file=audio_file, cover=cover) return redirect('/') else: return render(request, 'music.html') And when I try to add new always I get this error: Cannot assign "<Genre: Pop>": "Music.genre" must be a "Genre" instance. Can you guys help me out? -
How to develop Analytical Dashboard using django
I'm working on the project of Analytical Dashboard Web application. In this application user need to import data from datasource like server,local,drive. I don't want to import data from model. Is it possible in django-analytical. Request your suggestion. -
ValueError: cannot assign integer to foreign key during put request
So I have a model like this. class Member(BaseModel): objects = models.Manager() user = models.ForeignKey('api_backend.User', db_index=True, on_delete=models.CASCADE) cluster = models.ForeignKey('api_backend.Cluster', on_delete=models.CASCADE) And a generic api view for the same. lass MemberPutRetrieveUpdateDeleteView(PutAsCreateMixin, MultipleFieldLookupMixin, generics.RetrieveUpdateDestroyAPIView): queryset = api_models.Member.objects.all() permission_classes = [permissions.IsAuthenticated, IsMemberOrKickMembers] lookup_fields = ['user', 'cluster'] def get_serializer_class(self): if self.request.method in ['PUT']: return api_serializers.PartialMemberSerializer return api_serializers.MemberSerializer def destroy(self, request, *args, **kwargs): member = self.get_object() if member.cluster.owner == member.user: raise exceptions.ValidationError("cannot delete membership with this cluster as you own it.") return super(MemberPutRetrieveUpdateDeleteView, self).destroy(request, *args, **kwargs) I am currently using these mixins. class PutAsCreateMixin(object): """ The following mixin class may be used in order to support PUT-as-create behavior for incoming requests. """ def update(self, request, **kwargs): partial = kwargs.pop('partial', False) instance = self.get_object_or_none() serializer = self.get_serializer(instance, data=request.data, partial=partial) serializer.is_valid(raise_exception=True) if instance is None: if not self.lookup_fields: lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field lookup_value = self.kwargs[lookup_url_kwarg] extra_kwargs = {self.lookup_field: lookup_value} else: # add kwargs for additional fields extra_kwargs = {field: self.kwargs[field] for field in self.lookup_fields if self.kwargs[field]} serializer.save(**extra_kwargs) return Response(serializer.data, status=201) serializer.save() return Response(serializer.data) def partial_update(self, request, *args, **kwargs): kwargs['partial'] = True return self.update(request, *args, **kwargs) def get_object_or_none(self): try: return self.get_object() except Http404: if self.request.method == 'PUT': # For PUT-as-create operation, we need to ensure that … -
Django Makemigrations not working with ForeignKey field to an app that has AppConfig
We have an app called sessions, and since Django has similar django.contrib.sessions app, we need to create an AppConfig to fix the "duplicate app" error, that is, we set the app label as common.sessions. So, we have this folder/files structure: common sessions __init__.py apps.py models.py __init__.py default_app_config = 'common.sessions.apps.CommonSessionsConfig' apps.py class CommonSessionsConfig(AppConfig): name = 'common.sessions' label = 'common.sessions' models.py class SessionEventType(models.Model): name = models.CharField() class SessionEventTypeMapping(models.Model): session_event_type = models.ForeignKey(SessionEventType) settings.py INSTALLED_APPS = ( 'common.sessions', ... ) Running manage.py migrations will throw this error: File "/virtualenv/backoffice/lib/python2.7/site-packages/django/core/management/commands/makemigrations.py", line 125, in handle migration_name=self.migration_name, File "/virtualenv/backoffice/lib/python2.7/site-packages/django/db/migrations/autodetector.py", line 43, in changes changes = self._detect_changes(convert_apps, graph) File "/virtualenv/backoffice/lib/python2.7/site-packages/django/db/migrations/autodetector.py", line 111, in _detect_changes self.new_apps = self.to_state.apps File "/virtualenv/backoffice/lib/python2.7/site-packages/django/utils/functional.py", line 59, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/virtualenv/backoffice/lib/python2.7/site-packages/django/db/migrations/state.py", line 166, in apps return StateApps(self.real_apps, self.models) File "/virtualenv/backoffice/lib/python2.7/site-packages/django/db/migrations/state.py", line 248, in __init__ raise ValueError(msg.format(field=operations[0][1], model=lookup_model)) ValueError: Lookup failed for model referenced by field common.sessions.SessionEventTypeMapping.session_event_type: common.sessions.common.sessions.SessionEventType Apparently, it fails on this part and could not locate the SessionEventType class/model even though they're just in the same models.py file: session_event_type = models.ForeignKey(SessionEventType) Tried also this variant: session_event_type = models.ForeignKey('common.sessions.SessionEventType') but it didn't help, as well as this related issue. By the way, we're still using Py2/Django 1.8 since it's … -
__init__() got an unexpected keyword argument 'status' error in django
I'm using django-rest-framework. I can't understand why the error occurred. I am trying to save the queryset json. But it doesn't work. My queryset json is as below. I'm sorry for the misalignment. { "data": [ { "code": "123", "name": "hi", "cnt": "3", "construction":"123", "listedDate":"20171112", "lastPrice":"123", "state":"123", "token":"ff35885ab6c63290ccdf60b80a9b37769e287ec5" }, { "code": "123", "name": "hi2", "cnt": "3", "construction":"123", "listedDate":"20171112", "lastPrice":"123", "state":"123", "token":"ff35885ab6c63290ccdf60b80a9b37769e287ec5" }, { "code": "123", "name": "hi3", "cnt": "3", "construction":"123", "listedDate":"20171112", "lastPrice":"123", "state":"123", "token":"ff35885ab6c63290ccdf60b80a9b37769e287ec5" } ] } My Model class Stock(models.Model): code = models.CharField(max_length=20) name = models.CharField(max_length=30) cnt = models.BigIntegerField() construction = models.CharField(max_length=20) listedDate = models.DateTimeField() lastPrice = models.CharField(max_length=10) state = models.CharField(max_length=20) token = models.CharField(max_length=50,validators=[validate_token]) class Meta: db_table = 'stock' def __str__(self): return self.name This is my Viewset from requests import Response from rest_framework import viewsets, status from . import models, serializers class StockViewset(viewsets.ModelViewSet): queryset = models.Stock.objects.all() serializer_class = serializers.StockSerializer def create(self, request, *args, **kwargs): stock_data = request.data.get("data") serializer = self.get_serializer(data=stock_data,many=True) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) print(serializer.data) return Response(serializer.data,status=status.HTTP_201_CREATED,headers=headers) def perform_create(self, serializer): serializer.save() and my serializers from rest_framework import serializers from .models import Stock class StockSerializer(serializers.ModelSerializer): listedDate = serializers.DateTimeField(format="%Y-%m-%d",input_formats=['%Y%m%d']) class Meta: model = Stock fields = '__all__' Even if there is no solution for the above, I would like you … -
name 'request/self' is not defined
Getting requests is not defined. please find the below code(I'm not using it directly in CBV). views.py class ShiftChangeUpdateView(request,PermissionRequiredMixin,UpdateView): permission_required = ('apple.change_shiftchange',) model=ShiftChange logger.info('Data has been Deleted by %s !', request.user.username) fields='__all__' I have checked by using self also but no luck. urls.py url(r'^updategenesys/(?P<pk>\d+)/$', views.ShiftChangeUpdateView.as_view()), How to fix this issue? -
Get Error information while in Production, Django
I'm getting this weird error which only shows when the app i am working on is in production. While its easy to identify and fix the error in development, I'm getting a 500 error page when I switch to production. I'm trying to get a way to discover the error details in productions but this is proving difficult. Some assistance will help. Thanks. -
How to exclude fields from nested representation Django?
I have following UserSerializer class class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'persons'] depth = 1 The depth option allows me generate nested representations { "id": 2, "persons": [ { "id": 1, "name": "Alex", "city": "Paris", "bio": "This is my bio", "phone_number": "9130095484", "age": 24, "height": 56, "weight": 54} ] I don't need all fields in nested representation. How to exclude some fields but keep the depth option? -
Django Not Displaying Image When I Go to image's Link
I was trying to show an image on my webpage but when I go to the image's link it just shows the whole webpage! -
I want to create a page that can upload Excel (xlsx) file and convert to MySQL in Django
i've create python code that can convert excel to mysql, but i have to put it in Web app using Django here's my code for converting excel to mysql import xlrd import pymysql book = xlrd.open_workbook(r'/home/ubuntu/casa_debitur/simpanan.xlsx') sheet = book.sheet_by_name('Sheet1') mydb = pymysql.connect("localhost","vyzyz","vyzyz!","casa_debitur") cursor = mydb.cursor() truncate = "TRUNCATE simpanan" try: cursor.execute(truncate) except Exception as e: print("Occured : ",e) print(truncate) mydb.commit() for row in range(1, sheet.nrows): cif = sheet.cell(row,0).value nama_debitur = sheet.cell(row,1).value produk_simpanan = sheet.cell(row,2).value norek = str(int((sheet.cell(row,3).value))) if len(norek) == 12: norek = '000' + norek if len(norek) == 13: norek = '00' + norek if len(norek) == 14: norek = '0' + norek instanding = str(int((sheet.cell(row,4).value))) query = 'INSERT INTO simpanan(cif, nama_debitur, produk_simpanan, norek, instanding) VALUES("'+ cif +'", "'+ nama_debitur +'", "'+ produk_simpanan +'", "'+ norek +'", "'+ instanding +'")' try: #print(query) cursor.execute(query) except Exception as e: print("Occured : ",e) print(query) mydb.commit() and here is my code for file upload {% extends "base.html" %} {% block content %} <h1>{{ title }}</h1> <form action="/upload/" method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" title="Upload excel file" name="excel_file" style="border: 1px solid black; padding: 5px;" required="required"> <p> <input type="submit" value="Upload" style="border: 1px solid green; padding:5px; border-radius: 2px; cursor: pointer;"> </form> <p></p> <hr> {% for … -
How to add multiple childs to a Parent using only ForeignKey?
I have a parent model and child model. Child model have a foreignkey relationship with the parent model. But If i want to add multiple child to single parent without changing the model then how it is possible.? Child Model class Market(models.Model): market = models.CharField(max_length=285, blank=True, null=True) modified_by = models.ForeignKey( User, null=True, blank=True, on_delete=models.SET_NULL) parent_market = models.ForeignKey( 'ParentIndustry', null=True, blank=True, related_name='parent_market', on_delete=models.SET_NULL, default=None) Child Industries But I want to add multiple child industries to Parent then how can i do that in admin.? Parent model class ParentIndustry(models.Model): name = models.CharField(max_length=285, blank=True, null=True) modified_by = models.ForeignKey( User, null=True, blank=True, on_delete=models.SET_NULL) Parent Industries admin.py class ParentIndustriesAdmin(admin.ModelAdmin): list_display = ('id', 'name', 'company_count','email_count') search_fields = ['id', 'name', ] ordering = ['-date_modified'] def save_model(self, request, obj, form, change): obj.modified_by = request.user obj.save() admin.site.register(ParentIndustry, ParentIndustriesAdmin) -
Why does Django have a slug field?
This might seems a real simple question, but why does Django have a slug field? I have seen may articles about slug fields but I have not seen anybody explain why we should create a slug field. The closest I have seen is a couple of articales saying the URL should be in human readable field and unique is there any other reasons ?