Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I thumbnail images in serialization of Django REST Framework?
I recently jumped into Django REST Framework. Before using it, I thumbnailed images using django-imagekit. Like you see the models below, it worked well, so I used original size images from image and thumbnailed size images from image_thumbnail. models.py class Image(models.Model): ... image = ProcessedImageField(null=True, blank=True, upload_to=image_path, processors=[Thumbnail(1000, 1400)], format='JPEG') image_thumbnail = ImageSpecField( source='image', format='JPEG', options={'quality': 40}) ... The problem is I can't use image_thumbnail in my serializers. I can use image, but image_thumbnail throws an error message A server error occurred. Please contact the administrator. serializers.py class ImageRandomSerializer(ModelSerializer): class Meta: model = Image fields = ('image', 'image_thumbnail', ) Can I not thumbnailed images from models.py in serializers.py? Should I thumbnail them with some Django REST Framework thumbnail tool? -
StaticFiles Django not running with Certifield Let's Encrypt
I have a python site with the django framework. On the server I use NGINX and Supervisor for Gunicorn. NGINX was serving static files without the Let's Encrypt certificate. But after I put it in, the static files are not served. What should I do? -
Django Conversion from DecimalField to Decimal is not supported
I was trying to do a cart module from youtube and I ended up encountering thise "TypeError at /store/add-to-cart/1' . And so far I am kind of stuck from this error. So, here is the code that might (?) be related to this error. my views.py : def add_to_cart(request, product_id): product = Product.get_object_or_404(pk= product_id) order_item, status = OrderItem.objects.get_or_create(product=product) user_order, status = Order.objects.get_or_create(is_ordered=False) user_order.items.add(order_item) if status: user_order.OR = generate_order_id() user_order.save() messages.Information(request, 'Item added to cart') return redirect(reverse('store:index')) -
How to add an GenericRelation field in a form in Django
I have this following error: django.core.exceptions.FieldError: 'pictures' cannot be specified for Building model form as it is a non-editable field I many models that can have many Images. So I used django's GenericRelation. But as soon as I added the 'pictures' field in forms.py. I get an error forms.py class BuildingForm(ModelForm): class Meta: model = Building fields = ['landlord', 'address', 'pictures'] models.py from stdimage.models import StdImageField class Image(TimeStampedModel, models.Model): picture = StdImageField(upload_to='pictures/%Y/%m/%d', verbose_name="pics", null = True, blank = True, variations={ 'large': (600, 400), 'thumbnail': (250, 250, True), 'medium': (300, 200), }, default='default.jpg') # Generic Foreign Key content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() class Building(TimeStampedModel, models.Model): landlord = models.ForeignKey( settings.AUTH_USER_MODEL, related_name='building_manager') address = models.CharField(max_length=50, blank=False) pictures = GenericRelation(Image, null = True, blank = True, related_query_name='dwelling_picture', verbose_name=_('Screenshots')) views.py class BuildingCreateView(SuccessMessageMixin, CreateView): form_class = BuildingForm template_name = "parking/building/building_form.html" success_message = 'Successfully Added a Post entry' success_url = reverse_lazy('parkers:building_list') def form_valid(self, form): self.object = form.save(commit=True) #self.object.author = self.request.user return super(BuildingCreateView, self).form_valid(form) parking_building_new = login_required(BuildingCreateView.as_view()) forms.html <div class="container"> <div class="row"> <div class="col-lg-10 col-lg-1-offset"> <form action="." method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit" /> </form> </div> </div> </div> trace File "/home/laptopvm/Documents/Github/django_project_tutorial_genericrelation_key/parking/urls.py", line 4, in <module> from parking.views import … -
jQuery script doesn't work when moved into a file with plain javascript
I have functioning javascript and jQuery files. I tried copying the jQuery AJAX into my other file, but It doesn't work. Instead of AJAXing, it shows me the JSON info returned without the the template it was in. ? View def customer_profile(request, pk): name = get_object_or_404(CEName, id=pk) name_form = NameForm(instance=name) return render( request, 'customer/customer_profile.html', {'name':name, 'NameForm': name_form} ) def update_profile(request, pk): if request.POST: name = get_object_or_404(CEName, id=pk) name_form = NameForm(data=request.POST, instance=name) if name_form.is_valid(): name_form.save() updated_name = get_object_or_404(CEName, id=name.id) name_json = render_to_string( 'ce_profiles/name_json.html', {'name_json': updated_name,} ) return JsonResponse({'name_json': name_json}) templates {% extends 'base.html' %} {% load static %} {% block content %} {% include 'ce_profiles/name_header.html' %} <div id="name" class="container d-flex justify-content-between pt-1"> <div id="name_json"> {{ name }} </div> <button id="update_button" class="bold btn btn-main btn-sm button-main">UPDATE</button> </div> <div id="div_NameForm" class="container" style="display: none;"> <hr size="3px"> <form id="NameForm" method="POST" action="{% url 'customer:update-profile' name.id %}"> {% csrf_token %} {{ NameForm.as_p }} <br> <button id="save_changes" type="submit" class="btn btn-main button-main btn-block">Save Changes</button> </form> </div> {% endblock %} {% block script %} <script src="{% static 'ce_profiles/ce_profiles.js' %}"></script> <script src="{% static 'ce_profiles/ce_profiles_jquery.js' %}"></script> {% endblock %} <div id="name_json"> {{ name_json }} </div> jQuery $(document).ready(function() { $("#NameForm").submit(function(event) { event.preventDefault(); $.ajax({ url: $(this).attr('action'), type: $(this).attr('method'), data: $(this).serialize(), dataType: 'json', success: function(data) … -
Can't get Django Rest Framework ViewSet to recognize user's permission
I have a model Reservation with two custom permissions reservation_can_view and reservation_can_edit: class Reservation(models.Model): UNCONFIRMED = 'UNCONFIRMED' CONFIRMED = 'CONFIRMED' CANCELED = 'CANCELED' NO_SHOW = 'NO SHOW' GO_SHOW = 'GO SHOW' STATUS_CHOICES = ( (UNCONFIRMED, _('Unconfirmed')), (CONFIRMED, _('Confirmed')), (CANCELED, _('Canceled')), (NO_SHOW, _('No show')), (GO_SHOW, _('Go show')), ) booking = models.CharField(max_length=15, verbose_name=_('Booking')) agency = models.ForeignKey(Agency, on_delete=models.PROTECT, related_name='reservations', verbose_name=_('Agency')) comment = models.TextField(null=True, blank=True, verbose_name=_('Comment')) status = models.CharField(max_length=15, choices=STATUS_CHOICES, default=UNCONFIRMED, verbose_name=_('Status')) confirmation_date = models.DateTimeField(null=True, blank=True, verbose_name=_("Confirmation Date")) arrival_date = models.DateField(verbose_name=_('Arrival Date')) departure_date = models.DateField(verbose_name=_('Departure Date')) confirmation = models.CharField(max_length=15, null=True, blank=True, verbose_name=_('Confirmation Code')) is_invoiced = models.BooleanField(default=False, verbose_name=_('Is invoiced?')) euroamerica = models.BooleanField(default=False, verbose_name=_("Is Euroamerica sale")) user = models.ForeignKey(User, null=True, blank=True, on_delete=models.PROTECT, related_name='reservations') timestamp = models.DateTimeField(null=True, blank=True, auto_now_add=True) handle_fee = models.FloatField(null=True, blank=True, verbose_name=_("Handle Fee")) class Meta: verbose_name = _('Reservation') verbose_name_plural = _('Reservations') permissions = ( ('reservation_can_edit', 'Can Edit Reservation'), ('reservation_can_view', 'Can View Reservation') ) And a ModelViewSet that validates such permissions: class ReservationCompositionPermission(permissions.BasePermission): def has_permission(self, request, view): user_permissions = Permission.objects.filter(user=request.user) print(str(user_permissions)) if request.method == 'GET': return request.user.has_perm('reservation_can_view') elif request.method in ('POST', 'PUT', 'PATCH'): return request.user.has_perm('reservation_can_edit') return False class ReservationCompositionViewSet(viewsets.ViewSet): permission_classes = (ReservationCompositionPermission,) def list(self, request, pk): reservation = models.Reservation.objects.filter(booking=pk).order_by('timestamp').last() if reservation == None: raise CustomValidation(_('There is not such Reservation: {}'.format(pk)), 'booking', status.HTTP_400_BAD_REQUEST) result_set = serializers.ReservationSerializer(reservation).data result_set['pax'] … -
Modify image uploaded in django 2.0 before the image is saved to disk
I have a model with a FileField for document uploads (e.g. images, pdfs, or videos). I use this line in my Document model: storage_file_name = models.FileField('File name', upload_to=unique_file_path) and in unique_file_path I change the name of the uploaded document to a unique file name. I find that I will be uploading some tiffs, which I need to change to jpeg or something that a browser can easily display. I have been looking for the best way to convert the uploaded tiff file to jpeg. Is there a way to do it before the image is saved to the disk, or is the best way to use a @receiver(models.signals.post_save, sender=Document) and save the converted image over the saved tiff image? At this point I am only using the admin pages and not any custom views (except by customizing the admin pages). Thanks! Mark -
How to blank a form existing value when loading?
I'm loading ModelForm to allow users to edit their profile. I have a sensitive field (like an API key) that I don't want to show the contents of. I only want users to be able to overwrite it, and not read it. So basically, without using JS, I want to blank the contents of the field. Here is what I tried, but it still is loading the APK key. self.fields['api_key'].initial = "" -
How to render django blog posts in a row?
Why my post going under? How to fix this post_detail_html {% for tag in post.tags.all %} {{ tag.name }} {% if not forloop.last %}, {% endif %} {% endfor %} {{ post.title }} {{ post.body|truncatewords:30|linebreaks }} check this image Posts going under How to make like this, in a row (3 cards) -
Django missing migrations file - how to sync db with master file?
one of my fellow developers checked out from master and created new models for our website. He ran makemigrations, then ran migrate which obviously created the tables we wanted. However, he never committed his changes to github and he altered the production database. So when I went in to add a table today, when I ran makemigrations it the terminal listed several tables that I knew already existed...I was like "YOLO!" and ran the migrate command anyways and it puked. So, since the migrations file isn't in my migrate folder, django thinks it needs to create those tables...then it goes to create them and pukes because they're already there. The other developer is out of town visiting family and can't commit the file. How do I get this set straight? I think I need to run ./manage.py migrate my_app --fake But I don't completely understand what that does so I don't want to take the YOLO route and really mess things up... -
How to match Questions with Answers in django
Please explain me how to match the Answer of a particular Question in django. Right Now I am facing the issue that whatever the user inputs in the form if it exits in Answer database it returns True, But what I want is that whatever the user inputs should be matched with the Answer of that particular Question and not any of the Answers present. models.py from django.db import models from django.contrib.auth import get_user_model from PIL import Image User=get_user_model() # Create your models here. class Question(models.Model): question_name=models.CharField(max_length=20,unique=True,default=' ') question_image=models.ImageField(upload_to='levels/') question_text=models.TextField(blank=True,max_length=100) def __str__(self): return str(self.question_name) class Meta: ordering= ["question_name"] class Answer(models.Model): question_relation=models.ForeignKey(Question,on_delete=models.CASCADE) answer=models.CharField(max_length=100,unique=True) def __str__(self): return self.answer forms.py from django import forms from .models import Answer,Question from django.core.exceptions import ObjectDoesNotExist from . import views class CheckAnswer(forms.Form): your_answer=forms.CharField(label='Answer') def clean(self): cleaned_data=super(CheckAnswer,self).clean() response=cleaned_data.get("your_answer") try: p = Answer.objects.get(answer__iexact=response) except Answer.DoesNotExist: raise forms.ValidationError("Wrong Answer.") views.py from django.shortcuts import render,redirect,get_object_or_404 from django.views.generic import * from . import models from django import forms from .forms import CheckAnswer from django.contrib.auth.decorators import login_required from .models import Question from dashboard.models import UserLoggedIn # Create your views here. @login_required def Arena1(request): if request.method=='POST': form = CheckAnswer(request.POST) if form.is_valid(): return redirect('thanks') else: form=CheckAnswer() args={'form':form} return render(request,'levels/arena1.html',args) I think the concept of pk … -
Django HttpResponse: Download Excel After User Clicks a Button
In my Django project, I need to send an in-memory Excel file to the client side for download. The download should start after the user clicks a button. I've this code in app/views.py so far: import pandas as pd from io import BytesIO as IO from django.http import HttpResponse import xlsxwriter def write_to_excel(): df_output = pd.DataFrame({'col1': ['abc', 'def'], 'col2': ['ghi', 'jkl']}) # my "Excel" file, which is an in-memory output file (buffer) # for the new workbook excel_file = IO() xlwriter = pd.ExcelWriter(excel_file, engine='xlsxwriter') df_output.to_excel(xlwriter, 'sheetname') xlwriter.save() xlwriter.close() # rewind the buffer excel_file.seek(0) # set the mime type so that the browser knows what to do with the file response = HttpResponse(excel_file.read(), content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') # set the file name in the Content-Disposition header response['Content-Disposition'] = 'attachment; filename=myfile.xlsx' return response Here's my HTML file: <!DOCTYPE html> <html> <head> <title>Generate Data</title> </head> <body> <form method="post"> <!-- {% csrf_token %} {{ form.as_p }} --> <input type="submit" value="Excel"> </form> </html> </body> The above code is working and downloading an Excel file with correct data as soon as I run the app. I want it to wait until the user clicks the Excel button and then download the spreadsheet. How could I achieve this? I'm new … -
Django 2.1 - can't link my models variables in html file
guys, first of all thanks for your time. im having some problems to design my templates files in django 2.1 at the index.html of my app i can get in at the details page although when i want to design my detail page in the html file i put the references but the browser gives me nothing. MY MODELS.PY from django.db import models class Dreams (models.Model): titulo = models.CharField(max_length=100) objetivo = models.CharField(max_length=100) imagem = models.CharField(max_length=100) def __str__(self): return self.titulo + ' - ' + self.objetivo class Wich (models.Model): lets = models.ForeignKey(Dreams, on_delete=models.CASCADE) make = models.CharField(max_length=100) it = models.CharField(max_length=100) def __str__(self): return self.make MY VIEWS.PY from django.http import HttpResponse, Http404 from .models import Dreams, Wich from django.template import loader from django.shortcuts import render def index(request): all_dreams = Dreams.objects.all() contexto = {'all_dreams': all_dreams} return render(request, 'index.html', contexto) def detail(request, Dreams_id): try: titulo = Dreams.objects.get(pk=Dreams_id) contexto = {'titulo': titulo} except Dreams.DoesNotExist: raise Http404("sem sonhos") return render(request, 'detail.html', contexto) MY detail.html FILE <img src = {{ dreams.imagem }}> <h2>{{ titulo }}</h2> <h3>{{ wich.make }}</h3> but the only thing that i get is the 'titulo' in . i've tried to create variables in views for 'imagem' and 'make' and got nothing. again thanks for your … -
django queryset aggregation count counting wrong thing
This is a continuation question from: Django queryset get distinct column values with respect to other column My Problem: Using aggregate count in django counts the wrong thing in the queryset, or as far as I can see something that is not even in my queryset. What I did I used: queryset.order_by('col1', 'col2').distinct('col1', 'col2').values('col2') to get the values of col2 of a model where all the rows have a distinct pair of values in (col1, col2). There is an example in the link above. I printed my queryset and it looks good, I have [{col2: value1}, ... , {col2: value1},{col2: value2}, ..., {col2: value2},...]. I now want to count how much each value appears in the queryset I got. I do this using aggregation count. I have: a = {'count': Count(F(col2), distinct=False)} queryset.annotate(**a) I tried this with ``distinct=True` as well but no luck I would expect to get [{col2:value1, count: num1}, {col2:value2, count: num2} ...]. Instead I get [{col2: value1, count: num11}, {col2: value1, count: num12}, ... ,{col2: value1, count: num_1n}, {col2: value2, count: num21}, ... ,{col2: value1, count: num_2n}, ...] Where as far as I can tell num11, ...., num_1n are the amount of lines value1 existed in col2 … -
Missing filterset object in context using django-tables2 and django-filter
I have been trying to create a view with filter-bar and a table of users. I am using django-tables2 and django-filter libraries and I have this view: class UserListView(SingleTableView, FilterView): model = User template_name = 'admin/users.html' table_class = AdminUserTable filterset_class = UserFilter paginate_by = 10 However the problem is that there is no filterset object in data-context sent to template, nor there is no filterset object in self of UserListView. I was trying to replace SingleTableView, FilterView to FilterView, SingleTableView and then it passes filterset object under filter key in context to the template, however in this case when I visit a page with no filter parameters in url it shows empty list. But If I put a ?search= in url it shows all users and filtering works fine. -
Django Debug Toolbar 1.10 (and 1.10.1) Not Showing
I've got django-debug-toolbar 1.9.1 working fine in my configuration (Django 2.1.2), but if I simply update it to 1.10 or 1.10.1, without changing anything else, it doesn't show up anymore. I don't see anything in the change logs that indicate I need to update any settings. Does anyone have any suggestions? Or there a way I can turn on some kind of logging to see where it's not working? Thanks! -
fatal: bad numeric config value 'true{/code}' for 'credential.usehttppath': invalid unit
Can anyone help me to solve this error as while git using git clone I found this error. By mistake I added true {/code} true now unable to solve this error -
Django password reset email link redirects to login page
I am using custom forms to override the Django templates but when a user clicks reset password and receives the email with the password reset link, etc /reset/OA/50l-94673624f6b9fa5a060a/ When the link is clicked it redirects to /account/login/ It should be directing them to /reset-password/confirm/ and then to /reset-password/complete/ The command line looks like this when reset link is clicked GET /reset/OA/50l-94673624f6b9fa5a060a/ HTTP/1.1" 302 0 GET /account/login/ HTTP/1.1" 200 2237 urls.py app_name='accounts' from django.conf.urls import url from . import views from django.contrib.auth.views import LoginView, LogoutView, PasswordResetView, PasswordResetDoneView, PasswordResetConfirmView, PasswordResetCompleteView from django.conf import settings from django.conf.urls.static import static from django.urls import reverse_lazy urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^login/$', LoginView.as_view(template_name='accounts/login.html'), name='login'), url(r'^logout/$', LogoutView.as_view(template_name='accounts/logout.html'), name='logout'), url(r'^register/$', views.register, name='register'), url(r'^profile/$', views.view_profile, name='view_profile'), url(r'^profile/edit$', views.edit_profile, name='edit_profile'), url(r'^change-password/$', views.change_password, name='change_password'), url(r'^reset-password/$', PasswordResetView.as_view(template_name='accounts/reset_password.html', success_url=reverse_lazy('accounts:reset_password_done')), {'email_template_name': 'accounts/reset_password_email.html'}, name='reset_password'), url(r'^reset-password/done/$', PasswordResetDoneView.as_view(template_name='accounts/reset_password_done.html'), name='reset_password_done'), url(r'^reset-password/confirm/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>,+)/$', PasswordResetConfirmView.as_view(template_name='accounts/reset_password_confirm.html'), name='reset_password_confirm'), url(r'^reset-password/complete/$', PasswordResetConfirmView.as_view(template_name='accounts/reset_password_complete.html'), name='reset_password_complete'), ] settings.py INSTALLED_APPS = [ 'accounts', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] middleware.py import re from django.conf import settings from django.urls import reverse from django.shortcuts import redirect from django.contrib.auth import logout EXEMPT_URLS = [re.compile(settings.LOGIN_URL.lstrip('/'))] if hasattr(settings, 'LOGIN_EXEMPT_URLS'): EXEMPT_URLS += [re.compile(url) for url in settings.LOGIN_EXEMPT_URLS] class LoginRequiredMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response … -
UUIDs in Django fixtures
I have an UUIDField as the primary key for some model. In Django fixtures, how should I code the UUID PK value? What is the string format for the pk in this case? Please provide an example. -
AWS: 100.0% of all requests to elb are failing with HTTP 5xx
I don't know what causes this when I run the file Django app locally everything works. Django is in my requirements.txt file and should thus also be imported on the EB instance. I am new to elastic beanstalk and was in general. Please help. Here is my log output: [Sat Oct 20 12:38:08.627716 2018] [:error] [pid 29084] [remote 5.18.188.248:204] mod_wsgi (pid=29084): Target WSGI script '/opt/python/current/app/backend/backend/wsgi.py' cannot be loaded as Python module. [Sat Oct 20 12:38:08.627821 2018] [:error] [pid 29084] [remote 5.18.188.248:204] mod_wsgi (pid=29084): Exception occurred processing WSGI script '/opt/python/current/app/backend/backend/wsgi.py'. [Sat Oct 20 12:38:08.627973 2018] [:error] [pid 29084] [remote 5.18.188.248:204] Traceback (most recent call last): [Sat Oct 20 12:38:08.628023 2018] [:error] [pid 29084] [remote 5.18.188.248:204] File "/opt/python/current/app/backend/backend/wsgi.py", line 12, in <module> [Sat Oct 20 12:38:08.628037 2018] [:error] [pid 29084] [remote 5.18.188.248:204] from django.core.wsgi import get_wsgi_application [Sat Oct 20 12:38:08.628077 2018] [:error] [pid 29084] [remote 5.18.188.248:204] ModuleNotFoundError: No module named 'django' [Sat Oct 20 12:38:14.079664 2018] [:error] [pid 29084] [remote 5.18.188.248:2512] mod_wsgi (pid=29084): Target WSGI script '/opt/python/current/app/backend/backend/wsgi.py' cannot be loaded as Python module. I also have a Django.config and a python.config in my .ebextensions folder django.config: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: backend/backend/wsgi.py python.config: option_settings: - namespace: aws:elasticbeanstalk:container:python option_name: WSGIPath value: backend/backend/wsgi.py - option_name: DJANGO_SETTINGS_MODULE … -
Django password_reset/done page overriding my custom URL
I am working on the password reset area of my registration using custom html so am overriding Django's password reset pages. The reset password initial link works fine and redirects to my custom URL: /account/reset-password/ There a user can enter their email address and click submit to receive a password reset email. The next page shown should be /account/reset-password/done/ However when they click submit, I can see from the command line: POST /account/reset-password/ HTTP/1.1" 302 0 GET /password_reset/done/ HTTP/1.1" 302 0 GET /account/login/ HTTP/1.1" 200 2237 The 2nd line should be going to /account/reset-password/done/ not /password_reset/done/ urls.py app_name='accounts' from django.conf.urls import url from . import views from django.contrib.auth.views import LoginView, LogoutView, PasswordResetView, PasswordResetDoneView, PasswordResetConfirmView, PasswordResetCompleteView from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^login/$', LoginView.as_view(template_name='accounts/login.html'), name='login'), url(r'^logout/$', LogoutView.as_view(template_name='accounts/logout.html'), name='logout'), url(r'^register/$', views.register, name='register'), url(r'^profile/$', views.view_profile, name='view_profile'), url(r'^profile/edit$', views.edit_profile, name='edit_profile'), url(r'^change-password/$', views.change_password, name='change_password'), url(r'^reset-password/$', PasswordResetView.as_view(template_name='accounts/reset_password.html'), {'post_reset_redirect': 'accounts:reset_password_done', 'email_template_name': 'accounts/reset_password_email.html'}, name='reset_password'), url(r'^reset-password/done/$', PasswordResetDoneView.as_view(template_name='accounts/reset_password_done.html'), name='reset_password_done'), url(r'^reset-password/confirm/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>,+)/$', PasswordResetConfirmView.as_view(template_name='accounts/reset_password_confirm.html'), name='reset_password_confirm'), url(r'^reset-password/complete/$', PasswordResetConfirmView.as_view(template_name='accounts/reset_password_complete.html'), name='reset_password_complete'), ] settings.py INSTALLED_APPS = [ 'accounts', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] middleware.py import re from django.conf import settings from django.urls import reverse from django.shortcuts import redirect from django.contrib.auth import logout EXEMPT_URLS = [re.compile(settings.LOGIN_URL.lstrip('/'))] if hasattr(settings, … -
Error at start through .sh file: gunicorn: command not found
I want to run my server through the .sh file. But I ran into an error with a gunicorn. gunicorn: command not found gunicorn: command not found I have installed gunicorn 19.9.0. But if run without the .sh file, only this command, the server will sart. My command: gunicorn -c gunicorn_conf.py my_project.wsgi How fixed this. Thanks -
design model with draft and multiple preview instances
I want to have User and Articles for each user with this features: user can create Article user can change Article at any time. user can submit Article for review at any time admin can review submitted Articles. admin can publish Article which she reviewed before. So we have multiple instances of one Article at the moment. How i should design models for satisfying the requirements?I'm looking for best case. -
How to extend template from project templates folder in app in Django?
I've added the allauth package to my Django project. I tried extending a template from the project template folder, but it didn't work. It keeps giving me a 'template does not exist' error. Any idea how to solve this? my-project app1 account login.html app2 templates base.html settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'app1', 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] my-project/app1/account/login.html {% extends 'base.html' %} {% load static %} {% block content %} <!-- ========== MAIN ========== --> <main id="content" role="main"> ... -
Django queryset get distinct column values with respect to other column
I am using django orm and I am trying to get all the values of a column, but only if a different column is unique with respect to it. Its hard to explain, so here is an example: q | a | 1 w | s | 2 e | a | 3 q | a | 4 w | s | 5 e | a | 6 I would like to get all the values that are in column 2 but if they also have the same value in column 1 don't take duplicates. So in this case I want to get [a,s,a]. (column 3 only serves to show why these duplicates don't get merged in the first place). What I tried: I tried grouping by values of columns 1 and 2 and taking the distinct value of it, thus I would end up with: q | a w | s ---> which is actually given as [(q,a),(w,s),(e,a)] e | a with the code: queryset.values(col1,col2).distinct() but I only want the second column so I then added .values(col2). The problem with that is the distinct gets applied to the results of the second values as well as the first, so …