Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django custom dynamic form issue
I am trying to build a form that consists of dynamic adding of lesson availability to the form, the lesson availability has the foreign key of the lesson and the form for lesson availability is generated dynamically using JavaScript The problem is the model contains static values like: ''' lesson_virtual_id = models.Charfield(max_length = 100) ''' And the output of the forms comes like this: ''' lesson_virtual_id1': ['123456'], 'lesson_password1': ['password'], 'lesson_language1': [''], 'lesson_virtual_id2': ['123456'], 'lesson_password2': ['password'], 'lesson_language2': [''], ''' The dynamic html form in javascript file looks like this: ''' <div class="row accordion add-collapsed avail-${acount} " id="faq"> <div class="col-12 row card"> <div class="ml-3 d-flex"> <div class="col-sm-11 card-header" id="aqhead${acount}"> <a href="#" id="demo${acount}" class="btn btn-header-link collapsed" data-toggle="collapse" data-target="#faq${acount}" aria-controls="faq${acount}" >Lesson at</a> </div> <span class="col-sm-1 m-3"> <i style="color:#f10909;" class="fas fa-trash-alt" onclick="delete_collapsed(${acount});"></i> </span> </div> <div id="faq${acount}" class="col-sm-11 collapse hide" aria-labelledby="faqhead${acount}" data-parent="#faq"> <div class="card-body"> <div class="form-group"> <label>Lesson Type</label> <div class="col-12 d-flex"> <div class="form-check form-check-inline col-6"> <input class="form-check-input lesson_type${acount}" type="radio" name="lesson_type_radio${acount}" id="inlineRadio_${acount}" value="Live Virtual" onclick="lesson_type(${acount});"> <label class="form-check-label" for="inlineRadio_${acount}">Live Virtual</label></div> <div class="form-check form-check-inline col-6"> <input class="form-check-input lesson_type${acount}" type="radio" name="lesson_type_radio${acount}" id="inlineRadio2_${acount}" value="In-Person" onclick="lesson_type(${acount});"> <label class="form-check-label" for="inlineRadio2_${acount}">In-Person</label></div> </div> </div> <div class="form-group"> <input type="hidden" class="form-control lesson_text${acount}" name="lesson_text[]" id="lesson_text${acount}" readonly></div> <div class="form-group venue${acount}" style="display:none;"> <label>Lesson Venue</label> <div class="col-12 d-flex"> <div class="form-check form-check-inline … -
Django Changes in env lib site-packages don't apply
I meet a problem with a package : django-ckeditor. I have installed it with pip in my venv. And now I want to add just 1 or 2 modifications in the views file of ckeditor. The problem is : anything I write in this file: env\Lib\site-packages\ckeditor_uploader\views.py is not applying when I restart server. Look class ImageUploadView(generic.View): http_method_names = ["post"] def post(self, request, **kwargs): print("hello") I never get anything when I do this post request. Actually whatever I write (I removed all the lines and add 'azerrty' in my code) the server will run correctly... Does someone know why changes in my venv are not considered ? And how to solve this ? I tried to deactivate the venv and activate it again it didn't change anything -
django filters with pagination: showing same page after pressing next url
When i search for something(like tom), it works well for first page. But if I click next page url, it shows the same result, nothing changes, but in url, it becomes http://127.0.0.1:8000/search/?caption=tom to http://127.0.0.1:8000/search/?caption=tom&?page=2 filters.py: class VideoFilter(django_filters.FilterSet): class Meta: model = Video fields = ['caption'] filter_overrides = { models.CharField: { 'filter_class': django_filters.CharFilter, 'extra': lambda f: { 'lookup_expr': 'icontains', }, }, } views.py: def search(request): queryset = Video.objects.all() filterset = VideoFilter(request.GET, queryset=queryset) if filterset.is_valid(): queryset = filterset.qs paginator = Paginator(queryset, 2) page_number = request.GET.get('page') print(page_number)# always prints **none** queryset = paginator.get_page(page_number) return render(request, 'search.html',{ 'result': queryset, 'caption': request.GET['caption'], }) search.html: {% extends 'navbar.html' %} {% block body %} <!-- more code --> {% if result.has_next %} <a href="?caption={{caption}}&?page={{result.next_page_number}}"><button>See more results</button></a> {% endif %} {% endblock body %} navbar.html: <!-- more code --> <form action="/search/" method="GET"> <!-- working without csrf_token --> <input type="text" placeholder="Search" id="search" name="caption" required /> <button type="submit">Search</button> </form> where is the problem? how do i visit next page? -
How can I use custom web fonts in django cms icons
My question is how do how does the `/admin/djangocms_icon/includes/assets.html` file look like? Can someone give a sample supposing I am using font awesome 5? Below are the configuration settings that I followed on github. Configuration This addon provides a `default` template for all instances. You can provide additional template choices by adding a `DJANGOCMS_ICON_TEMPLATES` setting:: DJANGOCMS_ICON_TEMPLATES = [ ('svg', 'SVG template'), ] Web Font Icons ############## The django CMS Icon plugin ships with Font Awesome 4 as default. This can be changed by overriding the following setting:: DJANGOCMS_ICON_SETS = [ ('fontawesome4', 'fa', 'Font Awesome 4'), ] To use Font Awesome 5 in the above example; see the options below from the `DJANGOCMS_ICON_SETS` listed. In addition you need to load the resources for your fonts in `/admin/djangocms_icon/includes/assets.html`. Add this file to your project in order for the icon picker to pick up your custom icons in the admin. The icon picker supports `numerous font libraries <http://victor-valencia.github.io/bootstrap-iconpicker/>` out of the box. You can also add multiple font sets like this:: DJANGOCMS_ICON_SETS = [ ('elusiveicon', 'el', 'Elusive Icons'), ('flagicon', 'flag-icon', 'Flag Icons'), ('fontawesome4', 'fa', 'Font Awesome 4'), ('fontawesome5regular', 'far', 'Font Awesome 5 Regular'), ('fontawesome5solid', 'fas', 'Font Awesome 5 Solid'), ('fontawesome5brands', 'fab', 'Font Awesome … -
Django unit test is not finding any test
I want to run a unit test on test_models.py the contents of the file is below: from django.test import TestCase from django.contrib.auth import get_user_model class ModelTest(TestCase): def test_create_user_with_email_successful(self): email = 'superuser@super.com' password = '9876543210' user = get_user_model().objests.create_user( email=email, password=password ) self.assertEqual(user.email, email) self.assertTrue(user.check_password(password)) after i run python manage.py test I get this: System check identified no issues (0 silenced). ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK the file structure of my project is in the picture -
How do I access a Django template variable item(e.g an object in a list) using a variable
I have a for loop looping over a list supplied to the template. Now I want to use the first item on the list to on the first loop iteration, the second during the second one and so on. To access items in a list I would expect to use foo['bar'] or foo.bar. Question is how do I do this when bar is an attribute like {{ forloop.counter0 }}. {% for data in some_data %} <td>{{ some_list.{{ forloop.counter0 }} }}.</td> <!-- Cannot do this, Problem here --> {% endfor %} -
Alternative way of querying through a models' method field
I have this model about Invoices which has a property method which refers to another model in order to get the cancelation date of the invoice, like so: class Invoice(models.Model): # (...) @property def cancel_date(self): if self.canceled: return self.records.filter(change_type = 'cancel').first().date else: return None And in one of my views, i need to query every invoice that has been canceled after max_date or hasn't been canceled at all. Like so: def ExampleView(request): # (...) qs = Invoice.objects if r.get('maxDate'): max_date = datetime.strptime(r.get('maxDate'), r'%Y-%m-%d') ids = list(map(lambda i: i.pk, filter(lambda i: (i.cancel_date == None) or (i.cancel_date > max_date), qs))) qs = qs.filter(pk__in = ids) #Error -> django.db.utils.OperationalError: too many SQL variables However, ids might give me a huge list of ids which causes the error too many SQL variables. What's the smartest approach here? -
How to make a reserved button?
How can I create a button that when pressed, the car is reserved? Im trying to use a form with method GET but the button dont send nothing. Code: html: <from> <button onclick="enviar(True=true)" type="submit" name="id_coche" value="{{ car.matricula }}" >Reservar</button> </from> <script> function enviar(True) { let url = "" $.ajax({ method: 'GET', url: url, data: {}, success: True }); } </script> Views.py:### class CocheDetalles(DetailView): model = Coche template_name="wallacar_app/detalles.html" #if request.method == "GET": #Coche.objects.update(reserved=True) def get_context_data(self,object): context = super(CocheDetalles, self).get_context_data() context['coche'] = Coche.objects.filter(matricula=self.object).all() return context Im using Django 3.1.7 and jQuery. -
'QuerySet' object has no attribute 'user'
I am trying to query from pending payments and then when a user requests for a payment i also want to be checking from the orders that corresponds to a logged in user. This is the code that fetches the withdraw requests: pending_requests = WithdrawRequest.objects.filter(status='pending') Code that fetches the totals orders corresponding to the user from pending_requests variable above which is pending_requests.user: #amount query AccBalance = OrderData.objects.filter(payment_to=pending_requests.user, payment_status='approved').aggregate(totals=Sum(F('item__price')*F('quantity'))) The problem is i am getting this error: 'QuerySet' object has no attribute 'user' My full view.py code: def withdraw_requests(request): pending_requests = WithdrawRequest.objects.filter(status='pending') #amount query AccBalance = OrderData.objects.filter(payment_to=pending_requests.user, payment_status='approved').aggregate(totals=Sum(F('item__price')*F('quantity'))) context = {'AccBalance':AccBalance,'pending_requests':pending_requests} return render(request, 'accounts/withdraw_requests.html', context) -
How to update a record in django?
I try to update my record but in place of updating it displays a message saying the record already exists. here is the logic I m executing : @login_required def cylinderUpdateView(request,pk): if not request.user.is_superuser: return redirect('index') obj=CylinderEntry.objects.get(id=pk) form=CylinderEntryForm(instance=obj) if request.method=='POST': form=CylinderEntryForm(data=request.POST) if form.is_valid(): obj=form.save(commit=False) obj=form.save() return redirect(cylinderListView) return render(request,'entry/cylinderentry_form.html',locals()) -
django template get a list item using a template variable as index
Supposing a list0 with elements ['a','b','c','d'], I need to get the nth element depending on a template variable like forloop.counter0 or any other integer available from the template. So far the better way I found was to create a custom tag as explained here or here and in the django doc. Once defined you can write something like : {% for elm in list0 %} {{ elm }} {{ list1|index:forloop.counter0 }} {% endfor %} The example assumes there's another list list1, with elements ['A','B','C','D']. index is the name of the custom filter, it uses the forloop counter as an index to get each list1 element : list1[0], list1[1], list1[2], list1[3] So this generates : a A b B c C d D But what if you only want to use builtin filters ? (Or have spare time for recreative stuff ?) After some research and tests the only way I found is this odd thing : {% for elm in list0 %} {% with sl0=forloop.counter0|make_list sl1=forloop.counter|make_list %} {% with header_id=sl0.0|add:":"|add:sl1.0 %} {{ elm }} {{ list1|slice:header_id|join:"" }} {% endwith %} {% endwith %} {% endfor %} what it does : I hope I missed something in the documentation because the … -
Django forms not appearing due to Model as a field?
I am trying to make a file management system using Django but not clear how to make Model forms when there is a foreignkey in the model. Everything I have tried so far did not work. Models.py: from django.db import models from django.contrib.auth.models import User class Files(models.Model): name = models.TextField(max_length=144) contet = models.FileField(null=False) class UserFolder (models.Model): folderName = models.TextField(blank=False) files = models.ForeignKey(Files, on_delete=models.CASCADE) class UserProfile (models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField(upload_to='pictures/%y/%m/%d/', max_length=255, null=True, blank=True) folder = models.ForeignKey(UserFolder, on_delete=models.CASCADE, blank=True) file = models.ForeignKey(Files, on_delete=models.CASCADE) Created User model where user can have folders and files. Folder model where folder contains files and at last a model for files. Forms.py: class NewFolderForm(forms.ModelForm): class Meta: model = UserFolder fields = ['folderName', 'files'] widgets = { 'folderName': forms.Textarea(attrs={'class': 'field', 'placeholder': 'folder name...'}), 'files': forms.FileInput(attrs={'class': 'field input'}) } I think the main issue lies here as i'm trying to define the files field as an file input field as files is a reference to file model; but i don't know any workarounds to this issue. Views.py: def makeFolder(request): form = NewFolderForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('home') context = {form: 'form'} return render(request, 'makefolder.html', context) Just saving the form if it's valid. HTML Code: … -
How I can invoke js script from django view?
In a view I have a condition that should invoke js script declared in template. Is there any way to do it? -
How do I remove the "Account" section from the Django Admin Page
I would like to remove the "Account" section from the Django Admin page. I can't figure out what model I would need to unregister(). -
Unable to open Zip file downloaded using Django
I am converting a directory and all its contents into a zip file and downloading it but when I try to open the downloaded zip file I am getting the error:- C:\Users\user1\Downloads\directory1.zip: Unexpected end of archive Here is my function for zipping and downloading the directory as a zip file in Django:- def download(request): body = request.body #fetching directory name from request body directory = body['directory'] #dir_name contains path of the directory to be converted into zip dir_name = BASE_DIR + '\\downloads\\' +"\\{0}".format(directory) #zip_file_name is the full path of the zip file which will contain the directory as a zip zip_file_name = dir + '.zip' ###Creating Zip File zipf = zipfile.ZipFile(zip_file_name, 'w', zipfile.ZIP_DEFLATED) path = dir_name ziph = zipf # ziph is zipfile handle for root, dirs, files in os.walk(path): for file in files: ziph.write(os.path.join(root, file), os.path.relpath(os.path.join(root, file), os.path.join(path, '..'))) zipf.close() #Define the full file path filepath = zip_file_name #filename is the name to be given to the downloaded zip file filename = directory + '.zip' ###Download section # Open the zip file for reading content path = open(filepath, 'r', errors="ignore") # Set the mime type mime_type, _ = mimetypes.guess_type(filepath) # Set the return value of the HttpResponse response = … -
Forwarding a local port to a remote machine
I'm using Winscp trying to do a local port forwarding to a remote machine. In one putty window I run the django project on 127.0.0.1:8000, in another putty window I run the forward command ssh -L 8000:127.0.0.1:8000 -C -N -l <username> <ip> But I can't access through the browser on windows 10 at 127.0.0.1:8000 or localhost:8000. But if I try to open on mac os everything works. I tried disabling the firewall on windows 10, but it didn't help -
Django crispy-forms show all error messages on top of form
I use Django crispy-forms with tabs and bootstrap4 and everything works well. Except when I try to submit the form and there is an error on another tab: The user does not see the error and there is no visual hint that there is a validation error somewhere else on another tab. To work around this issue, I thought it would be easiest to just show all errors also on top of the form. But I didn't find any help on that so far... can someone point me in the right direction? I use Formhelper with Layout, TabHolder and Tab classes to create the tabs: form.helper = FormHelper() form.helper.layout = Layout( TabHolder( Tab( 'Basic', 'number', 'name', 'name_additional', ... -
Applying custom font to a Django email template
I'm styling a Django email template using inlinecss, but my custom font is not being applied to the email. In the css file (included using {% load inlinecss %} {% inlinecss "css/styles.css" %} in the html file), I have the following: @font-face { font-family: 'my-font'; src: url("../fonts/my-font.woff2") format("woff2"), url("../fonts/my-font.woff") format("woff"); } Any idea how I can get my custom font to get applied to the email? Thanks. -
Django unittest in Docker container : ModuleNotFoundError: No module named 'code.x'; 'code' is not a package
this is my first project with Django and also my first time using Docker. So far I'm really enjoying both of them but I'm facing a problem I couldn't resolve after a week. I followed this tutorial to build my project : https://medium.com/swlh/setting-up-a-secure-django-project-repository-with-docker-and-django-environ-4af72ce037f0 So far, my project structure looks like like this : MyProject ├── backend # Django "app" │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── models.py │ ├── permissions.py │ ├── serializers.py │ ├── tests.py │ └── views.py │ ├── config # Django "project" │ ├── __init__.py │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py │ ├── docker # Docker configuration files, content close to the source link above │ └── ... │ ├── frontend # independent angular project │ └── ... │ ├── .gitignore └── manage.py My project is up and running fine inside the containers and everything is working as expected. Well, almost everything.. I wrote some simple tests and tried to run them from inside the "web" container (which contains the web app) and whenever i run python manage.py test i get the following errors : root@web:/code# python manage.py test System check identified no issues (0 silenced). EE … -
Django how to test model functions with validator
My models.py is looking like this: def validate_yearofbirth(value): text = str(value) if len(text) < 4 or len(text) > 4 or value < 1900: raise ValidationError('Please insert your year of birth!') class Personal(models.Model): firstname = models.CharField(max_length = 100) lastname = models.CharField(max_length = 100) yearofbirth = models.PositiveIntegerField(validators = [validate_yearofbirth], null = True) @property def fullname(self): return '{}, {}'.format(self.lastname, self.firstname) def __str__(self): return self.fullname @property def age(self): year = datetime.now().year age = year - self.yearofbirth return age Anyone know how to write a test for def validate_yearofbirth and for def age? I only managed to write a test for def fullname, but I haven't figured out how to write a test for a function which is not def __str__(self). My test_models.py file for this class is looking like this: class TestModel(TestCase): def test_personal_str(self): fullname = Personal.objects.create(nachname = 'Last Name', vorname = 'First Name') self.assertEqual(str(fullname), 'Personal Test Nachname, Personal Test Vorname') Also you can ignore the fact that return age doesn't always return the "real" age - this isn't important for my class. -
can not deploy site to heroku , showing error app not compatibe
added requirement.txt, Procfile, receving error while deploying site to heroku what could be wrong with this Enumerating objects: 110, done. Counting objects: 100% (110/110), done. Delta compression using up to 8 threads Compressing objects: 100% (106/106), done. Writing objects: 100% (110/110), 13.54 MiB | 1.30 MiB/s, done. Total 110 (delta 35), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Using buildpack: heroku/python remote: -----> *App not compatible with buildpack: https://buildpack- registry.s3.amazonaws.com/buildpacks/heroku/python.tgz* remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to covidcms. remote: To https://git.heroku.com/covidcms.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/covidcms.git' -
Django POST request data object wraps string values in array
When I print the POST request object in a standard django view, the values are wrapped in an array and I don't understand why. Weird thing is if I do a GET for all objects using postman, they are not wrapped in array and appear as strings. FYI model fields are TextField NOT list. class JiraDataViewSet(BaseModelViewSet): queryset = JiraData.objects.all().order_by("-id") serializer_class = JiraDataSerializer permission_classes = [ IsAdmin, ] lookup_field = "uuid" @action(detail=False, methods=["post"]) def test_connection(self, request, *args, **kwargs): print(f'is request {request.data}') result = False if request.data: Print looks like: <QueryDict: {'jira_instance': ['https://uk-hairloom.atlassian.net/'], 'jira_board': ['TEST- board'], 'username': ['paul.macleod@uk-hairloom.net'], 'password': ['5G8K2iVx4xLp9BkpXDfx45R0'], 'ip_address': ['poc.sec-1.com', '129.0.2.3'], 'jira_prefix': ['bug'], 'customer_name': ['Example Inc.']}> Any advice much appreciated. -
Django - How to use Subquery and count
I'm trying to achive an annotated query and here's my code. # models.py STATUS_CHOICES = ( ("submitted", "제출됨"), ("in-review", "검토중"), ("rejected", "반려됨"), ("approved", "승인됨"), ) class ClassReview(models.Model): class = models.ForeignKey("class.Class", on_delete=models.PROTECT) status = models.CharField(max_length=10, choices=STATUS_CODE, default="submitted") class ClassReviewVote(models.Model): target = models.ForeignKey("class.ClassReview", on_delete=models.PROTECT) vote = models.BooleanField(null=True) # selectors.py def get_classreview_set(class_id): review_set = ClassReview.objects.filter(class_id=class_id, status="approved") review_Set = review_set.annotate( vote_up_count=Subquery( ClassReviewVote.objects.filter(target_id=OuterRef("pk"), vote=True) .values("target") .annotate(count=Count("target")) .values("count"), output_field=IntegerField(), ) ) return review_set # serializers.py def classreview_serializer(classreview): data = dict() ... data["vote_up_count"] = classreview.vote_up_count ... return data # views.py class ClassDetailView(TemplateView): ... def get(self, request, *args, **kwargs): class_id = request.kwargs.get("class_id") review_set = get_classreview_set(class_id) context = { review_list = classreview_serializer(review_set) } ... ... I want to annotate vote up count of each review. But it keeps raising Error "more than one row returned by a subquery used as an expression". When logged in user and someone else voted up. What is happening? -
Local time zone is not showing time
I am building a BlogApp and I am trying to accessing Local Time of the User , I have followed steps according to the documentation. BUT after it , it is not showing the local time of the user. settings.py MIDDLEWARE = [ 'app.middleware.TimezoneMiddleware', ] TIME_ZONE = 'Asia/Kolkata' USE_I18N = True USE_L10N = True USE_TZ = True middleware.py import pytz from django.utils import timezone class TimezoneMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): tzname = request.session.get('django_timezone') if tzname: timezone.activate(pytz.timezone(tzname)) else: timezone.deactivate() return self.get_response(request) views.py def set_timezone(request): if request.method == 'POST': request.session['django_timezone'] = request.POST['timezone'] return redirect('/') else: return render(request, 'template.html', {'timezones': pytz.common_timezones}) template.html {% load tz %} {% localtime on %} {{ value }} {% endlocaltime %} {% localtime off %} {{ value }} {% endlocaltime %} {% timezone "Europe/Paris" %} Paris time: {{ value }} {% endtimezone %} {% timezone None %} Server time: {{ value }} {% endtimezone %} {{ value|localtime }} I have seen answer like THIS and THIS, BUT still not showing the local time. Any help would be Appreciated. Thank You in Advance -
Get list of data on each available date in django
I am trying to build a Django app, where a user will enter daily reports. For example, on 13 April 2020, 4 Reports were made, on 14 April 2020, 6 Reports were made. The list of all reports will be divided into sub-lists based on the report date. So I want to get the list of reports in this following matter list_of_reports = { "14/04/2020": [<Report 1>, <Report 2>, <Report 3>], "15/04/2020": [<Report 4>, <Report 5>, <Report 6>], } And on my HTML view, I want to show my report in this following matter <div> <p>Date: 14/04/2020</p> <ul> <li>Report 1</li> <li>Report 2</li> <li>Report 3</li> </ul> </div> <div> <p>Date: 15/04/2020</p> <ul> <li>Report 4</li> <li>Report 5</li> <li>Report 6</li> </ul> </div> My Model class DailyReport(models.Model): report = models.CharField(max_length=500) created_at = models.DateTimeField(auto_add_now=True) @property def creation_date(self): return self.created_at.strftime('%Y:%m:%d') My Template View class DailyReportView(TemplateView): template_name = "Report/report_list.html" def get_context_data(self): context = super().get_context_data() report_list = # Here I will get the desired Report List that I want based on date context["reports"] = report_list return context