Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
heroku ps:scale web=1 Scaling dynos... Couldn't find that process type (web)
So I am making my portfolio python django website, while deploying I am getting an error I am try to type this heroku ps:scale web=1 and I am getting this error Scaling dynos... ! ! Couldn't find that process type (web). please help me out I want to show my class teacher this portfolio webpage but it would be very shameful to show her a locally hosted website -
Reverse for 'post_share' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<post_id>[0-9]+)/share/$']
show_more.html <p> <a href="{% url 'mains:post_share' post_id %}">Share This Post</a> </p> urls.py path('<int:post_id>/share/',views.post_share,name='post_share'), views.py def post_share(request, post_id): post = get_object_or_404(Post,pk=post_id, status='published') if request.method == 'POST': form = EmailPost(request.POST) if form.is_valid(): else: form = EmailPost() return render(request, 'mains/post_share.html', {'post':post,'form':form}) forms.py class EmailPost(forms.Form): name_subject = forms.CharField(max_length=400) email = forms.EmailField() description = forms.CharField(required=False,widget=forms.Textarea) Reverse for 'post_share' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<post_id>[0-9]+)/share/$']. This error is raising when i click on share the Post. Please help me to solve this Error. I will really appreciate your Help. -
nginx have access to static file but raises 403 permission error for downloading a file
I use django and nginx is the server. nginx has access to static folder and serves all static files. but I've defined a file field like: pp_file_url = models.FileField(, upload_to='app/', default='app/app.apk') and app folder has been created inside static folder which nginx has access to. I can properly upload a file in admin and I can access that file on the server. but when I want to download it through the admin of my website it raises this error: 403 Forbidden nginx/1.14.0 (Ubuntu) I've defined the static folder in .conf and used chmod 777 /static-root/app. It didn't solve my problem. -
Django Change a form structure by user
I am working in Django project that need to have a form that the user can change the structure of the form, for example if the default form is <form> <input type="text" value="3"> </form> the user can change it like <form> <input type="text" value="5"> <input type="text" value="6"> </form> The user can add, edit or delete an input. I have seen on internet the django admin site but it change only the data. Please, Help me -
Reverse for 'post_share' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<post_id>[0-9]+)/share/$'] [ ASKING AGAIN ]
show_more.html <p> <a href="{% url 'mains:post_share' post_id %}">Share This Post</a> </p> urls.py path('<int:post_id>/share/',views.post_share,name='post_share'), views.py def post_share(request, post_id): post = get_object_or_404(Post,pk=post_id, status='published') if request.method == 'POST': form = EmailPost(request.POST) if form.is_valid(): else: form = EmailPost() return render(request, 'mains/post_share.html', {'post':post,'form':form}) forms.py class EmailPost(forms.Form): name_subject = forms.CharField(max_length=400) email = forms.EmailField() description = forms.CharField(required=False,widget=forms.Textarea) I am asking it again but the previous answers didn't solve my problem. So i think i should upload it again with more efficiently. Reverse for 'post_share' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<post_id>[0-9]+)/share/$']. This error is raising when i click on share the Post. Please help me to solve this Error. I will really appreciate your Help. -
django, mod_wsgi and apache: error client denied by server configuration
My apache sites-available configuration is as below. (I already tried many things from other's answers for the same problem) In the browser, it is showing the error forbidden error and in the error log shows client denied by server configuration error. <VirtualHost *:80> #ServerName www.project.com ServerAdmin user_xmaster@localhost #DocumentRoot /var/www/html DocumentRoot /home/user_x/project/django-project Alias /static /home/user_x/project/user_x/static <Directory /home/user_x/project/user_x/static> Require all granted </Directory> <Directory /home/user_x/project/django-project> <Files wsgi.py> Require all granted </Files> </Directory> WSGIApplicationGroup %{GLOBAL} WSGIPassAuthorization On WSGIDaemonProcess user_xenv python-path=/home/user_x/project/django-project python-home=/home/virtualenvs/env WSGIProcessGroup user_xenv WSGIScriptAlias / /home/user_x/project/django-project/wsgi.py ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> -
How to use config MAINTENANCE_MODE_IGNORE_URLS in django-maintenance-mode
I'm using the django library django-maintenance-mode. This library is used to put the page in maintenance mode (thank you Angel) Everything works fine but there is one configuration that I can't make work: MAINTENANCE_MODE_IGNORE_URLS The only page that I don't want to be in maintetance mode in the login page because the admins will need to log in and the maintenance won't affect them. The docs says this list of urls that will not be affected by the maintenance-mode urls will be used to compile regular expressions objects MAINTENANCE_MODE_IGNORE_URLS = () My problem is that I don't know what should I write in the parenthesis these are my urls: urlpatterns = [ path('login/', login_view, name="login"), path('register/', register_user, name="register"), path("logout/", LogoutView.as_view(), name="logout") ] I tried: 'login', 'login/' but didn't work... If someone could help me I would really appreciate it -
How to enable pagination to work if Filter results are more than the specified records in page
I have implemented Filter and Pagination together in the same view class and per page, I am displaying 50 records and without performing any filter operation if I will click on the next page it is working as expected. But suppose if I am doing a filter based on the project name and it contains 70 records so I will get 50 records but when click on the next page to see the remaining 30 it is redirecting me to default page no 1. Please find the views.py def retrievermsi_view(request): allrmsi = RMSI.objects.all() rmsi_list = RMSI.objects.all() rmsi_filter = RMSIFilter(request.GET, queryset=rmsi_list) allrmsi = rmsi_filter.qs paginator = Paginator(allrmsi,50) page_number = request.GET.get('page') try: allrmsi = paginator.page(page_number) except PageNotAnInteger: allrmsi = paginator.page(1) except EmptyPage: allrmsi = paginator.page(paginator.num_pages) return render(request, 'apple/shift2rmsi.html', {'allrmsi': allrmsi,'rmsi_filter':rmsi_filter}) My filters.py file class RMSIFilter(django_filters.FilterSet): id = django_filters.NumberFilter(label="DSID") class Meta: model = RMSI fields = ['name', 'EmailID','id',] -
Django - ajax fetching from Google books API
I would like to implement one feature. In my app a user can insert a book, I would like to add field that would look for the book (live search) in the Google books API (based on title, or ISBN), and then prepopulate form with relevant data. This is my first time trying to develop something like this just by myself, so maybe someone could give me some tips. My question at the moment is, should I make a specific view, that would fetch the data and then send it back to template? Or, no view is required and I just fetch directly from template? I do have it like this, but what I don't like is that anyone can see I'm fetching from googlebooks and also my key is visible. -
Permanent redirect absolute url
I am struggling with a basic redirect functionality. I need to redirect all traffic not matching certain paths to another domain. in my urls.py re_path(r'^(?P<shortcode>[\w-]+)/$', core_views.myView) and the corresponding function in views.py def myView(request, shortcode=None): url = 'www.newdomain.cz/' + str(shortcode) return HttpResponsePermanentRedirect(url) but what it does is - when called for example www.olddomain.com/sdfasd it redirects me to www.olddomain.com/sdfasd/www.newdomain.cz/sdfasd but I obviously need only www.newdomain.cz/sdfasd what am I missing? -
DRF returns 400 Bad Request
I am new to Django Rest Framework and I am trying to send an object from a Flutter app to DRF backend. I have a BatchGuideDraft and I want to send it to backend inside POST method but I am getting a 400 Bad Request error. I have either 2 problems, first one is I am not mapping the object properly on the app side; second one is I am not able to deserialize it on backend. I couldn't find the problem why and I need your help here. This is my BatchGuideDraft model on Flutter side: class BatchGuideDraft implements BaseRequestModel { final String description; final String frequencyTitle; final DateTime startDate; final DateTime endDate; final ReminderType reminderType; final List<DateTime> reminderDates; bool repeating; int batchID; BatchGuideDraft({@required this.frequencyTitle, @required this.description, @required this.startDate, @required this.endDate, @required this.reminderType, @required this.reminderDates, @required this.repeating}); @override Map<String, dynamic> toMap() { assert(batchID != null); return <String, dynamic>{ 'description': description, 'frequency_title': frequencyTitle, 'start_date': startDate.toString(), 'end_date': endDate.toString(), 'reminder_type': reminderType.index.toString(), 'reminder_dates': reminderDates.map((e) => e.toString()).toList().toString(), 'batch': batchID.toString(), 'repeating': repeating.toString(), }; } } And this is how I try to send it: Future<void> createBatchGuide(BatchGuideDraft guide) async { await _post(["v1", "app", "guide"], guide.toMap()); } This is my BatchGuideDraftSerializer on API side: class BatchGuideRequestSerializer(serializers.ModelSerializer): done … -
Django saving a array of foreing keys linking to documents and pictures
I am creating an online app where people digging in the streets can register their digsite on a map and the council can approve it. Since we are using qgis also i am using a postgresdatabase in the backend. Now i have all the bits and pieces of my site, but i am struggeling how to handle the documents and images in django. I want the user when registratin a new dig site to upload all the documents (2-5 drawings etc) then I want the documents to be recorded in one table and stored in a folder like "/digsite/{dig_id}/documents/" and the same for pictures. In the digging permittion table i would like to store an array of assosiatet documents and images. I get it all to work with the creation of a digsite, users and user permittions and i have made an uploading function for the images witch get the GPS position and so on. But i cant figure out how i store multiple ids into the array field upon uploading pictures and documents. The pictures and documents are combined into the same form as the digging permittion. Anyone that knows a decent toturial or can give me some starter … -
How to populate serializer fields in Django Rest Framework (DRF)?
I am new to Django and DRF and am implementing JWT token authentication using simplejwt library (though the question is not related to simplejwt, but Django and DRF in general). I wrote a simple View class GenerateTokenPairView(TokenObtainPairView): permission_classes = (AllowAny,) serializer_class = GenerateTokenPairSerializer and the corresponding serializer class GenerateTokenPairSerializer(TokenObtainPairSerializer): email = serializers.EmailField(required=True, validators=[EmailValidator]) password = serializers.CharField(max_length=128, write_only=True, required=True) Have overridden validate function as below: def validate(self, attr): data = dict() user = self.authenticate(attr) refresh = self.get_token(user) data['refresh'] = str(refresh) data['access'] = str(refresh.access_token) self.cache_tokens(data) return data where authenticate and cache_tokens are custom methods. I have seen in the base (library) View - TokenViewBase, the following implementation for post method- def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) try: serializer.is_valid(raise_exception=True) except TokenError as e: raise InvalidToken(e.args[0]) return Response(serializer.validated_data, status=status.HTTP_200_OK) Am I correct in assuming that the line serializer = self.get_serializer(data=request.data) should get the email and password fields on GenerateTokenPairSerializer to populate? If not, could someone explain how do I do that? Libraries used- python==3.5 Django==2.2.16 djangorestframework==3.8.2 djangorestframework-simplejwt==4.3.0 -
Field 'id' expected a number but got "{ url 'mains:post_share' post_id %}"
This error is raised when i click on share post ( in post_share.html ( check below ) ). :- Field 'id' expected a number but got "{ url 'mains:post_share' post_id %}". Here is my Code :- def post_share(request, post_id): post = get_object_or_404(Post,id=post_id, status='published') if request.method == 'POST': form = EmailPost(request.POST) if form.is_valid(): else: form = EmailPost() return render(request, 'mains/post_share.html', {'post':post,'form':form}) urls.py path('<int:post_id>/share/',views.post_share, name='post_share'), post_share.html <p> <a href="{ url 'mains:post_share' post_id %}">Share This Post</a> </p> I've tried everything but nothing works. Please help me in this, I will really appreciate your Help -
post a list of objects Django
Hi I'm trying to make a post request like this [ { "question": "", "answer": "", "position": 0 }, { "question": "", "answer": "", "position": 1 }, { "question": "", "answer": "", "position": 2 }, { "question": "", "answer": "", "position": 3 }, { "question": "", "answer": "", "position": 4 } ] The max number of question answers can be 5, but for example I can send 2. I don't understand how this can be implemented. Each such question should be saved separately in the database. -
What is the best way to implement branch model in a multi branch school management system in Django
I am implementing a School managment system using django, in each branch there are multiple modules like student data management, an app to handle HR related functions and an app to handle the accounts. I want to implement thhis for multiple branches of the school. I can't think of a way to implement this for multiple branches. I want to keep it optional which module can be used in a branch(Student, HR, Accounting) -
Can anyone explain how webhooks interact between a client side app say JS and a server side app say in Flask or Django
I am not a complete beginner in web development however for now I am exploring and evaluating methods to update real-time data onto my front-end client written in JavaScript, data may be coming from somewhere to my back-end server which is written in Flask or Django. I have tried out methods like Short polling, Long polling and Web-sockets, then I came across this method of Reverse API or Web-hook. I read about it and also implemented a basic version in Python Flask framework by creating a POST method based Web-hook route, then using Ngrok I got a forwarded URL, which I registered on Git-hub Web-hook and I was able to receive notifications in my back-end related to pull requests, issues and stuff from Git-hub. What I could not understand here was, how it is working, basically I did nothing other than creating a POST API route (which I commonly always do in any rest-API server) that accepts data in JSON and shows it to me. Ngrok just exposed the local-host to the global network and the actual action was happening from Git-hub itself, i.e. whenever new pull requests come in it would POST to my Ngrok provided URL. That's still … -
Getting error 'ImportError: cannot import name md5', when installing pip on macOS Catalina
So I'm trying to install pip on my macOS and when I'm running sudo python get-pip.py command and I'm getting the following error: ERROR:root: code for hash md5 was not found. Traceback (most recent call last): File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module> globals()[__func_name] = __get_hash(__func_name) File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor raise ValueError('unsupported hash type ' + name) ValueError: unsupported hash type md5 ERROR:root:code for hash sha1 was not found. Traceback (most recent call last): File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module> globals()[__func_name] = __get_hash(__func_name) File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor raise ValueError('unsupported hash type ' + name) ValueError: unsupported hash type sha1 ERROR:root:code for hash sha224 was not found. Traceback (most recent call last): File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module> globals()[__func_name] = __get_hash(__func_name) File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor raise ValueError('unsupported hash type ' + name) ValueError: unsupported hash type sha224 ERROR:root:code for hash sha256 was not found. Traceback (most recent call last): File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module> globals()[__func_name] = __get_hash(__func_name) File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor raise ValueError('unsupported hash type ' + name) ValueError: unsupported hash type sha256 ERROR:root:code for hash sha384 was not found. Traceback (most recent call last): File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module> globals()[__func_name] = … -
Special characters in django allauth subject line
I am using allauth's ResetPasswordForm for password reset process. This form's save method sends the password reset email. I customized the password reset template to use it in Turkish, so it includes some special characters. The email message itself is printed perfectly, displaying the special characters the right way. However, the subject line is printed as below for a subject I enter e.g. "öla". "Subject: =?utf-8?b?W2V4YW1wbGUuY29tXSDDtmxh?=" If I give the subject "ola" without using the accent, there is no problem, it prints "Subject: ola" to the console. To stress again, this does not happen in the email body, which prints several special characters correctly. I only changed the allauth's template, and did not change anything in the form class. Any idea how to fix this? Thanks. -
I want to look up 2 models in Django and get the following results:
I have 2 models like below. class Card(models.Model): title = models.CharField(max_length=100) description = models.CharField(max_length=200) class Word(models.Model): cardname = models.ForeignKey(Card, on_delete=models.CASCADE) word1 = models.CharField(max_length=50) word2 = models.CharField(max_length=100) I would like to query 2 models and get the following results. I would like to print a list of cards and print the total number of words of the card. Card.title Card.description sum(Word) titleA aaaa 10 titleB bbbb 20 I'm a beginner in Django's query set. -
Django model form instantiation takes too long (eventually times out)
I'm using Django generic class views(CreateView) and Django ModelForms. But the form instantiation seems to get stuck for some reason. Here's my views.py class NewExternalWorkOrder(CreateView): model = ExternalWorkOrder template_name = 'new_external_work_order.html' form_class = ExternalWorkOrderForm My ExternalWorkOrder model: class ExternalWorkOrder(models.Model): asset = models.ForeignKey(Asset, null=True, blank=True, on_delete=models.DO_NOTHING) inventory_item = models.ForeignKey(Item, null=True, blank=True, on_delete=models.DO_NOTHING) inventory_item_quantity = models.PositiveIntegerField(validators=[MinValueValidator(1)], null=True, blank=True) number = models.CharField(max_length=50, null=True) date_created = models.DateTimeField(default=timezone.now) nature_of_problem = models.TextField() mileage_hours = models.PositiveIntegerField(null=True, blank=True) #...more fields... and my form class class ExternalWorkOrderForm(forms.ModelForm): def __init__(self, * args, ** kwargs): super(ExternalWorkOrderForm, self).__init__(*args, **kwargs) class Meta: model = ExternalWorkOrder fields = ['asset', 'inventory_item', 'inventory_item_quantity', 'nature_of_problem', 'mileage_hours'] widgets = { 'asset': forms.Select(attrs={'class': 'browser-default'}), } All this was working a few days back but it suddenly stopped working. The page now loads forever and the gunicorn worker always times out(I increased the timeout to over 5 minutes). I know that Django is getting stuck somewhere in the instantiation of the form because I tried overriding the get method or even using function views and comment out the form instantiation and everything would then work. Does anyone have an idea of what might be wrong? -
Downloading not showing in Python
Actually, I created a Youtube video download website using Django. But when I download the video, not showing the downloading process in the browser. It's just downloaded in the project location. -
Having trouble updating database with Django
Hey guys my code is a bit jumbled but maybe you can help me sort out why it's not doing what I want it to do. There's something wrong with my logic since I have tried the update statements on their own and they do work. I can't figure out why it won't go to the elif statement. The Vote table is just postID, username, upvote and downvote. I want it to work if a user has a record in the table for that postID and they have upvote marked as 1, then you should be able to only downvote. Currently, it doesn't let you vote twice, but it won't let you vote at all if you've already cast a vote. Here is my relevant code. Thanks! def upvote(request): postID = request.POST.get("postID") currentUser = request.POST.get("currentUser") username = request.POST.get("username") query = NewPost.objects.get(id = postID) check = Vote.objects.filter(postID = postID) & Vote.objects.filter(username = currentUser) if(len(check) < 1): query.rating = query.rating +1 query.save() query2 = User.objects.get(username = username) query2.userRanking = query2.userRanking +1 query2.save() new = Vote.objects.create(postID = postID, username = currentUser, downvote = 0, upvote = 1) new.save() pyautogui.hotkey('f5') return render(request) elif(len(check) > 1): if(check[0].upvote == 0): check.update(downvote = 0) check.update(upvote = 1) … -
IntegrityError Exception Value: NOT NULL constraint failed: accessories.price
i m facing this issues i have deleted migrations added not Null to price again migrate but issue haven't resolved. can someone help me with this. NOT NULL constraint failed: accessories.price class Accessories(models.Model): product = models.ForeignKey(Product, related_name='accessories', on_delete=models.CASCADE) acessoriesname = models.CharField(max_length=200, blank=True) acessoriestype = models.CharField(max_length=200, blank=True) price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) acessoriesimage = models.ImageField(upload_to='products/%Y/%m/%d', blank=True) acessoriesdescription = models.TextField(blank=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ('acessoriesname',) db_table = "accessories" default_permissions = ('view', 'change', 'delete', 'add') permissions = ( ('view_accessory', 'Can view accessories'), ("add_accessory", "Can add accessories"), ("change_accessory", "Can change accessories"), ("delete_accessory", "Can delete accessories") ) def __str__(self): return self.acessoriesname -
How to Implement download image size based on pixel option during download
def image_download_size(request, download_id): get_all_category = Images_category.objects.all() get_filter_image = Images.objects.filter(pk=download_id) if request.method == 'POST': image_size = str(request.POST["image_size"]) if image_size == 'option1': get_image = Image.open(get_filter_image) width, height = get_image.size print(width, height) new_width = width // 2 new_height = height // 2 resized_image = get_image.resize(new_width, new_height) current_size = resized_image.size print(current_size) print(resized_image) pro = {'resize': resized_image, 'current_size': current_size} return render(request, 'download_image.html', pro) if image_size == 'option2': get_image = Image.open(get_filter_image) width, height = get_image.size print(width, height) new_width = width // 3 new_height = height // 3 resized_image = get_image.resize(new_width, new_height) print(resized_image) current_size = resized_image.size print(current_size) pro = {'resize': resized_image, 'current_size': current_size} return render(request, 'download_image.html', pro) if image_size == 'option3': get_image = Image.open(get_filter_image) resized_image = get_image current_size = get_image.size print(resized_image) print(current_size) data = {'image': get_filter_image, 'category': get_all_category} return render(request, 'download_image.html', data)