Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
For ocr scanner based web app does flask is useful in python?
i am university student and new on python. i have to submit my final year project base on web app in which you can scan image and convert it into digital text. Also some other features i want to add like Conversion of text into handwritten format Conversion of mp3 file into text form Handwritten text into digital form Conversion of digital text into and other language I want to ask that which framework i need to learn after python to make web app like this and can flask will be useful for me? -
Statistic in template show CombinedExpression for one field
I have problem with template render. It shows statistic table for Document model (counts of views, downloads, likes, dislikes), but view_count in final html is not a number, it's an CombinedExpression object like F(view_count) + Value(1). Perhaps the reason for my problem is that I am updating a statistic and adding it to the template in the same part of the code. # views.py class DocumentDetailView(DetailView): ... def get(self, request, *args, **kwargs): self.object = self.get_object() self.statistic = FileStatistic.objects.get(document=self.object) self.statistic.increment_field('view_count') context = self.get_context_data(object=self.object, statistic=self.statistic) return self.render_to_response(context) # models.py # NOTE: this model class is OneToOneField referenced in Document model class. class FileStatistic(models.Model): download_count = models.IntegerField( default=0, verbose_name='Количество скачиваний' ) view_count = models.IntegerField( default=0, verbose_name='Количество просмотров' ) like_count = models.IntegerField( default=0, verbose_name='Количество лайков' ) dislike_count = models.IntegerField( default=0, verbose_name='Количество дизлайков' ) def increment_field(self, field_name: str) -> None: setattr(self, field_name, models.F(field_name) + 1) self.save(update_fields=[field_name]) <table class="table table-borderless table-sm"> <thread> <tr> <th class="text-center" scope='col'>Число скачиваний</th> <th class="text-center" scope='col'>Число просмотров</th> <th class="text-center" score='col'>Число лайков</th> <th class="text-center" score='col'>Число дизлайков</th> </tr> </thread> <tbody> <tr> <td class="text-center border-top">{{statistic.download_count}}</td> <td class="text-center border-top">{{statistic.view_count}}</td> <td class="text-center border-top">{{statistic.like_count}}</td> <td class="text-center border-top">{{statistic.dislike_count}}</td> </tr> </tbody> </table> Output: -
How to register as an admin in Django app using Registration Model and Views.py?
I am familiar with creating a superuser in a Django App using python manage.py createsuperuser command in terminal. I am also familiar with creating a superuser using Python Shell. But I want to know that how do we register a user as an admin in a Django App using RegistrationModel and views.py? Or more specifically, how to register the user and change it's status to staff or superuser in views.py? -
Docker python:alpine image can not install backports.zoneinfo using pip
I was trying to dockerize an django app. My requirements.txt had backports.zoneinfo. But when ever I try to install this packages docker is showing error. I tried the same in regular image (not alpine or slim) then it was working fine. I have tried upgrading pip, tzdata, wheel, gcc. But no luck. -
django download view downloading only .xls instead of file with extension on model
I have my django view where i upload the file from admin and users download it on front end when i downlaod the file on the frontend the download is extension with only .xls i.e when i upload the file with .xlsx extension it is still down;load ing with .xls instead the file should be downloaded according to the extension either its xls or xlsx. views.py class myAPIView(APIView): def get(self, request): data = Model.objects.first() return HttpResponse( data.file, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel', ) -
Regex patter to capture all variables in url including forward slash
I want to match dynamic created urls which can have multiple endpoints. Need some regex pattern for this. For ex. http://127.0.0.1:8000/api/:user_id/:endpointa/:endpoint1/ http://127.0.0.1:8000/api/:user_id/:endpointb/:endpoint2/:endpoint3/:endpoint4 http://127.0.0.1:8000/api/:user_id/:endpointc/:endpoint2/ http://127.0.0.1:8000/api/:user_id/:endpointd/:endpoint1/:endpoint2/ so till BASE_URL/api/:user_id/ is common. I am able to catch user_id but want to catch other params after user_id on single string variable. after that there can be any number of endpoints and I want to catch them all in one single string variable. like for first url string variable catched will be "endpointa/endpoint1/" and for next url string variable will be "endpointb/endpoint2/endpoint3/endpoint4" along with fwd slashes. What regex pattern should I write in urls.py for capturing this variables? I tried with re_path(r'(?P<user_id>[-\w]+)/(?P<customUrl>(.*?)(?:\/)?$)/.*', customLink, name='customLink'), but couldn't get it work. -
Ajax post request is printing json response on empty html page instead of html signup page
I am making a website in django with ajax.I have created a base html file django template and two other html templates named signup.html and home.html. I have written code to make ajax request with signup form in base.html file like this. $("#signupBtn").click(function() { event.preventDefault(); username=$('#id_username').val(); password1=$('#id_password1').val(); password2=$('#id_password2').val(); data={username=username,password1=password1,password2=password2} $.ajax({ type:'POST', url:'{% url "signup" %}', data:data, success:function(response){ // $('#msg').html(`<p style="font-size: 30px;color: lime;font-weight: bold;">User created succcess!</p>`); console.log('FORM SUCCESS!') window.location='{% url "home" %}' }, error:function(){ } }) }); and my signup views is like this: class signup(View): def post(self,request): fm=UserCreationForm(request.POST) if fm.is_valid(): fm.save() return JsonResponse({'status':1}) fm=UserCreationForm() return JsonResponse({'status':0}) def get(self,request): fm=UserCreationForm() return render(request,"home/signup.html",{"form":fm}) Main problem is this ,when there goes Get request form is showing and we can enter all details to create account and also account created successfully in admin panel,But in post request,after saving the form ,i get json response printed on blank page instead of getting again that signup page. How this is possible to return to the same page after post request is made? THIS IS PROBLEM: please check the problem as show in image -
Regarding Backend Framework
Hello guys I need a small piece of advice from you like I have completed django and flask and I have industrial experience on them now I am willing to learn a new backend language but I am confused in between go-lang,node.js,ruby on rails.First I thought to learn go lang bcz its very fast but when I researched about it there are negligible job opportunities for junior go lang developers so I am confused can you tell me what to do -
DJango Login Issue with incoorect credentials
If I try to enter wrong username and password it shows an tuple error, not my message def login(request): if request.method == 'POST' : username=request.POST['username'] password=request.POST['password'] user=auth.authenticate(username=username,password=password) if user is not None: auth.login(request,user), return redirect('/') else: messages.info(request,"invalid username or password"), return redirect('login'), return render(request,"login.html") enter image description here -
Django Classbased views with condition
I created script in function based view in django and I want to convert it into classbased views with if/else condition. I done searching but I didn't found the solutions. Sorry for a basic question, Im new in django and start learning. This is my function script that I want to convert in Classbased views. def vm_create(request): if request.method == 'POST': Number = request.POST.get('number') Date = request.POST.get('date') if Date == '': Date = None else: Date = datetime.datetime.strptime(or_date,'%Y-%m-%d') month = '' endnum = '' if Number != '': endnum = int(Number[-1]) if endnum == 1: month = 'January' elif endnum == 2: month = 'Febuary' save = Models(CS_Number=Number, CS_Date=Date, CS_Month=month) I tried to convert to classbased but return is not working. class vm_create(CreateView): model = models form_class = forms template_name = 'cs_form.html' def create_new(self, request, *args, **kwargs): endnum = '' if request.GET.get('Number') != '': endnum = int(Number[-1]) if endnum == 1: return 'January' elif endnum == 2: return 'Febuary' return super().create_new(request, *args, **kwargs) -
Does PasswordResetConfirmView.py auto populate uid and token?
The view definitely does not populate on my end but password_reset_confirm.html in the demo template folder seems to do that. password_reset_confirm_form.html Any help appreciated. url.py path("dj-rest-auth/password/reset/confirm/<str:uid>/<str:token>/", # TemplateView.as_view(template_name="password_reset_confirm.html"), PasswordResetConfirmView.as_view(), name='resend-email-verification' ), edit: maybe this webpage here is not the same page in dj-rest-auth demo folder... -
D3js Get the name of the data when it hovers
I'm working on an interactive graph project in django using d3js. I'm trying to create a scatter graph in d3js that displays a tooltip when the cursor hovers over a data node. However, I don't know how to get the name that corresponds to the pre-defined data when the cursor hovers over it. The scatter data I'm using is x : scatter x-coordinate y : scatter y-coordinate name : a unique name for the data I want to get the value of this name key during this hover. How can I reference the value of the original data corresponding to the data node with the key etc.? Thank you. My code is as follows. <div id="dc-graph"></div> // data from python (django) var graph_data = JSON.parse('{{ graph|safe }}'); var num = graph_data.num; var width = graph_data.width; var height = graph_data.height; var margin = graph_data.margin; var svgWidth = width + margin.left + margin.right; var svgHeight = height + margin.top + margin.bottom; var data = []; for (let i = 0; i < num; i++){ const adata = {x: graph_data.x[i], y: graph_data.y[i], name: graph_data.name[i]}; data.push(adata); } // svg var svg = d3.select("#dc-graph") .append("svg") .attr("class", "dc-graph-svg") .attr('width', svgWidth) .attr('height', svgHeight); // tooptip var tooltip … -
Update and create existing data in Django
I need to update and, if needed, create elements in a Django update view. Basically, I have a form where I am giving the user the chance of updating a row or inserting one or more new rows. The problem is that I am having issues in updating the "old" rows. If I update an existing row, it creates a new one. Here I post some code: views.py def edit_flight_mission(request, pk): mission = Mission.objects.get(id=pk) form = EditMissionForm(request.POST or None, instance=mission) learning_objectives = LearningObjective.objects.filter(mission_id=mission) context = { 'mission': mission, 'form': form, 'learning_objectives': learning_objectives, } if request.method == 'POST': learning_obj = request.POST.getlist('learning_obj') solo_flight = request.POST.get('solo_flight') if form.is_valid(): mission_obj = form.save() if solo_flight == 'solo_flight': mission_obj.solo_flight = True mission_obj.save() for lo in learning_obj: learning_objective, created = LearningObjective.objects.get_or_create(name=lo, mission_id=mission.id) if not created: learning_objective.name = lo learning_objective.save() return render(request, 'user/edit_flight_mission.html', context) models.py class Mission(models.Model): name = models.CharField(max_length=200) duration_dual = models.DurationField(blank=True, null=True) duration_solo = models.DurationField(blank=True, null=True) training_course = models.ForeignKey( TrainingCourse, on_delete=models.CASCADE) note = models.TextField(null=True, blank=True) solo_flight = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class LearningObjective(models.Model): name = models.CharField(max_length=300) mission = models.ForeignKey(Mission, on_delete=models.CASCADE, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) forms.py class EditMissionForm(forms.ModelForm): class Meta: model = Mission fields = ('name', 'duration_dual', 'duration_solo', 'training_course') widgets … -
Tags are not being stored in the database even after saving form in django
views.py def post(request): if request.method == 'POST': form = PostModelForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.user = request.user post.save() # using the for loop i am able to save the tags data. # for tag in form.cleaned_data['tags']: # post.tags.add(tag) images = request.FILES.getlist('images') for image in images: ImagesPostModel.objects.create(post=post, images=image) return redirect('/Blog/home/') else: form = PostModelForm(request.POST) return render(request, 'post.html', {'form': form}) models.py class PostModel(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date_time = models.DateTimeField(auto_now_add=True) title = models.TextField(null=True) body = models.TextField(null=True) tags = TaggableManager() def __str__(self): return str(self.user) post.html {% extends 'base.html' %} {% block content %} <form action="{% url 'post' %}" enctype="multipart/form-data" method="POST"> {% csrf_token %} {{ form.as_p }} <input type="file" multiple name="images"> <input type="submit"> </form> {% endblock %} After giving the input the data is stored in the tags field but, not saving in the database. I can manually insert data through the admin panel successfully but not as a non-staff user. I have installed taggit and placed it in the installed_apps in settings.py. Tags are being saved using post.tags.add(tag) inside for loop. What is the issue with the code? -
Found another file with the destination path 'admin'
I am trying to deploy the app on Heroku but when I run the following command: "python manage.py collectstatic" it returns multiple "Found another file with the destination path 'admin...". When I "git push heroku" the app, I can see the same error. Next, the application works, but /admin page doesn't have any format, like it is not reading css, font, etc. I've checked staticfiles/admin and it has its css,font,img and js folder with files. I've tried all the advices given here, but I'm not finding a solution. Here my settings: import os import django_heroku # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) . . . # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') #Heroku #STATIC_ROOT = os.path.join(BASE_DIR, 'static') #ok for IBM Cloud STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(STATIC_ROOT, 'media') # if I comment this line and MEDIA_URL = '/media/' # this line, /admin page has correct css but I don't have images in the application # Extra places for collectstatic to find static files.(extra heroku) STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) #django_heroku.settings(locals()) #if uncommented, application doesn't work And what I get when "git push heroku master" is: remote: Found another … -
write custom functions inside generic class based view in django rest framework
I have to write a custom function inside class based view which is like below: class ExampleView(ListCreateAPIView, UpdateAPIView, DestroyAPIView): queryset = Example.objects.all() serializer_class = ExampleSerializer def get(self, request, *args, **kwargs): /.........some code............./ def random_custom(self, request, *args, **kwargs): /.........some code............./ Here above I have a random custom function which I need to call from the url. Now I am not sure how to do that. If it was a modelviewset, we can do it easily like this: path("example/",users.ExampleView.as_view({"get": "random_custom"}), ), I have done it before in ModelVIewset,ie call custom functions like above but I am not sure how to do that is genericviews like above. -
How to convert JSON data in to python instance and save Django models multiple table with foreginkey (database sqllite)
*I am not able to save with id_category = models.ForeignKey please help me to solve ValueError: Cannot assign "21": "Categories.parent" must be a "Parents" instance. * View.py def GetProducts(request): endpoint = "[https://myurl.net/products/][1]" response = requests.request("GET", endpoint) data = json.loads(response.text) for cat in data['Category']: › pro_cat = ProCatData( id=cat['id'], name=cat['name'], image=cat['image'], ) pro_cat.save() for product in data['Products']: Products = ProductsData( id=product['id'], name=product['name'], id_category=product['id_category'], description=product['description'], image=product['image'], ) Products.save() model.py class ProCatData(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=30, null=True, blank=True) image = models.CharField(max_length=30) def __str__(self): return self.name class ProductsData(models.Model): id_category = models.ForeignKey(ProCatData, on_delete=models.DO_NOTHING,null=True, blank=True) image = models.CharField(max_length=300, null=True, blank=True) id = models.IntegerField(primary_key=True) name = models.CharField(max_length=30, null=True, blank -
Access Certain Data in html page from cursor.execute used in views django
I have used this method in my views.py to access the certain kind of data from table in database def report(request): cursor = connection.cursor() cursor.execute('''Select active, count(name) as count from s_transaction group by active ''') report_list = cursor.fetchall() return render (request, 'report.html',{'report_list': report_list}) I'm using this for loop to get the entire data <tbody> {% for transaction in report_list %} <tr> <td>{{transaction.0}}</td> <td>{{transaction.1}}</td> </tr> {% endfor %} </tbody> and i'm getting the result like this active count yes 85 no 67 but i want to get the count no.s separately for different purpose in html, how do I get the no. 85 and 67 from count separately? -
Store DateTimeField without timezone
In settings.py of my Django project I have: TIME_ZONE = 'UTC' USE_TZ = False And I have set the timezone of my Postgresql database to 'UTC' too. However these two model fields are still stored with timezone (+330) in the database: created_on = models.DateTimeField(auto_now_add=True) expires_on = models.DateTimeField() What else I was supposed to do to have them both stored in UTC? -
while html to pdf converting with pisa hindi words are in coded way
while converting Hindi words in HTML to pdf by using the xhtml2pdf library in Django projects I am getting some coded words on how to convert in the correct way? def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result, encoding='UTF-8') if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None -
How can i get many to many relationship table data in django?
This is my models.py from django.db import models class Course(models.Model): Credits = ( ('1', '0.75'), ('2', '1'), ('3', '2'), ('4', '3'), ('5', '4'), ('6', '5'), ('7', '6'), ) course_code = models.CharField(max_length=20, default="CSE-101", unique=True) course_name = models.CharField(max_length=50, default="C Language", unique=True) course_credit = models.CharField(max_length=1, choices=Credits, default='4') def __str__(self): return self.course_code class Student(models.Model): std_name = models.CharField(max_length=40) std_id = models.CharField(max_length=50, primary_key=True) std_email = models.EmailField(max_length=50, unique=True, blank=True) course = models.ManyToManyField(Course) def __str__(self): return self.std_id when i input data in Student table, database create a table student_course, i want to get this student_course data. How can i get this data and show this data in webpage? I'm a noob to python and Django so any help would be greatly appreciated. -
FieldError at /category_list
I am facing this probelm in my e-commerce project when i try to pagination Cannot resolve keyword '' into field. Choices are: created_at, description, id, is_active, subcategories, thumbnail, title, url_slug views.py file ''' # CATEGORIES class CategoriesListView(ListView): model = Categories template_name = "admin_local/category_list.html" paginate_by = 3 def get_queryset(self): filter_val = self.request.GET.get("filter", "")`enter code here` order_by = self.request.GET.get("orderby", "id") if filter_val != "": cat = Categories.objects.filter( Q(title__contains=filter_val) | Q(description__contains=filter_val)).order_by(order_by) else: cat = Categories.objects.all().order_by(order_by) return cat def get_context_data(self, **kwargs): context = super(CategoriesListView, self).get_context_data(**kwargs) context["filter"] = self.request.GET.get("filter", "") context["orderby"] = self.request.GET.get("orderby", "") context["all_table_fields"] = Categories._meta.get_fields() return context ''' I am facing this probelm in my e-commerce project when i try to pagination This Is html file ''' <div class="row"> <div class="col-lg-12"> <div class="card"> <div class="card-body"> <nav aria-label="Page navigation example"> <ul class="pagination"> {% if page_obj.has_previous %} <li class="page-item"><a class="page-link" href="{% url 'category_list' %}?filter={{ filter }}&orderby={{ orderby }}&page={{ page_obj.previous_page_number }} ">Previous</a> </li> {% else %} <li class="page-item disabled"><a class="page-link" href="#">Previous</a> </li> {% endif %} <li class="page-item"><a class="page-link" href="#">1</a></li> <li class="page-item"><a class="page-link" href="#">2</a></li> <li class="page-item"><a class="page-link" href="#">3</a></li> {% if page_obj.has_next %} <li class="page-item"><a class="page-link" href="{% url 'category_list' %}?filter={{ filter }}&orderby={{ orderby }}&page={{ page_obj.next_page_number }} ">Next</a> </li> {% else %} <li class="page-item disabled"><a class="page-link" href="#">Previous</a> </li> {% … -
React On Click Prevent Download but show excel
I have a link from microsoft one drive which is generated when we upload file pythonically. I have linked this link to a button whichis supposed to show the file but not download however on click it is donloading the file so i neeed help regarding how to prevent download but show the excel file linked. Below is react code I have been using function Files(props){ let getFileOnClick=(fileAddress)=>{ window.location.href=fileAddress } return( <button style={{float:'right'}} onClick = {()=>getFileOnClick(props.link)} className="btn btn-primary"> Get File </button> ) } -
Retrieve field values to Django Admin using many to many relationships
I have a simple task: I need to expose player name related to Game in game list (Django Admin). Game object has ManyToMany relationship with Player object via 'players' attribute. The problem is that now I have empty 'players_list' field (empty list means I don't know what to do and just leave it here[enter image description here][1]), though I tried Player.objects.all() and obviously got all players even those who are not bound to particular game. I feel it has simple solution but my brain refuses to work after 55 opened tabs. Thanks in advance! This is my models.py from django.db import model class Player(models.Model): name = models.CharField(max_length=54, default="") email = models.EmailField(max_length=54) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Game(models.Model): name = models.CharField(max_length=254, default="") players = models.ManyToManyField(Player, blank=True, related_name='player_games') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) players_list = [] def __str__(self): return self.name and admin.py from django.contrib import admin from .models import Game, Player class PlayerInline(admin.TabularInline): model = Game.players.through @admin.register(Player) class Admin(admin.ModelAdmin): search_fields = ['name', 'email'] list_display = ('name', 'email', 'created_at', 'updated_at') inlines = [ PlayerInline, ] @admin.register(Game) class AdminAdmin(admin.ModelAdmin): list_display = ('name', 'created_at', 'updated_at', 'players_list') inlines = [ PlayerInline, ] exclude = ('players',) Pic as it looks … -
Trying startapp in Django and i get core exception update sqlite3
When starting project in Django no sqlite3 file created. Trying startapp i get core exception update sqlite3 later version required. How update?