Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Difference between Apache process and WSGI process?
I have a Django application running with Apache prefork (my code is not thread safe). I am relatively new to Apache, so apologies in advance if this is too basic. As far as I understand the main differences are: Apache process: control access and serve static files WSGI process: execute python code Does this mean that if I define MaxRequestWorkers in Apache as 250, and wsgi processes = 10.. each one of the 250 Apache processes can fork into another 10 processes? Also, according to mod_wsgi documentation sites using Apache prefork should set the wsgi threads = 1 My site actually works when setting wsgi threads = 5 with Apache prefork. But doesn't work with Apache worker since the code is not thread safe... How can this be? -
Heroku unable to verify card
I wanted to connect my custom domain to django website hosted on heroku because it was free, I wanted to connect my domain to heroku but it asks for verification, I tried to add my card and I also added all things correctly but it gives unable to verify card error, I tried with different card also but it gives same error, There is no fault of card, Is there any other solution to it, Is there any hosting that allows to host django website for free and also allows to add custom domain like heroku instead of digital ocean and amazon aws. -
How to keep the content inside the card?
I making my first web project, and as a first project im doing To-Do app. Im also learning to do it responsive website, but i have stuck in a problem. When I add a content larger then the table it goes out of the card. What i want is despite that the content is larger i want to stay inside the table. body { background-color: #6ea1ff; /*#3f7ef3;*/ font-family:; } /* The navbar */ .navbar { padding: 25px; } .navbar-brand { font-size:; } .d-flex { margin-right: 680px; width: 30%; } #add-btn { width: 80px; } /* THe table */ .container{ position: relative; bottom: -75px; width: 65%; font-family:; } .card { background-color: #0d2e72; } .card-header { border: none; } #header { font-size: 25px; text-align: center; color: white; } #tr-table { width: 100px; } #text-left { width: 10%; } #text-right { width: 15%; padding-left: 40px; } #text-center { text-align: center; } #btn-delete { width: 80px; margin-left: 35px; } /* THE footer */ footer { position: fixed; left: 0; bottom: 0; width: 100%; padding: 10px; background-color: #26272b; color: white; text-align: center; } @media screen and (max-width: 667px) { /* The navbar */ .navbar { padding: 15px; height: auto; } .d-flex { position: relative; left: … -
django filter get parent to child
i am using django(3.1.5). and i am trying to get parent model to child model by filter query i have model like - class Product(models.Model): product_name = models.CharField(max_length=255, unique=True) is_feature = models.BooleanField(default=False) is_approved = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) class ProductGalleryImage(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) product_gallery_image = models.FileField(upload_to='path') is_feature = models.BooleanField(default=False) i am getting data from SELECT * FROM products_product AS pp INNER JOIN products_productgalleryimage AS ppgi ON ppgi.product_id = pp.id WHERE ppgi.is_feature=1 AND pp.is_feature=1 AND is_approved=1 ORDER BY pp.created_at LIMIT 4 mysql query. so how can i get data like this query in django filter query -
How to enable cors in django (DJANDO + REACT)
Access to XMLHttpRequest at 'http://127.0.0.1:8000/lessons/student' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request. xhr.js:177 GET http://127.0.0.1:8000/lessons/student net::ERR_FAILED On my localhost it works good, I get data from API but when my friend tries to go to the "Lessons" page and fetch data it shows that error; In the backend, I downloaded django-cors or whatever it is called and did everything as said CORS_ORIGIN_ALLOW_ALL = True INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'News', 'Users', 'Lessons', 'Tests', 'GradeBook', 'Schedule', 'DeadLines' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', ] I fetch data using redux-thunk with axios const lesson = await axios.get(`${url}/lessons/student`, { headers: { "Authorization": "JWT " + getState().auth.token.access, } }) I have checked a lot of answers to similar problem but they only say that I should install django-cors..enable cors...lalal... I do everything reload the server even localhost but it still doesn't work. It also isn't a problem with the browser, my friend tried chrome since he used opera. One more time, on my computer it works nice. I get the data once I … -
refresh a same page without reloading?
i have already asked this question here but none of the answers were working.i have a messaging app where users can send messages each other.i want to refresh the page so that the user can see new messages.but there is one problem if the user is writing a message and i try to reload the page every x-minutes the message that the user was writing will disapear.so how can i avoid this? window.location.reload(true);// this what i have tried history.go(0); window.location.href=window.location.href; -
Passing a form in the context of django view gives 502 bad gateway on aws server
I am getting a 502 bad gateway error as soon as i am passing a form object in my django view. If i don't pass the form it doesn't give any errors on the server. This is my model class scholarship(models.Model): GRADUATION_CHOICES = ( ('UG', 'Under Graduate'), ('G', 'Graduate'), ('PG', 'Post Graduate'), ) name = models.TextField() slug = models.SlugField(max_length=250, unique=True) supportingImage = models.FileField(upload_to ='student/scholarship/supportingImage/',null=True, blank=True, validators=[FileExtensionValidator(['jpg','png','jpeg'])]) author = models.ForeignKey(User, on_delete=models.SET_NULL, related_name='authorSCH', null=True, blank=True) productCategory = models.TextField(null=True, blank=True) currentClass = models.ManyToManyField(studentClass, related_name='currentClassSStudent', blank=True) graduation = models.CharField(max_length=10, choices=GRADUATION_CHOICES, default='G') scholarshipAmount = models.TextField(null=True, blank=True) fee = models.TextField(null=True, blank=True) gender = models.CharField(max_length=50, choices=GENDER_CHOICES, null=True, blank=True) country = models.ForeignKey(countryAndCurrencyList, related_name="countrySCH", blank=True,on_delete=models.SET_NULL,null=True) state = models.ForeignKey(state, related_name="stateSCH", blank=True,on_delete=models.SET_NULL,null=True) city = models.ForeignKey(city, related_name="citySCH", blank=True,on_delete=models.SET_NULL,null=True) eligibility = models.TextField(null=True,blank=True) scholarshipCourse = models.ManyToManyField("course", related_name='scholarshipCourseS',blank=True) scholarshipCareer = models.ManyToManyField(career,related_name='scholarshipCareerS',blank=True) scholarshipCollege = models.ManyToManyField(collegeProfile,related_name='scholarshipCollegeS',blank=True) scholarshipUniversity = models.ManyToManyField(universityProfile,related_name='scholarshipUniversityS',blank=True) scholarshipEntrance = models.ManyToManyField(entranceExams,related_name='scholarshipEntrance',blank=True) scholarshipGlobalisation = models.CharField(max_length=15,choices = AREA_CHOICE, default='india') dateToApply = models.DateField(default=datetime.date.today) whereToApply = models.TextField(null=True, blank=True) lastDateToApply = models.DateField(default=datetime.date.today) description = models.TextField(null=True, blank=True) publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') def __str__(self): return self.name class Meta: verbose_name_plural = 'Student-Scholarship' def get_absolute_url(self): return reverse('studentApp:scholarshipDetail', args=[self.slug]) def save(self): if self.name: if not self.slug: self.slug = re.sub(r'[\W_]+', '-', self.name.lower()) super(scholarship, self).save() else: super(scholarship, self).save() … -
Logger emit() is called multiple times for a single request
I am trying to modify the emit() of logging. handler such that I can ship the logs to my Kafka broker. However, I am noticing something strange, every time I make a request, the emit() is called multiple times. E.g When I go to the browser and press enter once, the emit() is called once, and then when I retry the request, the emit() is called twice. The trend is that the calls to emit() increases linearly with every request. Tried debugging through the logs but couldn't find any errors. Any suggestion or advice would be really appreciated. handler.py from logging import StreamHandler from ..mykafka import MyKafka class ErrorLogHandler(StreamHandler): def __init__(self, broker, topic): StreamHandler.__init__(self) self.broker = broker self.topic = topic # Kafka Broker Configuration self.kafka_broker = MyKafka(broker,True) def emit(self, record): data = { 'sys_name': 'Test', 'logger_name': record.name, 'level': record.levelname, 'message': record.msg, 'function_name': record.funcName, 'file_name': record.filename, } self.kafka_broker.send(data, self.topic) mykafka.py from kafka import KafkaProducer import json class MyKafka(object): def __init__(self, kafka_brokers, is_json=False): self.is_json = is_json if not is_json: self.producer = KafkaProducer( bootstrap_servers=kafka_brokers ) else: self.producer = KafkaProducer( value_serializer=lambda v: json.dumps(v).encode('utf-8'), bootstrap_servers=kafka_brokers, ) def send(self, data, topic): if self.is_json: result = self.producer.send(topic, key=b'log', value=data) else: result = self.producer.send(topic, bytes(data, 'utf-8')) print("kafka send … -
Django Nested model or serializers
I'm new in Django and I have a simple use case to parse a nested json file. Most of tutorials I've seen are using nested relation in their serializer code like this which is a bit different than my case. What is the best way to create implement this structure? class AlbumSerializer(serializers.ModelSerializer): tracks = serializers.StringRelatedField(many=True) class Meta: model = Album fields = ['album_name', 'artist', 'tracks'] And here is my input json file. { "BMW":[ { "model":"3", "price":"500" }, { "model":"5", "price":"600" } ], "TOYOTA":[ { "model":"X", "price":"300" }, { "model":"H", "price":"400" }, { "model":"S", "price":"500" } ] } -
I am trying to create an writable nested serializer in django, but can't use post method properly
So I am trying to create a serializer that shows me the whole object of the other model that is linked by a ForeignKey with the model I am working with my GET woks good, but I can only post by creating a new Country not with an actual existing one, so here are my two models, Model 1 class CountryName1(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name the other model, Model 2 class TeslaModel1(models.Model): model_name = models.CharField(max_length=30) price = models.IntegerField() origin = models.ForeignKey(CountryName1, on_delete=models.CASCADE, related_name='teslamodels') def __str__(self): return self.model_name My serializers are like this class CountryNameSerializer(serializers.ModelSerializer): class Meta: model = CountryName1 fields = ['name'] class TeslaModelSerializer(serializers.ModelSerializer): origin = CountryNameSerializer() class Meta: model = TeslaModel1 fields = ['model_name', 'price', 'origin'] def create(self, validated_data): origin_data = validated_data.pop('origin') country_model = CountryName1.objects.create(**origin_data) Here are my views: class TeslaModelListCreateAPIView(ListCreateAPIView): queryset = TeslaModel1.objects.all() serializer_class = TeslaModelSerializer class CountryNameListCreateAPIView(ListCreateAPIView): queryset = CountryName1.objects.all() serializer_class = CountryNameSerializer -
Django PayPal delay
I'm creating a payment system for a project I'm working on and I'm using django-paypal. I followed their guide and implemented the signals and everything is working correctly (user clicks on a button -> gets redirected to paypal -> if everything is good success page is shown). The thing is in my signals I have a thing where I want to give users points when the do the buying function. I have that in my signals but there is a delay between showing the success page and the actual signal receiving the data and being executed. I don't know if this is because I'm using stuff like ngrok and localtunnel or is it something else. This is my signals.py from paypal.standard.models import ST_PP_COMPLETED from paypal.standard.ipn.signals import valid_ipn_received, invalid_ipn_received from account.models import Account def show_me_the_money(sender, **kwargs): ipn_obj = sender if ipn_obj.payment_status == ST_PP_COMPLETED: if ipn_obj.receiver_email != "**": # Not a valid payment print("BAD EMAIL") else: print("ALL GOOD") acc = Account.objects.get(account_url=ipn_obj.custom) acc.coins = acc.coins + int(ipn_obj.mc_gross) acc.save() else: print("FAIL") valid_ipn_received.connect(show_me_the_money) So if I'm understanding everything this is all correct but for some reason the delay is happening and I don't know whats causing it. -
Django - Extending user profile not showing fileds in chenge form
I want to extend the user model in django adding new fields and of course be able to manage it through the admin pages. I created a CustomUser model in django extending AbstractUser and added some extra fields, created a UserCustomCreateForm and UserCustomChangeForm to manage the creation and change and then registered a CustomUserAdmin that extend the UserAdmin adding the two forms. In admin, it seems to work fine when create a new users but unfortunately the new fields don't appear on the change view. What am i doing wrong? Thanks here is the models.py users/models.py # Create your models here. from django.db import models from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): # add additional fields in here address = models.CharField(max_length=50, null=True, verbose_name='Indirizzo') house_phone = models.CharField(max_length=20, null=True, verbose_name='Telefono') mobile_phone = models.CharField(max_length=20, null=True, verbose_name='Cellulare') def __str__(self): return self.first_name + ' ' + self.last_name here the forms # users/forms.py from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser from django import forms class UserCustomCreateForm(UserCreationForm): class Meta(UserCreationForm): model = CustomUser fields = ('username', 'email', 'first_name', 'last_name', 'address', 'house_phone', 'mobile_phone') class UserCustomChangeForm(UserChangeForm): class Meta: model = CustomUser fields = ( 'username', 'email', 'first_name', 'last_name', 'address', 'house_phone', 'mobile_phone') … -
Show the button based on value of one column
I'm using django and trying to create a template and the last column would be the "View". If the variable c equals success, then there will show a detail button. If error, then the view column in this row would be blank. How could I realize this idea? Btw, the button will pop up a modal form when clicking. "columns": [ {"data": "a"}, {"data": "b"}, {"data": "c"}, { "data": null, "defaultContent": '<button type="button" class="btn btn-info btn-sm">Detail</button>' }, ], -
Reverse related object lookup is not accessing in ForeignKey
I am Building a BlogApp and I stuck on a Problem. I am trying to access two model objects but Failed many times. models.py class Topic(models.Model): dairy_no = models.CharField(max_length=100000,default='') dairy_title = models.CharField(max_length=2000,default='') date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(Profile,on_delete=models.CASCADE,null=True) def __str__(self): return self.dairy_title class Entry(models.Model): topic = models.ForeignKey(Topic, on_delete=models.CASCADE,default='',related_name='topic') date_added = models.DateTimeField(auto_now_add=True,null=True) updated = models.DateTimeField(auto_now=True) note = models.TextField() def __str__(self): return str(self.topic) views.py def show_entry(request): showd = Journel.objects.all() context = {'showd':showd} return render(request ,'mains/showd.html', context) showd.html {% for post in topic.journel_set.all %} {{ post.dairy_title }} {{ post.note }} {% endfor %} The Problem I am trying to access both model's Objects in showd.html. What have i tried I saw tons of Answers like :- This This and Many More answers about reverse related object lookup. BUT nothing is worked for me. I don't know am i doing wrong in this. Any help would be Appreciated. Thank You in Advance. -
django channels is slow
I am using django channel to send periodic message to subjects. The messages are not instantaneously sent to consumers even when I just test with 2 players. I am struggling to improve it. Any ideas that I could try? I am using threading.timer if this is relevant. There is the code. def periodic_signal(self, subperiod, num_subperiods): start = time.time() msg = {} for p in self.get_players(): ...some code here msg[pcode] = {'subperiod': subperiod + 1, 'signal': sampled_choices_counter_list} channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)(self.get_group_channel_name(), { 'type': 'send.signal', 'msg': msg, 'time': time.time() }) # print('periodic_signal elapsed', time.time()-start) In consumers.py: def send_signal(self, event): msg = event['msg'] print('consumer elapsed', time.time() - event['time']) self.send_json({ 'msg': msg }) Here is some print output with 2 users and python 3.8.5: consumer elapsed 5.806595802307129 consumer elapsed 5.8080527782440186 consumer elapsed 0.007779836654663086 consumer elapsed 0.009441852569580078 consumer elapsed 5.816624164581299 consumer elapsed 5.818100929260254 It is improved if I use python 3.7.4 but still there is about 1 second delay sometimes. consumer elapsed 0.9057967662811279 consumer elapsed 0.8448600769042969 consumer elapsed 0.05404329299926758 consumer elapsed 0.051050424575805664 consumer elapsed 0.022072315216064453 consumer elapsed 0.014770746231079102 consumer elapsed 0.14920377731323242 consumer elapsed 0.15003633499145508 consumer elapsed 0.0430903434753418 consumer elapsed 0.04086613655090332 Django==2.2.12, channels==2.4.0 redis==3.3.8 -
How can I get 8 random images URLS from my database in Django?
I am having a situation where I am using build in User model which have One-to-One relation with my UserProfile Model. I have an image field for user profile image in my UserProfile model. So I have to show random 8 images URLS of my Users. How can I achieve this? Thanks in advance for your addition to my knowledge. -
Loading extra fields for update in Django dependent dropdown list
I implemented a dependent dropdown on my Django webapp. I used this tutorial Implementing dependent drop down. However, challenge comes when I want to update the form. To put this in perspective, let me recreate the code here. Model.py class VehicleMake(models.Model): make = models.CharField(max_length=20) manufacturer = models.CharField(max_length=20) def __str__(self): return self.make class VehicleModel(models.Model): make = models.ForeignKey(VehicleMake, on_delete=models.CASCADE) model_name = models.CharField(max_length=20) def __str__(self): return self.model_name class Vehicle(models.Model): model = models.ForeignKey(VehicleModel, on_delete=models.CASCADE) description = models.TextField() Notice that unlike in the provided tutorial, I don't have both of the dependent fields on the vehicle model. That is to avoid repetition since if you know the vehicle model, you will definitely know the make from the VehicleModel table. Here is the form: forms.py class VehicleDetails(forms.ModelForm): make = forms.ModelChoiceField(queryset=VehicleMake.objects.all(), empty_label="Select Vehicle Make") class Meta: model = Vehicle fields = ['make', 'model', 'description' ] def __init__(self, *args, **kwargs): super(VehicleDetails, self).__init__(*args, **kwargs) self.fields['model'].queryset = VehicleModel.objects.none() if 'make' in self.data: try: make = int(self.data.get('make')) self.fields['model'].queryset = VehicleModel.objects.filter(make=make).order_by('model_name') except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty VehicleModel queryset elif self.instance.pk: vehicle_model = VehicleModel.objects.get(self.instance.model) self.fields['make'] = vehicle_model.make self.fields['model'].queryset = self.instance.model_set.filter(make=vehicle_model.make).order_by('model_name') So, my challenge is, when I want to update the form, I get … -
How to replace Php contact form with DJango
I have website template downloaded and now I want to replace its contact form backend whichin PHP with django codes. I have created all the stuffs of django and can't figure out whats wrong because on requesting localhost its says sendEmail.php is missing which I delete as didn't need that for now. <div class="row contact__main"> <div class="col-eight tab-full contact__form"> <form name="contactForm" id="contactForm" method="post" action="{% url 'home' %}"> {% csrf_token %} <fieldset> <div class="form-field"> <input name="contactName" type="text" id="contactName" placeholder="Name" value="" minlength="2" required="" aria-required="true" class="full-width"> </div> <div class="form-field"> <input name="contactEmail" type="email" id="contactEmail" placeholder="Email" value="" required="" aria-required="true" class="full-width"> </div> <div class="form-field"> <input name="contactSubject" type="text" id="contactSubject" placeholder="Subject" value="" class="full-width"> </div> <div class="form-field"> <textarea name="contactMessage" id="contactMessage" placeholder="message" rows="10" cols="50" required="" aria-required="true" class="full-width"></textarea> </div> <div class="form-field"> <button class="full-width btn--primary" onsubmit="">Submit</button> <div class="submit-loader"> <div class="text-loader">Sending...</div> <div class="s-loader"> <div class="bounce1"></div> <div class="bounce2"></div> <div class="bounce3"></div> </div> </div> </div> </fieldset> </form> {% if contact_Name %} <!-- contact-success --> <div class="message-success"> Thanks {{ contact_Name }}! <br> Your mail has been recieved! I'll reply you shortly. </div> {% else %} <!-- contact-warning --> <div class="message-warning"> Something went wrong. Please try again. </div> {% endif %} This is my form code var ssContactForm = function() { /* local validation */ $('#contactForm').validate({ /* submit … -
Django retrieve data from html form
this is my form in html <form action="#about" method="POST"> {%csrf_token%} <h2>Signup today</h2> <input type="text" name="name" class="form-control" placeholder="Full name" required=""> <input type="email" name="email" class="form-control" placeholder="Your email address" required=""> <input type="password" name="password" class="form-control" placeholder="Your password" required=""> <button class="submit-btn form-control" id="form-submit">Get started</button> </form> and this is views.py def Student(request): if request.method=="POST": print('this post') name =request.POST['name'] email =request.POST['email'] print(name, email) return render(request,'#about') this is my urls.py from django.urls import path from . import views urlpatterns = [ path('',views.index, name='index.html'), path('',views.Student, name="#about"), ] I'm new to Django and I spent the last 24h trying to get this right, it doesn't show any error but it doesn't print any of what there is in views.py and it doesn't retrieve form data as well, could anyone explain to me what I'm doing wrong and how to properly retrieve html data form to django? Thank you very much in advance! -
Django: What is the difference between ./manage.py [...] and python manage.py [...]
I am following a tutorial for Django and at some point, it says to run ./manage.py migrate and says that if I get an error, I should fix it. I get an error but when I search for it I can't find specifically ./manage.py but I keep finding mixes with that and python manage.py. But when I run the code python3 manage.py everything works fine and I don't get errors. So are ./manage.py and python(3) manage.py different or not? -
Django Textarea contains additional newline
Why does a Django Textarea Widget render the additional newline? Textarea().render('name', 'value') Result: '<textarea name="name" cols="40" rows="10">\nvalue</textarea>' Is there a way to avoid the unneeded \n? -
how to split django rest and react app for docker
I'm trying do dockerize Django Rest Framework server and React app, but I don't understand howto manage connection between them. At the moment, they are connected like so: django-app settings.py: (with front beign my React app) INSTALLED_APPS = [ 'corsheaders', 'rest_framework', 'rest_framework.authtoken', 'django_database.apps.DjangoDatabaseConfig', 'rest_api.apps.RestApiConfig', 'front', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] And in my front directory I have: urls.py views.py . Now, if I'll split them in separate containers this solution is not going to work. Then what should I do insted ? -
How to pass primary key at views.py without changing url?
In index if someone clicks the link, the result will be incremented by 1. But if I enter http://127.0.0.1:8000/1 then the total_downloads is incremented by 1. But I want no change in url. So, in my index page, when download link will be hit by anyone the total_downloads will be updated by 1. My views.py: from django.shortcuts import render from django.http import HttpResponse import os from .models import FilesAdmin def index(request): context = {'file': FilesAdmin.objects.all()} return render(request,'libooki/index.html',context) def totals(request,pk): n = FilesAdmin.objects.get(pk=pk) n.total_downloads += 1 n.save() return HttpResponse("Downloaded!") def download(request,path): file_path = os.path.join(settings.MEDIA_ROOT,path) if os.path.exists(file_path): with open(file_path,'rb') as fh: response = HttpResponse(fh.read(),content_type="application/adminupload") response['Content-Disposition']='inline;filename'+os.path.basename(file_path) return response My urls.py: from django.conf.urls.static import static from libooki import views from django.conf.urls import url from django.views.static import serve urlpatterns = [ path('', views.index,name='index'), path('<int:pk>',views.totals,name='totals'), path('admin/', admin.site.urls), url(r'^download/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) My index.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>hello</title> </head> <body> {% for post in file%} <h2>{{post.name}}</h2> <a href="{{post.adminupload.url}}" download="{{post.adminupload.url}}">Download</a> {% endfor %} </body> </html> -
django on IIS encounter 404 for media file with chinese character in filename
I deploy django on IIS. Everything is ok. But I encounter 404 when I download a media file with chinese character in filename. Page not found (404) Request Method: GET Request URL: http://localhost:8089/media/attachment/2021/02/%25B2%25E2.txt Raised by: django.views.static.serve "D:\Python\MrDoc\media\attachment\2021\02\%B2%E2.txt" Not exist. I know that %B2%E2 is URLencode with gb2312 of chinese character '测'. When the media file name contains only ASCII, such as 1.txt, no 404 and the file can be downloaded via browser. When I run server with "py manage.py runserver 0.0.0.0:8088", no 404 for media file name with chinese character. So the 404 problem is probably caused by the urlencode of IIS. I do not know how to solve this problem. The web.config file content: <?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <handlers> <add name="DjangoWebHandler" path="*" verb="*" modules="FastCgiModule" scriptProcessor="D:\Python\virtualenv\MrDoc\Scripts\python.exe|&quot;D:\Python\virtualenv\MrDoc\Lib\site-packages\wfastcgi.py&quot;" resourceType="Unspecified" /> </handlers> </system.webServer> </configuration> The settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') The urls.py: re_path('^static/(?P<path>.*)$',serve,{'document_root':settings.STATIC_ROOT}), re_path('^media/(?P<path>.*)$',serve,{'document_root':settings.MEDIA_ROOT}), or: ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
how to register this offline wallet in sign up?
here is my view.py from models import balance def profile(request): user = balance.objects.get(user=request.user return render(request,'profile.html',{"balance":user.balance}) and created model here class Balance(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) balance = models.IntegerField(default=0) def __str__(self): return self.user.username here is my registration and i think i have made mistake here: @unauthenticated_user def register(request): form = CreateUser() if request.method == 'POST': form = CreateUser(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') instance = Balance(user=request.user, balance=0) instance.save() messages.success(request, "Congrats !!" + username + "now you are member of the society") return redirect('login') context = {'form': form} return render(request, "register.html", context) I am able fetch the balance of the user in from the database at the time of showing the profile but not able save it into database while registration. As erorr returns: ValueError at /register/ Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x7f98c64caa60>>": "Balance.user" must be a "User" instance