Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Save all i18 strings in single .po file
Is there a way to create single django.po for one language from all apps inside the project in BASE_DIR/locale or at least put .po file in BASE_DIR/app_name/locale? -
Logged in user has a different id than that of the same user in django database
I am trying to create a todo note application using django,sqlite database, when a user try to register into my app,he is assigned by an id by django by default,but when i try to retrieve/get information of that user using request.user.id it returns a different id than that of actual id.Example, a user is registered in my site by a name 'honey', the django sqlite shows his id as '12' but when i try to get it by request.user.id then its raising an matching query does not exist error. views.py def newNotePage(request): form = NewNote user = request.user print(user) #prints 'honey' print(user.id) #prints '13' cus = NotesModel.objects.get(id=user.id) print(cus) # raises - NotesModel matching query does not exist. if request.method == 'POST': form = NewNote(request.POST) if form.is_valid(): # cus = NotesModel.objects.get(id=user.id) # cus.notes_set.create(notesOf=user) form.save() return redirect('welcome') context={'form':form} return render(request,'todoapp/new_note.html',context) models.py class NotesModel(models.Model): userFromModel = models.OneToOneField(User,null=True,on_delete=models.CASCADE) name = models.CharField(max_length=100,null=True) def __str__(self): return self.name class Notes(models.Model): notesOf = models.ForeignKey(NotesModel,null=True,on_delete=models.SET_NULL) title = models.CharField(max_length=100,null=True) description = models.TextField(null=True,blank=True) created_date = models.DateTimeField(auto_now_add=True) edited_date = models.DateTimeField(auto_now=True) def __str__(self): return str(self.title) console output or server log django database -
django urls doesn't work on a distant server
my_project.urls from django.contrib import admin from django.urls import path from django.conf.urls import include, re_path from django.conf import settings from django.http import HttpResponse from machina import urls as machina_urls from allauth.account import views def empty_view(request): return HttpResponse("Empty View") urlpatterns = [ # path('', empty_view, name='empty_view'), path('admin', admin.site.urls), re_path(r'^account/', include('allauth.urls')), # path('', include('allauth.urls')), # re_path('^', include('allauth.urls')), I tested all the above possibilities. On my computer, localhost:8000/account/login/ is just fine. On a distant server (PlanetHoster), my_domain/my_app/ says : Using the URLconf defined in my_app.urls, Django tried these URL patterns, in this order: admin ^account/ /my_domain/my_app/account/ says : Using the URLconf defined in my_app.urls, Django tried these URL patterns, in this order: signup/ [name='account_signup'] login/ [name='account_login'] logout/ [name='account_logout'] The empty path didn't match any of these /my_domain/my_app/account/login return to the homepage of my_domain. And in settings.py LOGIN_URL = 'account/login' LOGIN_REDIRECT_URL = '/projects/project/' ACCOUNT_LOGOUT_REDIRECT_URL = "/account/login" ACCOUNT_EMAIL_REQUIRED = True # ACCOUNT_EMAIL_VERIFICATION = "optionnal" I test with the empty_view in the urls, with Application URL : my_domain/my_app/account/login on the server, it works. -
Submitting a Django form and returning a JsonResponse?
Im working on some API views, created with pure Django, which I have never done before. I am testing with Postman, and running into some issues. I need to be able to post form data, and convert it to JSON. My view def buyer_offer_api(request): if request.method == 'POST': form = BuyerForm(request.POST, request.FILES) if form.is_valid(): post = form.save(commit=False) post.user = request.user post.save() data = form.cleaned_data return JsonResponse(data, safe=False) else: data = form.errors.as_json() return JsonResponse(data, status=400, safe=False) else: form = BuyerForm().fields return JsonResponse({'form': list(form)}) Now, testing a POST request on postman, using raw json data, I am getting a 404. Basically saying nothing has been filled out? -
bootstrap : cards in a for-loop
I try to use Cards from Bootstrap to show some information from different stocks in a database. I'm using DJANGO's template engine and already have the code below. On a desktop, after three cards a new row is showed but there is no space between the first and second row. When showed on mobile, all the cards are underneath eachother, but again with no space between. How can I add some extra space between the cards? <div class="container"> <div class="row"> {% for security in securities %} <div class="col-sm-4"> <div class="card" style="width: 18rem;"> <img src="{% static "public/engie.jpg" %}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{ security.name }}</h5> <p class="card-text">Text here</p> </div> <ul class="list-group list-group-flush"> <li class="list-group-item">{{ security.quote }}</li> <li class="list-group-item">{{ security.lastchange_pct }}</li> <li class="list-group-item">{{ security.remarks }}</li> </ul> <div class="card-body"> <a href="#" class="card-link">Card link</a> <a href="#" class="card-link">Another link</a> </div> </div> </div> {% endfor %} -
TypeError: '<' not supported between instances of 'method' and 'method' [closed]
I have a model form wherein I want the values in the drop-down to be sorted in alphabetical order based on name, however, because of method(get_full_name) I am unable to sort it. Snippet of my Model form: class AwardForm(forms.Form): def __init__(self, user=None, award_id=None, *args, **kwargs): kwargs.setdefault('label_suffix', '') super(AwardForm, self).__init__(*args, **kwargs) if user and award_id: receivers = get_user_model().objects.select_related('employee'.filter(employeeemployee__user=user).exclude(id=user.id).distinct('id') self.fields['receiver'].choices = [('','--Please Select--')]+ sorted([(receiver.employee.id, receiver.get_full_name) for receiver in receivers], key=lambda name: name[1]) self.fields['sender'].widget.attrs['value'] = user.get_full_name() And my model is: class User(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.get_full_name() -
Django upload form for logo into BinaryField
I have a MySQL table with languages, and want to have a flag field next to every single language. This is an existing situation that I'm trying to convert from a different language into Django. This is the model I have for my languages: class Language(models.Model): language = models.CharField(primary_key=True,unique=True, max_length=8) description = models.CharField(max_length=35) flag = models.BinaryField(editable=True, blank=True, null=True) class Meta: db_table = 'language' verbose_name_plural = "language" def __str__(self): return self.description I already managed to display the flags in my list view. But I also want to have an upload function in my form, but I'm not able to figure this out. forms.py class LanguageForm(forms.ModelForm): class Meta(): model = Language fields = '__all__' widgets = { 'flag': forms.FileInput() } views.py class CreateLanguageView(LoginRequiredMixin,CreateView): login_url= '/login/' redirect_field_name = 'app/language_list.html' form_class = LanguageForm model = Language def form_valid(self, form): if form.is_valid(): data = form.cleaned_data self.object.save() return HttpResponseRedirect(self.get_success_url()) def get_success_url(self): return reverse('language_list') -
Why is Django not reading HTML code within a for loop?
I have written some code that allows users of a website to comment on photos in a picture gallery, using a form. However, when I test the code, no comments are displayed. It would appear that Django is not processing the following code (from my HTML file for the photo gallery), given that 'Comment by' is not displayed on screen: {% for comment in comments %} <div class="comments" style="padding: 10px;"> <p class="font-weight-bold"> <h4>Comment by</h4> {{ comment.user }} <span class=" text-muted font-weight-normal"> {{ comment.created_on }} </span> </p> {{ comment.body | linebreaks }} </div> {% endfor %} Does anyone have any suggestions as to how I can fix this, please? Thank you. Jeff -
Django - How to display a attribut (name) from forgeinKey object?
I have an artist which has many paintings, so a many to one relation. So i got class Artist(models.Model): name = models.CharField(max_length=120) age = models.IntField() class Paintings(models.Model): painting = models.ImageField() painting_name = models.CharField(max_length=120, default='', null=True) artist = models.ForeignKey( 'Artist', related_name='paintings', on_delete=models.CASCADE, verbose_name= 'Künstler' ) now if I'll create a new Painting rely to an artist it doesnt show me the exact name of the artist, just the artist object [id] inside my admin.py I try to define artist = Artist.name list_display = ('image_tag', artist, 'painting_name') but this is not allow. So how can I replace the Artist Object (id) with the acutal name of the artist? -
Mailchimp embedded form Integration to Dajngo application Error
I have created a Mailchimp email list form with the official mailchimp embedded form creator. When I test it on my development machine it works a couple of times but after a while like a day later it does not when I pus the code online to my digital ocean server it just stop working immediately. I have not modified the code that I have copied and pasted from mailchimp in any ways. What should happen: people type in their email in to a filed click subscribe Pop up windows comes up from mailchimp recaptcha does on that pop up window Approval shows on the small op up window Subscriber receives conformational mail What happened when it did not work correctly: people type in their email in to a filed click subscribe Reloaded the same page I was on with a long URl like this https://MYWEBSITE.COM/?EMAIL=SUBSCRIBER%40gmail.com&b_11111111111111111111111111111111_1111111111111111=&subscribe=Subscribe **Mailchimp Code ** <!-- Begin Mailchimp Signup Form --> <link href="//cdn-images.mailchimp.com/embedcode/horizontal-slim-10_7.css" rel="stylesheet" type="text/css"> <style type="text/css"> #mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; width:100%;} /* Add your own Mailchimp form style overrides in your site stylesheet or in this style block. We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. … -
django.db.utils.ProgrammingError: multiple default values specified for column "question_id" of table "questions_question"
Hello I wrotet this models.py and when i migrate this error appears: " django.db.utils.ProgrammingError: multiple default values specified for column "question_id" of table "questions_question" class Test(models.Model): test_id = models.AutoField(primary_key=True) name = models.CharField(max_length=200) def __str__(self): return str(self.name) class Question(models.Model): question_id = models.AutoField(primary_key=True) question_text = models.CharField(max_length=200) c1 = models.CharField(max_length=200, default='') c2 = models.CharField(max_length=200, default='') c3 = models.CharField(max_length=200, default='') c4 = models.CharField(max_length=200, default='') answer = models.CharField(max_length=200, default='c1') marks = models.IntegerField(default=0) def __str__(self): return self.question_text class Association(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) test = models.ForeignKey(Test, on_delete=models.CASCADE) -
I'm getting 404 error on every page in django
I'm developing my first app in Django and facing some issues. The server runs smoothly and I can operate the admin panel without any issues. However, all of the app pages including the default homepage show a "404 not found" error. I have created a templates directory in project root updated this line in settings.py for templates, 'DIRS': [os.path.join(BASE_DIR,'templates')], View for the app from django.shortcuts import render from .models import * # Create your views here. def customers(request): customers = Customer.objects.all() return render(request, "customers.html", {'customers': customers}) urls for the app from django.urls import path from . import views urlpatterns = [ path('customers',views.customers, name='customers') ] urls for the project from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('trips/',include('trips.urls')), path('customers/',include('customers.urls')), path('drivers/',include('drivers.urls')), path('vehicles/',include('vehicles.urls')), path('admin/', admin.site.urls), ] urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Help is appreciated -
DRF: Right way to use ListCreateAPIView with nested serializer
I make a page that lists all the existing vendors and modules that apply to each vendor. Here I need to change the status of modules (active or unactive), and if the module does not exist, but need to make it active then create it. It looks roughly like this. Vendor1 module1/false module2/true module3/true ..... Vendor2 module1/false module2/true module3/true ..... ..... ..... models.py class RfiParticipation(models.Model): vendor = models.ForeignKey('Vendors', models.DO_NOTHING, related_name='to_vendor') m = models.ForeignKey('Modules', models.DO_NOTHING, related_name='to_modules') active = models.BooleanField(default=False) user_id = models.IntegerField() rfi = models.ForeignKey('Rfis', models.DO_NOTHING, related_name='to_rfi', blank=True, null=True) timestamp = models.DateTimeField(auto_now=True) To display it, I use ListCreateAPIView() class and nested serializer serializer.py class VendorModulesListManagementSerializer(serializers.ModelSerializer): to_vendor = RfiParticipationSerializer(many=True) class Meta: model = Vendors fields = ('vendorid', 'vendor_name', 'to_vendor',) read_only_fields = ('vendorid', 'vendor_name', ) def create(self, validated_data): validated_data = validated_data.pop('to_vendor') for validated_data in validated_data: module, created = RfiParticipation.objects.update_or_create( rfi=validated_data.get('rfi', None), vendor=validated_data.get('vendor', None), m=validated_data.get('m', None), defaults={'active': validated_data.get('active', False)}) return module class RfiParticipationSerializer(serializers.ModelSerializer): class Meta: model = RfiParticipation fields = ('pk', 'active', 'm', 'rfi', 'vendor', 'timestamp') read_only_fields = ('timestamp', ) views.py class AssociateModulesWithVendorView(generics.ListCreateAPIView): """ RFI: List of vendors with participated modules and modules status """ permission_classes = [permissions.AllowAny, ] serializer_class = VendorModulesListManagementSerializer queryset = Vendors.objects.all() I have a question about using the create serializer … -
Casting result of an F function to an int
I have a simple Django application were I try to aggregate multiple values into an annotation for easier processing on the client side. Basically, I need to sum the values of multiple columns into one. For this I'm trying to use annotate with F functions: qs = TimeReport.objects \ .filter(year=year, term=term) \ .annotate( created_by_first_name=F('created_by__first_name'), created_by_last_name=F('created_by__last_name'), total_hours = F('master_thesis_supervision_hours') + F('semester_project_supervision_hours') + F('other_job_hours') + F('MAN_hours') + F('exam_proctoring_and_grading_hours') + F('class_teaching_exam_hours') + F('class_teaching_practical_work_hours') + F('class_teaching_preparation_hours') + F('class_teaching_teaching_hours'), ) \ .all().values() Suprisingly, when I inspect the content of the calculated field, it does not contain anything: list(qs)[0]['total_hours'] None Trying to cast the result of the F function does not either: ... total_hours = int(F('master_thesis_supervision_hours')) +int(F('semester_project_supervision_hours')) + ... I also tried to update the models.py to add a property: @property def total_hours(self): return self.master_thesis_supervision_hours + self.class_teaching_total_hours + self.semester_project_supervision_hours + self.other_job_hours + self.MAN_hours + self.exam_proctoring_and_grading_hours and update the views.py accordingly: qs = TimeReport.objects \ .filter(year=year, term=term) \ .annotate( created_by_first_name=F('created_by__first_name'), created_by_last_name=F('created_by__last_name'), total_hours = F('total_hours'), ) \ .all().values() But I get the following error: django.core.exceptions.FieldError: Cannot resolve keyword 'total_hours' into field. What would be the correct way to do this? -
Django form doesn't appear on template
I'm currently working on a project that require Django Forms but I ended up with some issues. My form doesn't display at all ... No field appear on my template. So my code : models.py class Place(models.Model): name = models.CharField(max_length=255) longitudeMax = models.DecimalField(max_digits=8, decimal_places = 4 ,blank=True) longitudeMin = models.DecimalField(max_digits=8, decimal_places = 4, blank=True) latitudeMax = models.DecimalField(max_digits=8, decimal_places = 4, blank=True) latitudeMin = models.DecimalField(max_digits=8, decimal_places = 4, blank=True) datasetPath = models.CharField(max_length=255) isActive = models.BooleanField(default=True) def __str__(self): return self.name def get_place(self, name): return None forms.py class NewPlaceForm(forms.Form): name = forms.CharField( widget=forms.TextInput( attrs={ "placeholder" : "Name", "class": "form-control" } )) longMax = forms.DecimalField( widget=forms.NumberInput( attrs={ "placeholder" : "Longitude Max", "class": "form-control" } )) longMin = forms.DecimalField( widget=forms.NumberInput( attrs={ "placeholder" : "Longitude Min", "class": "form-control" } )) latMax = forms.DecimalField( widget=forms.NumberInput( attrs={ "placeholder" : "Latitude Max", "class": "form-control" } )) latMin = forms.DecimalField( widget=forms.NumberInput( attrs={ "placeholder" : "Latitude Min", "class": "form-control" } )) class Meta: model = Place fields = ('name', 'longitudeMax', 'longitudeMin', 'latitudeMax', 'latitudeMin') views.py def upload(request): msg = None if request.method == "POST": form = NewPlaceForm(request.POST) if form.is_valid(): form.save() msg = 'Place created' else: msg = 'Form is not valid' else: form = NewPlaceForm() return render(request, "pages/place_upload.html", {"form": form, "msg" : … -
How to get image's url in HTML template in Django?
I have a model class SliderImage(models.Model): title = models.CharField("Nazwa obrazka", max_length=250) image = models.ImageField(upload_to="main/media/slider/") def __str__(self): return self.title Then I have the view: def page(request): sliders = SliderImage.objects.all() return render(request, 'page/page.html', {'sliders':sliders, 'section':'page'}) Then I have HTML code: {% for slide in sliders %} <p><img src="{{ slide.image }}"/></p> {% endfor %} The problem here is that page doesn't get the path of images right - I believe it's because of "/main/" at the beginning of the image path - code gets confused. My folders' structure looks like this: main->media, static, templates, migrations I'm not sure how to handle it. I believe that maybe even the media folder should be outside of main(app), but how should then code look like, so Django knows where to look for those images? I had tried putting media folder outside of main, but it still didn't help. -
Django populate admin with dynamic fields and save model
I have a use case where admin wants to add certain default message for various cases like below. default -> "Hello" website -> "StackOverflow" user -> "Kausal" My admin has a model tied already and want this model to be attached as NestedTabularInline. And I want my admin to show as many fields as they are created in admin, dynamically. My admin should look something like this so the messages configured already appears by default and the user can edit if required. **Messages** **case** **message** default Hello website StackOverflow user Kausal They all should be tied to another model with a foreign key like the below table structure. id foreign_key(id) case message 1 123 default Hello 2 123 website StackOverflow 3 123 user Name I tried searching multiple docs and it pointed to FormSet but it doesn't solve my use case. I am not sure if this is possible in Django at all but thought of checking on community before thinking of overriding any default methods. -
Django:Unable to add extra field in User Model
I got the idea from a random post that how to extend the field of the User Model in Django by using the One to One relation. I'm trying to write One to One relation by creating a complete_user model in models.py but i'm getting error.can anyone tell me what's wrong with my code.i'm new in django. models.py from django.db import models from django.contrib.auth.models import User class complete_user(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) country1=models.CharField(max_length=10) class Meta: db_table='complete_user' forms.py from django import forms class user_data(forms.Form): country=forms.CharField(widget=forms.TextInput) html file <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> </head> <body> <br> <center><h1 class="bg-info">Create Your New Account</h1></center> <header class="container"> <div class="w-25 mx-auto"> <form action="{% url 'save_account' %}" method="POST"> {% csrf_token %} <div class="form-group"> <label for="name">Name</label> <input type="text" placeholder="e.g. John" required name="name" class="form-control" id="name"> </div> <div class="form-group"> <label for="email">Email address</label> <input type="email" name="email" required placeholder="e.g. john12@gamil.com" class="form-control" id="email" aria-describedby="emailHelp"> <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small> </div> <div class="form-group"> <label for="country">Country</label> <input type="text" required name="country" placeholder="e.g. India" class="form-control" id="country"> </div> <div class="form-group"> <label for="password1">Password</label> <input type="password" minlength="8" required name="password1" class="form-control" id="password1" aria-describedby="password_help"> <small id="password_help" class="form-text text-muted">Password should be strong it must contain numbers,alphabet and … -
Search Form in Django with python
I'm trying to add a simple search form on my django website. When I hit the search button I'm redirected to the new_search.html page (as it should be) but the page doesn't show any result. Thanks for your help! The code is this: I've got an homepage where I put the search form like this: <form method="get" action="{% url 'new_search' %}"> {%csrf_token%} <input type="text" name="srh" class= "form-control" placeholder="Search"> <button type="submit" name="submit">Search</button> </form> When a user search for something the result should be showed in the new_search.html page. The function I wrote in the views.py is this: def new_search(request): if request.method == 'GET': srch = request.GET.get('srh') if srch: sr = Info.objects.filter(Q(band__icontains=srch) | Q(disco__icontains=srch)) if sr: return render(request, 'new_search.html', {'sr':sr}) else: messages.error(request, 'no results') else: return render(request, 'new_search') return render(request, 'new_search.html') And the new_search.html page is this: <div> {% if sr %} {% for k in sr %} <table width="200px"> <tr><td>Band</td><td>{{k.band}}</td></tr> <tr><td>Album</td><td>{{k.disco}}</td></tr> </table> {%endfor%} {%endif%} </div> The model.py is this: class Info(models.Model): band = models.CharField(max_length=200, help_text="Write Here") disco = models.CharField(max_length=200, help_text="Write Here") etichetta_p = models.CharField(max_length=200, help_text="Write Here") etichetta_d = models.CharField(max_length=200, help_text="Write Here") matrice = models.CharField(max_length=200, help_text="Write Here") anno = models.PositiveIntegerField(default=0) cover = models.ImageField(upload_to='images/') def __str__(self): return self.band -
How to allow empty strings in Django serializer's datetime fields
I attached my serializer code. I'm working with Django Rest Framework. Normally you can setup a serializer in less than 5 lines of code but this is not the case. The problem is that the FE sends date_start or date_end as empty string instead as null when the user did not set them inside the form. In the current code, to allow the FE to pass date_start and date_end as an empty string, I set on them a temporary not empty value, so that the validation can work and, before to save the data to the DB, I revert this special value to None. Anything works... but... I know that it is an ugly solution, is there a better way to pass date_time as "" instead as null ? I have to use Django 1.10 class RulesSerializer(serializers.Serializer): __None__ = "__None__" nullable_fields = ( 'date_end', 'rules', 'date_start', 'price_base') id = serializers.IntegerField() country_code = serializers.CharField() operator_name = serializers.CharField() operator_id = serializers.IntegerField() calculation_base = serializers.CharField() price_base = serializers.CharField(required=False) rules = serializers.CharField(required=False) value_format = serializers.CharField() value = serializers.FloatField() date_start = serializers.CharField(required=False) date_end = serializers.CharField(required=False) def to_rapresentation(self, instance): return super(RulesSerializer,self).to_rapresentation(instance) def to_internal_value(self, data): for field in self.nullable_fields: if field in data: data[field] = data[field] or … -
Ordering by day of week - Django
I want to create a weekly calendar according to created schedules by admin. Days of week should be displayed horizontally, and each of schedules under according day of week, vertically. Now my code works like in this picture. But I want to display, for example, monday meeting vertically in one column and so on. here are my codes: views.py: def index(request): available_times = Available.objects.all().order_by('available_date') context = { 'available_times': available_times } return render(request, 'index.html', context) models.py: class Available(models.Model): description = models.TextField(max_length=200) message_to_participiant = models.TextField(max_length=500) available_date = models.DateField() available_hour = models.TimeField() is_scheduled = models.BooleanField(default=False) def __str__(self): return self.description index.html: <div class="container"> {% for meeting in available_times %} <div class="meeting-box"> <h4>{{ meeting.available_date|date:"l" }}/{{ meeting.available_date }}</h4> <p>{{ meeting.available_hour }}</p> <p>{{ meeting.description }}</p> <p>{{ meeting.message_to_participiant }}</p> </div> {% endfor %} </div> -
Django django-jet rename header for ModelAdmin
enter image description here I have a Django application with django-jet admin panels. How to rename MEMBER BOOKING FEEDBACKS to a custom title (upper left corner)? Custom title need to be provided from back-end. -
djago_el_pagiination not working as it should
I am using django_el_pagination to paginate pages on my application, but the ajax call doesn't work. I have follwed the documentation to the last bit, but still doesn't work. I got it to at least call the ajax function when i changed the way the documentation says to call the el-pagination static js file, but then it just shows loading and outputs an empty page. Below is my code, what am i doing wrong? View @login_required @page_template('app/clients.html') def clients_list(request, template='app/user_measurements.html', extra_context=None): get_order = get_object_or_404(ClientOrdering, pk=request.user.clientordering.pk) if request.method == 'POST': form = OrderingForm(request.POST, instance=get_order) if form.is_valid(): form.save() return HttpResponseRedirect(reverse_lazy('user-measurements')) else: form = OrderingForm(instance=get_order) if request.user.clientordering.order == 'Name': clients = UserModel.objects.filter(user_name=request.user).order_by('client_name') elif not request.user.clientordering.order: clients = UserModel.objects.filter(user_name=request.user).order_by('date') else: clients = UserModel.objects.filter(user_name=request.user).order_by('-date') clients_count = UserModel.objects.filter(user_name=request.user).count() context = { 'page': 'user_measurement_list', 'clients_count': clients_count, 'clients': clients, 'form': form } if extra_context is not None: context.update(extra_context) return render(request, template, context) clients.html {% load el_pagination_tags %} {% paginate 12 clients %} {% for client in clients %} <div class="col-md-4"> <a href="{% url 'client' client.id %}" class="blog-entry element-animate" data-animate- effect="fadeIn"> <div class="blog-content-body"> <div class="post-meta"> {% if client.image %} <span class="author mr-2"><img src="{{ client.image.url }}" alt="image"> </span>&bullet; {% elif not client.image and client.client_gender == 'Male' %} <span class="author mr-2"><img … -
Django get Deadline Date exclude weekends
How to get the exact Deadline date not the number of days in Django Models exclude weekends? My code work good but I want to exclude weekends. Deadline = models.DateTimeField(default=datetime.datetime.today() + timedelta(days=15)) -
I need to append a value in an array to another value in python
This is the current json response [ [ { "TO":"nathanoluwaseyi@gmail.com", "FROM":"johndoe@gmail.com", "SUBJECT":"This is the subject 1", "MESSAGE":[ "First Message" ], "NAME":"John Doe", "DATE":"2019-08-18 19:48:10" }, { "TO":"nathanoluwaseyi@gmail.com", "FROM":"johndoe@gmail.com", "SUBJECT":"This is the subject 2", "MESSAGE":[ "Second message" ], "NAME":"John Doe", "DATE":"2019-08-18 19:48:10" } ] ] But i want a situation whereby more than one of the response have the same FROM then, the MESSAGE should be together in this format or something like this. How do i go about this? Everything i have tried didn't work [ [ { "TO":"nathanoluwaseyi@gmail.com", "FROM":"johndoe@gmail.com", "SUBJECT":"This is the subject 1", "MESSAGE":[ "First Message", "Second Message" ], "NAME":"John Doe", "DATE":"2019-08-18 19:48:10" } ] ]