Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Defining a struct as a class attribute
I'm defining a class in a Django project and I want a class to have a specific structure. Versions used: Django2.2.3 python3.7 I thought about defining the struct as a class and then adding it as an attribute for the main class. But then I am afraid it will create a DB. This is what I tried: from django.db import models class Host(models.Model): id_host = models.CharField(max_length=20) [... more attributes here ...] class Apartment(models.Model): _id = models.CharField(max_length=20) host = Host() [... more attributes here ...] Any idea on how to do this correctly? -
How to modify a class attribute from within a method of this class?
I am just trying to modify output_list from the get function so that I can get the data in the post function. From now, the code is working but I'm repeating the same code in get and post which isn't ideal. class Questionnaire(TemplateView): template_name = 'blog/questionnaire.html' context = {'title': 'Questionnaire page'} output_list = [] def get(self, request): self.output_list = [] outputs = OutputOutcomeImpact.objects.filter(activity__activity_name=request.session['activity']) for output in outputs: if output.question: self.output_list.append([output.output_outcome_impact_name , output.question]) form_quest = QuestionnaireForm(None, extra=self.output_list) self.context['form_quest']=form_quest return render(request,self.template_name, self.context) def post(self,request): print(self.output_list) outputs = OutputOutcomeImpact.objects.filter(activity__activity_name=request.session['activity']) for output in outputs: if output.question: self.output_list.append([output.output_outcome_impact_name,output.question]) form_quest = QuestionnaireForm(request.POST, extra = self.output_list) if form_quest.is_valid(): request.session['outputs_values'] = [] for i in range(len(self.output_list)): request.session['outputs_values'].append([self.output_list[i][0],form_quest.cleaned_data[self.output_list[i][0]]]) return redirect('/about', self.context) I just want to pass output_list the way it is after passing through the get method so I don't repeat code. Thanks. -
how to send a copy of my car booking to admin via email
I am building a car booking system.I want the admin to get a copy of the car booking details whenever a user clicks save or deletes the booking using Django framework -
django rest framework How to delete redundant queries?
i use django debug_toolbar see SQL query ,I want to delete the second SQL query + 1.(SELECT ••• FROM auth_user LEFT OUTER JOIN accounts_userextension ON (auth_user.id = accounts_userextension.user_id) 50.86474349085549% 28.30 Sel Expl) + 2.(SELECT ••• FROM auth_user LIMIT 1000 49.13525650914451% 27.34 Sel Expl) class UserExtension(models.Model): ##models.py user = models.OneToOneField(User,on_delete=models.CASCADE,related_name='user_detail') birthday = models.DateField(null=True,blank=True) from django.contrib.auth.models import User ##serializers.py from .models import UserExtension class UserExtensionSerializer(serializers.ModelSerializer): class Meta: model = UserExtension fields = '__all__' class accountDetailSerializer(serializers.ModelSerializer): user_detail = UserExtensionSerializer() class Meta: model = User fields = [ "username", "email", "first_name", 'user_detail', ] class AccountView(generics.ListCreateAPIView): ##views.py queryset = User.objects.all().select_related('user_detail') serializer_class = accountDetai`enter code here`lSerializer permission_classes = () -
How am I supposed to use this in HTML?
I want to use {% is.user_authentificated %} to change a function display, but when I add this line, it shows it in the view ben I reload the page. Did I do something wrong in it ? {% if is.user_authentificated %} li><a ng-if="item.detail_url.indexOf('/layers/') > -1" href="{% endverbatim %}{% url "new_map" %}?layer={% verbatim %}{{ item.detail_url.substring(8) }}"> {% endverbatim %} <i class="fa fa-map-marker"></i>{% trans "Create a Map" %}</a> {% verbatim %} </li> {% endif %} -
In Django 1.6 - how to use a pre-existing database for unit tests? (--keepdb flag)
We are using Django 1.6.x for our codebase and there are no unit tests for the code. I want to begin to implement unit tests on the codebase and we have a Oracle database we can use for the task. On other codebases we maintain, I can use the --keepdb flag to prevent django from creating/tearing down the database. Apparently in earlier versions of Django this flag doesn't exist. Created a custom settings file but I cannot figure out how to prevent the modification of db tables I do not have permissions for. -
how to render multiple fusioncharts to single html page in django
I want to make a dashboard web app, so I need to use multiple fusion charts for same html page. I have tried making a dictionary but that only shows one chart and not the other one. please help me achieve this so that i an render 3-4 charts. or if it doesn't work this way let me know any alternative? views.py context={ 'all_count': all_count, 'total_high': total_high, 'total_medium': total_medium, 'total_low': total_low } status = FusionCharts('doughnut2d', 'ex1', '600', '400', 'chart-1', 'json', """{ "chart": { "showpercentvalues": "1", "aligncaptionwithcanvas": "0", "captionpadding": "0", "decimals": "1", "plottooltext": "<b>$percentValue</b> of offenses <b>$label</b>", "centerlabel": "# Users: $value", "theme": "fusion" }, "data": [ { "label": "Opened offense", "value": "1000" }, { "label": "Closed offense", "value": "5300" } ] }""") context2 = { 'monthly': monthly.render(), 'status': status.render() } # returning complete JavaScript and HTML code, which is used to generate chart in the browsers. return render(request, 'dashboard.html', {'context2': context2, 'context': context}) dashboard.html <div class="content"> <div class="container-fluid"> <div class="card"> <div id="chart-1">{{ context2.monthly|safe }}</div> </div> </div> </div> <div class="content"> <div class="container-fluid"> <div class="card"> <div class="section__content section__content--p30"> <div class="container-fluid"> <div class="row m-t-25"> <div class="col-sm-6 col-lg-3"> <div id="chart-2">{{ context2.status|safe }}</div> </div> </div> </div> </div> </div> </div> </div> -
with transaction.atomic() not working for Azure SQL Database
I use django-pyodbc-azure 2.1.0.0 for the connection with an Azure SQL database which works fine. When I understand the documentation of django-pyodbc-azure correctly, transactions should be supported. However, this code immediately updates the row. I would expect, that the row is updated after 20 seconds. from django.db import transaction from myapp.models import MyModel import time with transaction.atomic(): MyModel.objects.filter(id=1).update(my_field='Test') time.sleep(20) Am I doing something wrong? Do I need to specifiy certain settings on the Azure SQL database? -
Can't manage to display form from my view
I'm trying to create a page where admins can upload some files using some FileField. The problem is that I can't manage to display any field from my form, I must be missing something important but I can't find out what, hope anyone can help me. Here is the code related to this form: urls.py urlpatterns = patterns( '', url(r'^admin_fichiers_phyto/$', phyto_views.AdminFichiersPhyto.as_view(), name='phyto-admin-fichiers-phyto'), ) phyto_admin_fichiers.html {% block forms %} {% if user.is_staff%} <fieldset> <div> <span>{{ form.other }}</span> </div> </fieldset> <p> <input id="submit" class="btn btn-primary" type="submit" value="Synchronisation Autre" name="autre"/> <input id="submit" class="btn btn-primary" type="submit" value="Synchronisation Traitements généraux" name="trtm_gen"/> </p> {% endif %} {% endblock %} views.py class AdminFichiersPhyto(TemplateView): template_name = 'phyto/phyto_admin_fichiers.html' form_class = forms.PhytoFileForm current_url = 'phyto-files' context_object_name = 'phyto_files' def post(self, request, *args, **kwargs): if request.POST.get('autre'): return HttpResponse('<h1>autre</h1>') if request.POST.get('trtm_gen'): return HttpResponse('<h1>Traitement Generaux</h1>') forms.py class PhytoFileForm(forms.Form): class Meta: model = models.PhytoFile fields = ['general_treatment', 'other'] def __init__(self, *args, **kwargs): super(PhytoFileForm, self).__init__(*args, **kwargs) models.py class PhytoFile(models.Model): general_treatment = models.FileField(upload_to='fichiers_phyto/', blank=True, null=True) other = models.FileField(upload_to='fichiers_phyto/', blank=True, null=True) Here is what my webpage is showing : https://imgur.com/a/yH0be0K I can't understand why the Field isn't displayed, I really hope somebody have the knowledge to help me with my problem ! ^_^ Have a nice day … -
How to Show Subcategory under Specific Category in Django?
I have some issue with my code, the Same Subcategory is showing under all Category, if a category doesn't have sub category then that category is also showing subcategory, I want to show if a category has subcategory then it should be shown in dropdown otherwise it should be blank. Here is my views.py file def home(request): context = RequestContext(request) category_list = WebCategory.objects.order_by('-created_at')[:5 subcategory_list = WebSubCategory.objects.order_by('-created_a context_dict = {'webcat': category_list, 'websubcat':subcatego return render_to_response('home.html', context_dict, context) And here is my header.html file.. <ul class="nav nav-pills" id="mainNav"> {%if webcat %} {% for category in webcat %} <li class="dropdown dropdown-mega"> <a class="dropdown-item dropdown-toggle" href="JavaScript:void()"> {{category}} </a> <ul class="dropdown-menu"> {% if websubcat %} <li> <div class="dropdown-mega-content"> <div class="row"> {% for subcategory in websubcat.all %} <div class="col-lg-3"> <span class="dropdown-mega-sub-title">Elements 1</span> <ul class="dropdown-mega-sub-nav"> <li><a class="dropdown-item" href="{{subcategory.slug}}">{{subcategory.name}}</a></li> </ul> </div> {% endfor %} </div> </div> </li> {% else %} <p>No category Found</p> {% endif %} </ul> </li> {% endfor %} {% else %} <p>No Category Found</p> {% endif %} Please guide me how i can show specific subcategory (if a category have subcategory) under category, right now i am getting subcategory under all category. -
Is there a way I can get comments for only one specific article using Django rest framework?
I'm learning how to create APIs with Django Rest Framework. the issue I'm having is filtering only comments for one specific blog post lets say the url is like this http://127.0.0.1:8000/blog-posts/1/blog-comments/ I'm using ViewSets but I have no idea of how I can do it class BlogPostViewSet(ModelViewSet): """ Handles creating, updating, listing and deleting blog posts. """ serializer_class = BlogPostSerializer queryset = BlogPost.objects.all() @action(methods=['GET', 'POST'], url_name='blog_comments', url_path='blog-comments', detail=True) def get_comments(self, request, pk=None): blog_post = self.get_object() comments = Comment.objects.filter(blog_post=blog_post) return JsonResponse(comments) class CommentViewSet(ModelViewSet): """ Handles creating, updating, listing and deleting comments on blog posts. """ serializer_class = CommentSerializer queryset = Comment.objects.all() When I visist the url ````http://127.0.0.1:8000/blog-posts/1/blog-comments/I'm getting a not found error but whenever I got to thishttp://127.0.0.1:8000/blog-posts/blog-comments/I get{ "detail":"Not found" }``` -
How to serialize models with multiple foreign keys?
I want to serialize data in the format given below.I'm new to django-rest framework.I am working in a varsity project.So, little help will be appreciated. { { "Series_name":"something", "Home_team":"anything", "Away_team":"sbh", "players":[ { "id":"1", ... } { "id":"2", ... } ] }, { "Series_name":"something2", "Home_team":"anything", "Away_team":"sbh", "players":[ { "id":"1", ... } { "id":"1", ... } ] } } I have tried this.But this doesn't give satisfactory result.In fact it returns empty set. class PlayersSerializer2(serializers.ModelSerializer): class Meta: model = Players fields = ['name', 'country', 'image', 'role', 'credit'] class SeriesListSerializer2(serializers.ModelSerializer): class Meta: model = SeriesList fields = '__all__' class SeriesSquadsSerializer(serializers.ModelSerializer): players = PlayersSerializer2(many=True, read_only=True) series = SeriesListSerializer2(many=True, read_only=True) class Meta: model = SeriesSquads fields = ['series', 'players'] these are the models I'm working with.I've 3 models SeriesList,Series_Squads and Players.Series_sqauds has unique pairs (Series_name,Players).It has two foreign keys pointing objects of SeriesList and Players. class SeriesList(models.Model): Series_name = models.CharField(max_length=250, unique=True,primary_key=True) No_of_matches = models.IntegerField() Home_team = models.CharField(max_length=250) Away_team = models.CharField(max_length=250) class SeriesSquads(models.Model): Series_name = models.ForeignKey(SeriesList, on_delete=models.CASCADE) Squad_player = models.ForeignKey(Players, on_delete=models.CASCADE) class Players(models.Model): name = models.CharField(default="", max_length=250) country = models.CharField(max_length=250) image = models.CharField(max_length=500) role = models.CharField(max_length=30) credit = models.FloatField(default=None) -
Turn off trimming of whitespace in Django
I have a charfield in a django model: sheet = models.CharField(max_length=256, blank=True, null=True) I am using the default sqlite database. When I add a new object that has trailing whitespace at the end of this field, Django automatically trims the string. Is there a way to avoid this behaviour? -
ImportError: cannot import name 'gen_filenames'
I am upgrading a django cookiecutter project from django version 2.0.7 to version 2.2.3. I am getting ImportError: cannot import name 'gen_filenames' I can't find anything online for this problem. Can anyone help me out? Highly appreciated! Thanks in advance -
Objects and attribute errors on browser, after server runs
I'm new to Django and I'm working on an app that display the objects of a primary key. The server runs fine but I get an error on the browser that says: 'master_courses' objects has no attribute 'masterCourses_slug' The code looks like this: from django.shortcuts import render, redirect from .models import master_courses, course_category, course_series def single_slug(requests, single_slug): categories = [c.course_slug for c in course_category.objects.all()] if single_slug in categories: matching_series = course_series.objects.filter(course_category__course_slug=single_slug) series_urls = {} for ms in matching_series.all(): part_one = master_courses.objects.filter(course_series__course_series=ms.course_series).earliest("date_added") series_urls[ms] = part_one return render(request, "main/category.html", {"the_series": series_urls}) masterCourses = [ m.masterCourses_slug for m in master_courses.objects.all()] if single_slug in masterCourses: return HttpResponse(f"{single_slug} is a single slug.") The error points to the code below (which is on the last line of the code above: masterCourses = [ m.masterCourses_slug for m in master_courses.objects.all()] if single_slug in masterCourses: return HttpResponse(f"{single_slug} is a single slug.") The error isn't on the code section, but on the browser. Any suggestions on how I could Sol this please. -
Redirect to current page after editing a record
I'm listing 100 of records using a pagination in django. Each page contains 10 records. Suppose i'm on page 6 and selected a record to edit . After editing the record, successful url to redirect list view(which is first page). I need to stay the page where i pick the record to edit. i tried using the {{ request.get_full_path }} which will show the current url. But i cant pass it to edit url, if i passed it will show in the url. I'm using Class Based View. def form_valid(self, form): self.object = form.save(commit=False) now = datetime.now() self.object.updator = self.request.user.username self.object.date_updated = now self.object.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER')) Suppose my on 6th page, a picked a record to edit. After editing the record i need redirect back to 6th page. Please suggest me a way to achieve this. -
How to limit paging in Django admin without changing the results number
I have a Django admin page and i wish to limit the number of pages without changing the number of objects in ChangeList. E.g. I have ChangeList with 1000 results, limit 20 results per page.and i wish to limit paging offset to 10 pages but still present i have 1000 results. So the user will be able to see the count but won't be able to "jump" to the "far" offset. -
best way to restrict update on field
I have a model class MyModel(models.Model): name = models.CharField(max_length=100, blank=False, null=False, unique=True) content = models.TextField(blank=True, null=True) I want to let user create MyModel with name parameters I am using ModelViewset. I want to avoid updating name on PUT request. But model serializer raises required error as blank=False in Model. I face this problem commonly. Yes I can override and update and create and write new serializers. Is there any other way to do it? -
How to run command inspectdb from python code
In my project I need to create a schmea python file. Now I know that I can do that with the following line of code in the command line: python manage.py inspectdb --database=blah > you_app/models.py Now I need to add a shema in my python code. The problem is i cant stop the server and start a script. I need run that command from my python file. Here is my current def and my first try: def trigger_after_extract(request): # inspectdb print(request.GET.get('project')) name = request.GET.get('project') # conn = name.connect(connect='postgres', user='postgres', password='g7mN5da1e2') # connection.ensure_connection(); test = connect_to_db(name) command = 'python manage.py inspectdb --database ' + name + ' > api_manager/schemas/' + name + '.py' os.system(command) # append to __init__.py in project.schemas # with open(--path--, 'a+') as file: # file.write(--thing-- + "\n") # pass return JsonResponse({'json': test, 'oldJson': 'RESULT'}) -
On The Fly Validating and Manipulating Dictionary by Django-Rest Serializer (NO MODEL)
I have some data (dict) and I want to validate its data structure at the first and ensure about validation, after that I want to change fields name (CamelCase to snake_case), that's all it! I had lots of searches and I know about re_presentation method (it seems it calls only when using ModelSerializer as a parent class) and also read about ListSerializer. Any helps will be appreciated :) -
Create an undo button in my crud operations
So I've created a simple crud operation, but the only difference is that when you delete data entered the deleted data gets deleted from the original data list but gets saved in a separate table which is in a different URL. Now I need to create an undo function where the user has done a mistake of deleting the content and in order to retain the content he can go to the deleted table URL and click undo. from django.shortcuts import render, redirect from employee.forms import EmployeeForm from .models import * # Create your views here. def emp(request): if request.method == "POST": form = EmployeeForm(request.POST) if form.is_valid(): try: form.save() return redirect('/show') except: pass else: form = EmployeeForm() return render(request,'index.html',{'form':form}) def show(request): employees = Employee.objects.all() return render(request,"show.html",{'employees':employees}) def edit(request, id): employee = Employee.objects.get(id=id) return render(request,'edit.html', {'employee':employee}) def update(request, id): employee = Employee.objects.get(id=id) form = EmployeeForm(request.POST, instance = employee) if form.is_valid(): form.save() return redirect("/show") return render(request, 'edit.html', {'employee': employee}) ''' def destroy1(request,id): i= Employee.objects.get(id=id) if request.method==='POST': if POST.objects.filter(ename=request.POST['ename']) and POST.objects.filter(eid=request.POST['eemail']) and POST.objects.filter(econtact=request.POST['econtact']): print(employee.ename,employee.eemail,employee.econtact) i.deleted=True i.save() return redirect("/show") else: print("Nothing here") return HttpResponse("Nothing") else: retrun redirect('/show/') ''' def destroy(request,id): employee= Employee.objects.get(id=id) x=Deleted() x.eid= employee.eid x.ename=employee.ename x.eemail=employee.eemail x.econtact=employee.econtact x.save() employee.delete() return redirect ('/show') def … -
Convert query MySQL to query Django
I have a query in MySQL SELECT COUNT(app_warnings.id) AS num_warning, MONTH(app_warnings.date_created) AS month FROM app_warnings WHERE app_warnings.date_created BETWEEN '2019-04-01' AND '2019-07-31' GROUP BY month I wish I could convert to query in Django -
directly able to access the page which is after login
in respect to my previous Question, i modified my code and added the decorators and modified urls.py but the error i m encountering are:- A) The error provide valid credential is appearing on the login page even if the user does't enters anything (like some static text) B) I m able to access the localhost/Automation page directly using the url (without authentication needed) even though i added @login_required decorator. In views.py #some more imported stuff from django.urls import reverse import csv from django.contrib.auth import authenticate,login,logout from django.contrib.auth.decorators import login_required # Create your views here. def login_view(request): context = {} if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user: login(request, user) return HttpResponseRedirect(reverse('IP form')) else: context["error"] = "Provide valid credentials" #this message is displayed as it is. return render (request,"first_app/login.html", context) else: return render (request,"first_app/login.html", context) @login_required def user_logout(request): if request.method == "POST": logout(request) return HttpResponseRedirect(reverse('login')) @login_required def form_name_view(request): if request.method == "POST": #Automation page view #even without login i m able to access it using url only and i want to restrict that login.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Login</title> </head> <body> <h1> Please Login</h1> <form method="POST" action="{% url 'login' … -
Django list comapre in views
I have two models from different apps. I'm fetching one field of each of the models which is fetched as a list. I am converting the said lists elements into string through a for loop. My question is how do I compare these two strings with this method. That the element from model B are to be compared with model A elements, something like this. model A element 1 value : '923' model A element 2 value : '9253' model B element 1 value : '9256' model B element 2 value : '92356' if the last character of the string of element B 1 is matched the save the result somewhere if it's not move to the next character and so on. def LCR(request): template = "LCR\LCR.html" dest = Destination.objects.values_list('dest_num', flat=True) ven = RateFile.objects.values_list('ven_des_num', flat=True) for i in dest: str(i) print i for x in ven: str(x) print x context = {"dest":dest,"ven":ven} return render(request, template,context) -
QuerySet object has no attritube
I got a problem when I select the distinct value from DB. Here is my model => class Shift(models.Model): shiftid = models.CharField(max_length=15) shiftdesc = models.CharField(blank = False, null= False, max_length=20) dayname = models.CharField(blank = False, null= False, max_length=20) class Meta: unique_together = ('shiftid','dayname') Data structure will be like that=> shiftid shiftdesc dayname shift1 desc1 1 shift1 desc2 1 shift1 desc1 1 My requirement => shiftid shiftdesc dayname shift1 desc1 1 shift1 desc2 1 I am trying to select the records like that => @action(methods=['get'], detail=False) def shiftsum(self, request): newest = self.get_queryset().order_by('shiftid','dayname').values('shiftid','dayname').distinct() serializer = self.get_serializer_class()(newest) return Response(serializer.data) When I try like that I always got this "'QuerySet' object has no attribute 'shiftid' and May I know how to select the distinct value?