Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Improving accuracy in Python Tesseract OCR
I am using pytesseract along with openCV in a simple django application in Python to extract text in Bengali language from image files. I have a form that lets you upload an image and on clicking the submit button sends it to the server side in an ajax call in jQuery to extract the text from the image to serve the purpose of OCR (Optical Character Recognition). Template part : <div style="text-align: center;"> <div id="result" class="text-center"></div> <form enctype="multipart/form-data" id="ocrForm" action="{% url 'process_image' %}" method="post"> <!-- Do not forget to add: enctype="multipart/form-data" --> {% csrf_token %} {{ form }} <button type="submit" class="btn btn-success">OCRzed</button> </form> <br><br><hr> <div id="content" style="width: 50%; margin: 0 auto;"> </div> </div> <script type="text/javascript"> $(document).ready(function(){ function submitFile(){ var fd = new FormData(); fd.append('file', getFile()) $("#result").html('<span class="wait">Please wait....</span>'); $('#content').html(''); $.ajax({ url: "{% url 'process_image' %}", type: "POST", data: fd, processData: false, contentType: false, success: function(data){ // console.log(data.content); $("#result").html(''); if(data.content){ $('#content').html( "<p>" + data.content + "</p>" ) } } }) } function getFile(){ var fp = $("#file_id") var item = fp[0].files return item[0] } // Submit the file for OCRization $("#ocrForm").on('submit', function(event){ event.preventDefault(); submitFile() }) }); </script> The urls.py file has: from django.urls import path, re_path from .views import * urlpatterns … -
Check if token exist
How can i check if the token i'm sending to django exist? does jango rest framework has a built-in function to check this? Currently i've the login and i'm creating the token each time a user logs in c86177ae21c1c0b83a5c0354e742334ef2f376f3 -
Django Mysql string convertion utf8 and unicode?
Well, I have a django model that stores the name of a music band. So new trouble arises when a band called '✝✝✝ (Crosses)' attempts to be stored in a TextField. This is the error: django.db.utils.OperationalError: (1366, "Incorrect string value: '\\xE2\\x9C\\x9D\\xE2\\x9C\\x9D...' for column 'album_name' at row 1") But this becomes weird because I have another table that stores a JsonField with the band info. The same name '✝✝✝ (Crosses)' is stored correctly. the JsonField was a TextField that stored json.dumps(dict_with_band_info) ... So in the database is stored something like { "name": "✝✝✝ (Crosses)" ...}. And repeat, this was a TextField before and works as expected. So why attempting to add "name": "✝✝✝ (Crosses)" to the db Textfield shows that error but not in the other table no? I'm using pdb.set_trace() to see what are the values before do the save(). I would like to mention again that that error doesn't appear even when the JsonField was TextField in my band info table, but the error appears in the TextField of the band_name and exactly in the instance.save(). with this, I can deduct that my text_fields are ready to receive unicode, because in the band info table, the jsonfield shows the … -
I raise two validationerror but if anyone of them is triggered it always gives me the same validation error output
I raised two validationerror messages but if anyone is triggered it gives me the same message of one of the the message is "User has already a current profile model try to update it not creating a new one" here is the code class CurrentProfileSerializer(serializers.ModelSerializer): class Meta: model = CurrentProfile fields = '__all__' read_only_fields = ('user', ) def create(self, validated_data): try: c_profile = CurrentProfile(**validated_data) if c_profile.profile.owner != c_profile.user: raise serializers.ValidationError('You can only use profiles that the user created') c_profile.save() return c_profile except: raise serializers.ValidationError('User has already a current profile model try to update it not creating a new one') the try and except block is made because i mad a OneToOne realtionship in my model CurrentProfile with the user model so it will trigger an error if i tried to add more than one instance of the CurrentProfile Model with same user. the validation error in the if block is made to ensure that the profile selected is created by the same user not just any random profile created by another user the weird thing is that if i remove the try and except block it works fine but when add it again in both cases it gives me the … -
How to use Ajax in Django to change image url
I'm using Django with Ajax ,I have already used Ajax to upload image successfully. Now I want to figure out how to use Ajax direct change the image url. Html: {% block content %} <div class="row"> {{user.username}} {{user.avatar.url}} <p id="error"></p> <div class="col-md-2"> <img class="avatar" src="{{user.avatar.url}}" width="60px" height="60px" /> </div> <div class="mb-2"></div> {% if request.user.username == profile_user.username %} <form enctype="multipart/form-data" class="form-horizontal" method="post"> {% csrf_token %} <label for="avatar" class="change-avatar" >更换头像/change avatar</label> <input type="file" id="avatar" style="visibility:hidden;"> <input type="button" class="btn" value="保持更改/save"> </form> <script> $(".btn").click( function(){ var formdata = new FormData(); formdata.append("avatar",$("#avatar")[0].files[0]); $.ajax({ url:"", type:"post", contentType:false, processData:false, data:formdata, beforeSend: function (xhr, settings) { xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}"); }, success:function(data){ console.log(data) var error = data.error var avatar = data.avatar var s =`<div> ${error} </div>` var t = '${avatar}' var src = $(".avatar").attr('src').replace('avatar','avatar') $(".avatar").attr('src', src); $("#error").prepend(s); } }) } ) </script> {% endif %} </div> {% endblock content %} views: @login_required def user_detail(request, username): profile_user = get_object_or_404(User, username=username) form = UserAvatar(request.POST, request.FILES, instance=request.user) response = {} if request.is_ajax(): if form.is_valid(): form.save() response['avatar'] = request.FILES.get('avatar') else: response['error'] = '格式错误' return JsonResponse(response) return render(request, 'user/user_detail.html', { 'profile_user': profile_user, }) -
In Python Graphene is there any way to set common graphene fields for class and class arguments at one place instead of defining it at both places?
Please find the link below for the graphql queries https://www.howtographql.com/graphql-python/3-mutations/ -
Internal Server Error when implementing Allauth with Django, Nginx and uWSGI
As of this moment, I have been able to successfully implement google sign into my website while I run it locally on my machine while using a plugin known as Django-allauth. However, when I try moving it over to my AWS lightsail server, I get an “internal server error” the moment the website is attempted to load. To give some information to how we are running the website, I have the backend running through Django, and the frontend which serves the static files running through NGINX. The front end is connected through uWSGI and micro uWSGI to the backend. Also, I have all of this automized through emperor so that I don’t have to constantly run the command to run the server. While doing troubleshooting by entering one line of code at a time for the integration of allauth, I discovered that the error pops up when I try adding “allauth” to installed apps in the settings.py file. Thinking that this was because allauth may not have been installed, I tried installing it again in different versions to see if that would make a difference. It did not. Through the research that I have done, I have found that it … -
IntegrityError Django Postgres when deleting
This is the error, I get it when I delete a TaskList, which is related to ChartDay which is related to MemberRemaining all with on_delete CASCADE, If a delete TaskList the Charts related to it should be deleted, same way happens with ChartDay to Chart and MemberRemaining to ChartDay. Why am I getting this error? insert or update on table "chart_memberremaining" violates foreign key constraint "chart_memberremainin_chart_day_id_e25c792b_fk_chart_cha" DETAIL: Key (chart_day_id)=(7) is not present in table "chart_chartday". class TaskList(models.Model): members = models.ManyToManyField( to=get_user_model(), through='TaskListMemberShip', related_name='task_lists', blank=True ) name = models.CharField(max_length=60, null=True) color = models.CharField(max_length=7, default='#ffffff', null=True) avatar = StdImageField( upload_to=FilePattern(filename_pattern='task_lists/{uuid:base64}{ext}'), variations={ 'normal': {'width': 200, 'height': 200, 'crop': True}, 'small': {'width': 50, 'height': 50, 'crop': True}, }, null=True, blank=True, ) organization = models.ForeignKey(Organization, related_name='task_lists', on_delete=models.CASCADE) auto_created = models.BooleanField(default=False) objects = TaskListManager() class Chart(models.Model): """ Chart model. """ start_date = models.DateField(null=True) end_date = models.DateField(null=True) estimated = models.DecimalField(max_digits=4, decimal_places=1, null=True) task_list = models.ForeignKey( TaskList, related_name='charts', on_delete=models.CASCADE) class ChartDay(models.Model): """ Chart day model. """ date = models.DateField() chart = models.ForeignKey( Chart, related_name='chart_days', on_delete=models.CASCADE ) class MemberRemaining(models.Model): """ Member remaining model. """ member = models.ForeignKey( get_user_model(), on_delete=models.SET_NULL, null=True ) chart_day = models.ForeignKey( ChartDay, related_name='members_remaining', on_delete=models.CASCADE ) remaining = models.DecimalField(max_digits=4, decimal_places=1, null=True) -
Django how to compare auto_now and auto_now_add
created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) I have used this code to stamp the time. And used the following to compare the two and if it is edited I set to express the updated time as shown below. {% if comment.created_at != comment.modified_at %} <p class="text-muted float-right"><small>Updated: {{ comment.modified_at }}</small></p> {% endif %} However, all of the comments say that it has different created_at and modified_at values even though I did not edit thus the two values would be the same. How could I fix this problem? Thanks. -
Django Model is creating another model after editing it
I made a random number creator in a model and if I make changes on an object Cakmak on the admin page, after saving it, it creates another one with the same name but different no. from django.db import models from random import randint class Cakmak(models.Model): marka = models.CharField(blank=True, max_length=200) model = models.CharField(blank=True, max_length=200) no = models.IntegerField(primary_key=True, unique=True, editable=False, ) def save(self): no = randint(100000, 999999) if Cakmak.objects.filter(no=no).exists(): super(Cakmak, self).save() else: self.no = no super(Cakmak, self).save() def __str__(self): return (self.marka) + (' ') + (self.model) -
How to get queryset with total seconds from sum of DurationField
Suppose, I have a Django model called MyModel like this: class MyModel(models.Model): event_started = models.DateTimeField(default=timezone.now) event_duration = models.DurationField() Now I want to get a queryset with the total seconds grouped by day. The following code returns the queryset with the total duration as timedelta instead of seconds: from django.db.models import Sum qs = (MyModel.objects .annotate(date=TruncDay('event_started')) .values('day') .annotate(total_duration=Sum('event_duration')) .order_by('-day') ) I want to include the total seconds instead of timedelta in the total_duration field of the queryset. How can I do that? -
Deployment Djnago appilication WSGI.py error
As i am deploying my django project on server i get a error Internal server Error but on the production server my code runs bug free and also i tried on server local host 0.0.0.0:8000 but when i create a virtual host and try to access my project from the domain or server ip i get screen with error internal server error. on ther server error logs the error i get is enter image description here I already tried hosting on differnt server modifying wsgi file but same result. -
Getting an error when creating Superuser in Django
File "C:\Users\Name\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\dispatch\dispatcher.py", line 179, in for receiver in self._live_receivers(sender) TypeError: create_profile() missing 1 required positional argument: 'senerd' Getting this error when creating a Superuser in Django with VS Code terminal, did I miss something? anyone else get this before? -
too many redirect issue, if the URL doesn't end by slash
I'm working on a small project using Django Rest Framework, everything is going well, I have just a small issue about the URLs, if the user enters the URL in the browser without slash / at the end. he get redirected too many times to login page like that /login/login/login/login/login how can I fix that This is my code : from django.urls import path from list.api.views import ListView from rest_framework import routers router = routers.DefaultRouter() router.register(r'list', ListView, basename="list") urlpatterns = router.urls This is my settings.py : LOGIN_URL = 'account/login/' LOGIN_REDIRECT_URL = '/' LOGOUT_REDIRECT_URL = '/' -
jQuery autcomplete Django forms
I have integrated the jQuery autocomplete in Django and it works on the frontend side. The goal is to let users filter the data with the input. Is there any way to integrate jQuery-autocomplete with the django forms? If not, how hard is it to write the html code for the forms to connect it back to views.py? Is there any templates for such basic forms? (My only "form field" is a name) -
Django same username in different organizations
I am building an API with Django rest, and I am dealing with a situation where I have to authenticate users with the same username but in different organizations and I have no idea how to do it, any suggestions ?? I would be grateful. -
How can show the vendors againt the product id in django
At this time i am select the vendor through the category id, but i want to show the vendor against the product when i place the order. Then all vendor against that product should show, but i don't know how can i do that. Because without passing the product_id it's impossible.How can i pass the product id in place order button View.py class OrderProduct_View(TemplateView): template_name = 'purchase/orderProduct.html' def get(self, request, *args, **kwargs): allOrder = OrderProduct.objects.all() categories = Category.objects.all() categoryId = self.request.GET.get('SelectCategory') product = Product.objects.filter(category_id=categoryId) args = {'categories': categories, 'product': product, 'allOrder': allOrder} return render(request, self.template_name, args) def post(self, request): productobj = self.request.GET.get('SelectProduct') if productobj: messages.info(request, productobj) try: data = self.request.POST.get orderProducts = OrderProduct( product_id=productobj, description=data('description'), quantity=data('quantity'), ) orderProducts.save() return redirect('orderProduct') except Exception as e: return HttpResponse('failed{}'.format(e)) class All_Vendor(TemplateView): template_name = 'purchase/allVendor.html' def get(self, request, *args, **kwargs): try: categories = Category.objects.all() categoryId = self.request.GET.get('SelectCategory') vendors = Vendor.objects.filter( vendorcategory__category_id__exact=categoryId ) args = {'categories': categories, 'selectedCategory': categoryId, 'vendors': vendors} return render(request, self.template_name, args) except Exception as e: return HttpResponse('failed{}'.format(e), 500) Template Order product {% block content %} <form method="get"> {% csrf_token %} <label> <select name="SelectCategory"> <option disabled="disabled" selected> Select Category</option> {% for category in categories %} <option value="{{ category.id }}"> {{ category.name }} … -
How to fix the issue 'add_students_by_manager' object is not iterable
I am trying to display some data in my templates by passing it as context. I noticed that the problem actually has to do with outputting the result on the template. how can i fix this please. models.py class add_courses(models.Model): Course_Name = models.CharField(max_length=200, blank=True) student = models.ManyToManyField(add_students_by_manager, blank=True) def __str__(self): return self.Course_Name class add_students_by_manager(models.Model): manager_ID = models.ForeignKey(Manager_login_information, on_delete=models.CASCADE) student_ID = models.CharField(max_length=200) student_name = models.CharField(max_length=200) def __str__(self): return self.student_name views.py def assignment_page(request): if request.method == "POST": get_course_name = request.POST.get('get_course_name') stu_course_all_stu = add_courses.objects.filter(Course_Name=add_courses_get) for all_stu_details in stu_course_all_stu: for stu_details in all_stu_details.student.all(): print(stu_details.student_ID) # THIS PRINTS OUT ALL THE student_id context3 = {"stu_course_all_stu": stu_course_all_stu} return render(request, 'assignment_page.html', context3) else: return redirect('/') assignment_page.html {% for m in stu_details %} <div class="card mb-3 ml-5" style="max-width: 840px;"> <div class="row no-gutters"> <div class="col-md-4"> <img src="/media/uploads/student_user.png" class="rounded profile-pic mt-2 ml-5 mb-2" alt="user" height="120" width="140"> </div> <div class="col-md-8"> <div class="card-body"> <h5 class="card-title">Student ID : {{m.student_ID}}</h5> <h5 class="card-title">Student Name : {{m.student_name}}</h5> <form action="{% url 'stu_id_details' %}" method="POST">{% csrf_token %} <div class="form-group"> <input type="hidden" name="get_id_stu_details" value="{{m.student_ID}}" class="form-control" id="exampleInputPassword2"> </div> <button type="submit" class="btn btn-outline-success btn-sm">See Student Details</button> </form> </div> </div> </div> </div> {% endfor %} -
How to update the html table <td> by press button and get the info from python script
I want to make a website that gets data from the python code below, that when I press the button that will update each of HTML table -
Getting error while giving command-pip install virtualenvwrapper-win
ERROR: Exception: Traceback (most recent call last): File "C:\Users\Stc\AppData\Roaming\Python\Python38\site-packages\pip_internal\cli\base_command.py", line 186, in _main status = self.run(options, args) File "C:\Users\Stc\AppData\Roaming\Python\Python38\site-packages\pip_internal\commands\install.py", line 253, in run options.use_user_site = decide_user_install( File "C:\Users\Stc\AppData\Roaming\Python\Python38\site-packages\pip_internal\commands\install.py", line 604, in decide_user_install if site_packages_writable(root=root_path, isolated=isolated_mode): File "C:\Users\Stc\AppData\Roaming\Python\Python38\site-packages\pip_internal\commands\install.py", line 548, in site_packages_writable return all( File "C:\Users\Stc\AppData\Roaming\Python\Python38\site-packages\pip_internal\commands\install.py", line 549, in test_writable_dir(d) for d in set(get_lib_location_guesses(**kwargs)) File "C:\Users\Stc\AppData\Roaming\Python\Python38\site-packages\pip_internal\utils\filesystem.py", line 140, in test_writable_dir return _test_writable_dir_win(path) File "C:\Users\Stc\AppData\Roaming\Python\Python38\site-packages\pip_internal\utils\filesystem.py", line 153, in _test_writable_dir_win fd = os.open(file, os.O_RDWR | os.O_CREAT | os.O_EXCL) PermissionError: [Errno 13] Permission denied: 'c:\program files\python38\Lib\site-packages\accesstest_deleteme_fishfingers_custard_lvqv1z' -
django NoReverseMatch at /account/dashboard/1/
I have a problem when I want to visit the user dashboard. On each article there is a link to the user profile, however, when I click on the link I'm getting NoReverseMatch. I was doing troubleshoots for days but I'm not able to fix the problem. Any help on how to fix this error is more than welcome, thank you! article.html: <a href="{% url 'guest_user' pk=article.author.pk %}"><h6> {{ article.author.profile.username}}</h6></a> accounts>views: @login_required def guest_dashboard(request, pk): user_other = User.objects.get(pk = pk) already_followed = Follow.objects.filter(follower = request.user, following = user_other) if guest_dashboard == request.user: return HttpResponseRedirect(reverse('dashboard')) return render(request, 'account/dashboard-guest.html', context = {'user_other' : user_other, 'already_followed' : already_followed}) articles>View: def article_detail(request, pk): article = Article.objects.get(pk=pk) comment_form = CommentForm() already_liked = Likes.objects.filter(article=article, user=request.user) likesCounter = Likes.objects.filter(article=article).count() if already_liked: liked = True else: liked = False if request.method == 'POST': comment_form = CommentForm(request.POST) if comment_form.is_valid(): comment = comment_form.save(commit=False) comment.user = request.user comment.article = article comment.save() return HttpResponseRedirect(reverse('article_detail', kwargs={'pk':pk})) return render(request, 'article/single-article.html', context={'article':article, 'comment_form':comment_form, 'liked': liked,'likesCounter':likesCounter,'already_liked':already_liked}) article>URLs: path('<pk>', article_detail , name = 'article_detail'), account>URLs: path('account/dashboard/', dashboard, name = 'dashboard'), path('account/dashboard/<pk>/', guest_dashboard, name = 'guest_user'), -
Django Channels sleep
i have two group sends that i want to sleep between them, my code: await self.channel_layer.group_send( str(self.game_link), { "type": "group_message", "text": json.dumps(answer_data), } ) await asyncio.sleep(5) await self.channel_layer.group_send( str(self.game_link), { "type": "group_message", "text": json.dumps(data), } ) what ends up happening is that both send at the same time after sleep ends. how can i get around this? -
Is there any way to limit the choices displaying in autocomplete fields in Django admin based on the foreign key just selected in another field?
I encounter a problem when using the autocomplete fields in Django admin. #model.py class Party(models.Model): pass class Address(models.Model): party = models.ManyToManyField(Party,through='MailAddress') class MailAddress(models.Model): party = models.ForeignKey(Party,on_delete=models.CASCADE) address = models.ForeignKey(Address,on_delete=models.CASCADE) class Mail(models.Model): party = models.ForeignKey(Party,on_delete=models.CASCADE) mail_list = models.ForeignKey(MailAddress,on_delete=models.CASCADE) #admin.py class AddressInline(admin.TabularInline): model = Address.party.through class PartyAdmin(admin.ModelAdmin): inlines = [AddressInline] class MailAddressAdmin(admin.ModelAdmin): search_fields = ['address'] class MailAdmin(admin.ModelAdmin): autocomplete_fields = ['mail_list'] My question is whether I can make the autocomplete field display MailAddress field for the selected Party only? Thanks. -
How to return a form result set using MySQL in PhpMyAdmin to a Python Web Application
Apologies for the novice MySQL question, I need some guidance. I am working on a project with several Python/Django programmers building a web app. The web app uses MySQL database on the backend, and I access it using XAMPP and PhpMyAdmin. We need to create several reports for the web app, to be displayed in the web page and available to print. These reports are generally in table format. I wanted to develop a stored procedure to return a table resultset, based on the parameters entered in the developers forms, but I am hitting a wall finding resources on writing this out. Is this not possible? Can a MySQL stored procedure, or other function, return a table as a result set? Is there a way I could do this with a temp table or views instead? If not, then can anyone advise on an alternative to complete these reports, please. Thank you for any feedback you can provide on this topic, in advance! -
Django Advanced Tutorial: How to write reusable apps - cannot find /polls/index.html, polls/question_list.html, TemplateDoesNotExist:
I am new to Django and still a beginner at Python. The tutorial I'm following is here: https://docs.djangoproject.com/en/3.1/intro/reusable-apps/#installing-reusable-apps-prerequisites I am trying to follow the Django tutorials but it was not very clear where exactly I should be placing my /django-polls/ folder when removing /polls/ from /mysite/. I have looked at other similar questions here, but none of them solved the issue for me. I am able to run the python -m pip install --user django-polls/dist/django-polls-0.1.tar.gz line when I am inside of my directory right above /mysite/. Here is roughly what my current directory layout looks like: django-tutorial |- /django-polls | |- /dist | |- /... | |- /polls | |- /...#all relevant polls files from previous tutorials |- LICENSE |- MANIFEST.in |- setup.cfg |- setup.py |- /mysite | |- /mysite | |- /templates | |- manage.py My INSTALLED_APPS looks like this: INSTALLED_APPS = [ 'polls.apps.PollsConfig', # The path to the PollsConfig so it can be included 'django.contrib.admin', # The admin site. 'django.contrib.auth', # An authentication system. 'django.contrib.contenttypes', # A framework for content types. 'django.contrib.sessions', # A session framework 'django.contrib.messages', # A messaging framework 'django.contrib.staticfiles', # A framework for managing static files ] I also tried it with just 'polls', instead …