Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Setting up a custom workflow for the edit model form view
Context I have a model, let's call it Application. class Application(models.Model): # various fields here status = status = models.CharField( max_length=100, choices=APPLICATION_STATUSES, default=PENDING_STATUS[0], ) assigned_operator = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.PROTECT, editable=True, null=True, ) This model has some fields, but the ones we care here are the status, which is simply a choice field, and the assigned_operator field, which defines a 1-1 relationship with a User instance. This model also has its corresponding ApplicationAdmin view defined. Description The requirement is that when trying to edit an Application, from the admin view, the default workflow, where you make whatever changes you want and then simply save the form, should be replaced with the following workflow: The application form is readonly unless the user is the assigned_operator of the application, in which case the application is editable. When the user is not the application's assigned_operator the actions at the bottom will be 1 button: "Assign to myself" - When clicked the Application model is updated to reference the current user as its assigned_operator and the page refreshes When the user is the application's assigned_operator the actions at the bottom will be 3 buttons: "Save changes" - Does what default "Save" button does "Reject" - … -
Queries on multiple fields, each with a custom method, with django-filter
I have this filter: class MsTuneFilter(django_filters.FilterSet): def all_titles(self, queryset, name, value): return MsTune.objects.filter( Q(name__icontains=value) | Q(title__icontains=value) | Q(alt_title__icontains=value) ) def ind_1(self, queryset, name, value): return MsTune.objects.filter( Q(index_standard_1__startswith=value) | Q(index_gore_1__startswith=value) | Q(alt_index_gore_1__startswith=value) | Q(alt_index_standard_1__startswith=value) ) title = django_filters.CharFilter(method='all_titles', label="All title fields") index_standard_1 = django_filters.CharFilter(method='ind_1', label="Index 1") class Meta: model = MsTune fields = ['index_standard_1', 'title', ....] It all works well when I'm making queries which do not involve both 'title' and 'index_standard_1'. Nevertheless, if I'm searching for something with a specific title AND with a specific index, the index search is ignored, i.e. the query returns all the indexes, ignoring my search. What am I overlooking? -
name 'serializer' is not defined
I'm trying to build an API on Django REST framework but when I try to use the POST method I get this error: name 'serializer' is not defined This is the API view: class apiOverview(APIView): serializer_class = serializers.EmailsSerializer def get(self, request, format=None): an_apiview = [ ] return Response({'message':'Hello!', 'an_apiview': an_apiview}) def post(self, request): serializer_class = self.serializer_class(data=request.data) if serializer.is_valid(): url = serializer.validated_data.get('url') message = f'The url is {url}' return Response({'message': message}) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) The error is in this line particularly when trying to validate: if serializer.is_valid(): url = serializer.validated_data.get('url') message = f'The url is {url}' return Response({'message': message}) All apps are correctly installed. -
Error trying to attach an image to an email with DRF
I'm trying to attach an image in a email that i send in a task with celery Im working with Django Rest Framework This are my task.py from celery import shared_task from email.mime.image import MIMEImage from django.contrib.staticfiles import finders from django.template.loader import get_template from django.core.mail import EmailMultiAlternatives @shared_task def send_new_dispatch_guide_email_task(**kwargs): subject = kwargs['subject'] from_email = 'contact@ecmat.cl' to = kwargs['email'] email_context = { 'name': kwargs['name'], 'button_msg': kwargs['button_msg'], 'button_link': kwargs['button_link'], 'subject': subject, 'text': kwargs['text'], 'entity_in_question': kwargs['entity_in_question'], 'after_text': kwargs['after_text'], 'purchase_order_code': kwargs['purchase_order_code'], 'dispatch_guide_code': kwargs['dispatch_guide_code'], 'provider_name': kwargs['provider_name'], 'withdrawal_address': kwargs['withdrawal_address'], 'destination_address': kwargs['destination_address'], 'items_quantity': kwargs['items_quantity'], 'withdrawal_date': kwargs['withdrawal_date'], 'withdrawal_time': kwargs['withdrawal_time'], 'goto_link': kwargs['goto_link'] } text_content = "" html = get_template('dispatch_guide.html') html_content = html.render(email_context) msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.attach(logo_data(file_name='linkedin.png', image_id='1')) msg.attach(logo_data(file_name='twitter.png', image_id='2')) msg.attach(logo_data(file_name='youtube.png', image_id='3')) msg.attach(logo_data(file_name='image_2.png', image_id='4')) msg.attach(logo_data(file_name='image_5.png', image_id='5')) msg.attach(logo_data(file_name='logoemail_2.png', image_id='6')) msg.send() return None @shared_task def send_new_dispatch_guide_email_provider_task(**kwargs): subject = kwargs['subject'] from_email = 'contact@ecmat.cl' to = kwargs['email'] email_context = { 'name': kwargs['name'], 'subject': subject, 'text': kwargs['text'], 'entity_in_question': kwargs['entity_in_question'], 'after_text': kwargs['after_text'], 'purchase_order_code': kwargs['purchase_order_code'], 'dispatch_guide_code': kwargs['dispatch_guide_code'], 'withdrawal_address': kwargs['withdrawal_address'], 'destination_address': kwargs['destination_address'], 'items_quantity': kwargs['items_quantity'], 'withdrawal_date': kwargs['withdrawal_date'], 'withdrawal_time': kwargs['withdrawal_time'] } text_content = "" html = get_template('dispatch_guide_provider.html') html_content = html.render(email_context) msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.attach(logo_data(file_name='linkedin.png', image_id='1')) msg.attach(logo_data(file_name='twitter.png', image_id='2')) msg.attach(logo_data(file_name='youtube.png', image_id='3')) msg.attach(logo_data(file_name='image_2.png', image_id='4')) msg.attach(logo_data(file_name='image_5.png', image_id='5')) msg.attach(logo_data(file_name='logoemail_2.png', image_id='6')) msg.send() return None def … -
How to create reusable components for UI in Django
I am building a project in Django which has 5 different applications inside it. Some applications are falling under same pattern and some are not. Can I create a UI components using bootstrap on the top of all these applications to reuse over the entire project. Any help would be appreciated.. Thanks in advance -
Django register form
so, I made the registration page with django and it doesn't show the form register.html <form method="post"> {{ form.as_table }} {% csrf_token %} <input type='submit' value="Register"> </form> and this is the views.py from django.shortcuts import render, redirect from django.http import HttpResponse from django.contrib.auth.forms import UserCreationForm def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() return redirect('login') else: form = UserCreationForm() return render(request, 'register.html', { 'form ' : form}) def login(request): return render(request, 'login.html') And all it shows is the register button -
pip installing does not install to virtualenv
I'm very new to all of this, so bear with me. I started, and activated, a virtual environment. But when I pip install anything, it installs to the computer, not the the virtual env. I'm on a Mac, trying to build a Django website. Example: With the virtual machine activated. I type: python -m pip install Django Then I can deactivate the virtual env, and type: pip freeze And it will list out the freshly installed version of Django. Any clue as to why this is happening? -
Django Template Broke When Model Field Type Changed From CharField to ForeignKey
I had a set of templates that all start with the same object_list. The first (reviews_list) displays every item in the object list. The rest of them display a subset of the items based on an attribute: {% if review.library == "Movies" %}. This worked fine until I changed the Review model. Where library used to be a CharField, it's now a ForeignKey, though the name of the field did not change. reviews_list still renders properly but all of the other templates are showing empty. I have tried both of the following and everything's still empty. On library's pk as a string: {% if review.library == "1" %} On library's pk as an int: {% if review.library == 1 %} I had wiped the database before doing the migration, then repopulated, so there shouldn't be any weird data issues. The template is pretty short, so pasting it below. How can I get items to display in the template based on the value of a field that's an fk? Thanks {% extends 'base.html' %} {% block title %}TV Reviews{% endblock title %} {% block content %} <h1 class="jumbotron-fluid">List Of TV Reviews</h1> {% for review in object_list %} {% if review.library == … -
Why django changes timezone while creating Post Model?
def test_post_order_positioning_by_date(self): Post.objects.create( body="test", date_added="2020-12-31 18:51:19.959463+01:00", author=self.user, uniqueID="61672dba-0d36-43b1-b36a-bbd0a3d317b5", image="" ) post = Post.objects.get(uniqueID="61672dba-0d36-43b1-b36a-bbd0a3d317b5") print(post.date_added) This function when printig post.date_added show code below: 2020-12-31 17:51:19.959463+00:00 Here is the model code: class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='author') body = models.TextField(max_length=500, default="") date_added = models.DateTimeField(auto_now_add=False) image = models.ImageField(default=None, upload_to="posts/") uniqueID = models.UUIDField(unique=True, max_length=255, primary_key=True) def __str__(self): return str(self.uniqueID) def pre_save_post_receiver(sender, instance, **kwargs): print(sender, instance) pre_save.connect(pre_save_post_receiver, sender=Post) Any idea why this happens? I tried overide_settings and changins timezone for this function and django module timezone with timezone.localtime(timezone.now()) but both of these attempts failed. -
Python: Matplotlib Animation in Django
This is more a question of asking for guidance than to solve a specific problem. I am trying to display a live graph constructed with matplotlib's animation feature in Django, however I am stuck and do not know how to approach this. If someone has advice, it would be greatly appreciated. -
Ajax Validation stops after first use with model django form
I have a model form in django that I am rendering on the front end and validating with Ajax. but the Validation works only once which is the first time I visit the page. If I submit the form again, I don't get any response from Ajax. Here is the code: $(document).ready(function(e) { $('#new_order').submit(function(e) { // On form submit event $.ajax({ // create an AJAX call... data: $(this).serialize(), // get the form data type: $(this).attr('method'), // GET or POST url: $(this).attr('action'), // the file to call success: function(response) { // on success.. if (response.success) { document.getElementById("new_order").reset(); $('.message').html(response.success); setTimeout(function(){ $('.message').hide() }, 1000) } else if(response.err_code == 400){ for(var key in response.error){ document.getElementById("new_order").reset(); $('.message').html(response.error[key][0]); setTimeout(function(){ $('.message').hide() }, 1000) }} }, error : function(xhr,errmsg,err) { console.log(xhr.status + ": " + xhr.responseText); } }); return false; }); e.preventDefault(); }); While the views.py is this: @login_required def counter(request): message = {} user = request.user if user.user_type != 'counter_staff' and user.user_type != 'manager': message = 'You are not authorized to view this page' return render(request, 'counters.html', {'message' : message}) else: form = NewOrderForm if request.method == 'POST': form = NewOrderForm(request.POST) if form.is_valid(): new_order = form.save(commit=False) new_order.taken_by= user new_order.order_date_time = datetime.now() new_order.save() message['success'] = 'Order Taken Successfully' … -
Display Django Foreign key on webpage
I have three models. class Supplier(models.Model): name = models.CharField(max_length=200, null=True) class Order(models.Model): supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) class Product(models.Model): supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE, null=True, blank=True) on_order = models.ForeignKey(Order, on_delete=models.CASCADE, null=True, blank=True) I can display a table of all the products of a given order. However, I cannot seem to render the name of that supplier on the html page like <h4> Supplier: {{order.supplier}}</h4> this is the view: def PurchaseOrder(request, pk_order): orders = Order.objects.get(id=pk_order) products = Product.objects.filter( on_order_id=pk_order).prefetch_related('on_order') total_products = products.count() supplier = Product.objects.filter(on_order_id=pk_order).prefetch_related('on_order') context = { 'supplier': supplier, 'products': products, 'orders': orders, 'total_products': total_products, } return render(request, 'crmapp/purchase_order.html', context) I've tried so hard... and didn't get very far. Please help... -
Mongodb aggregations with django
i am trying to develop a mongodb aggregation with django and python. I have an atlas server with a database named 'sucre' with a collection named 'bdua' In settings.py i have: DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'morfeeweb', 'ENFORCE_SCHEMA': False, 'CLIENT': { 'host': 'mongodb+srv://xxxxxx:xxxxxx@xxxxx.xxxxx.xxxxxx.mongodb.net/morfeeweb?retryWrites=true&w=majority', 'port': 27017, 'username': 'xxxxxx', 'password': 'xxxxxxxx', 'authSource': 'admin', 'authMechanism': 'SCRAM-SHA-1' }, 'LOGGING': { 'version': 1, 'loggers': { 'djongo': { 'level': 'DEBUG', 'propagate': False, } }, }, }, 'sucre': { 'ENGINE': 'djongo', 'NAME': 'sucre', 'ENFORCE_SCHEMA': False, 'CLIENT': { 'host': 'mongodb+srv://xxxx:xxxxxx@xxxxx.xxxxx.xxxx.mongodb.net/sucre?retryWrites=true&w=majority', 'port': 27017, 'username': 'xxxxx', 'password': 'xxxxxxxx', 'authSource': 'admin', 'authMechanism': 'SCRAM-SHA-1' }, 'LOGGING': { 'version': 1, 'loggers': { 'djongo': { 'level': 'DEBUG', 'propagate': False, } }, }, } } views.py from django.contrib.auth.decorators import login_required from django.shortcuts import render from django.http import HttpResponse, JsonResponse from random import randint from django.db import connection @login_required(login_url='/admin/login') def consolidado(request): aggretation_sample = connection['sucre'].db.bdua.aggregate([ { '$match': {'estado': 'AC', 'regimen': 'subsidiado'} }, { '$group': { '_id': '$cod_EPS', 'Afiliados': {'$sum': 1}} }, { '$sort': {'Afiliados': -1} } ]) return HttpResponse(aggretation_sample) It returns 'TypeError at /aseguramiento/ 'DefaultConnectionProxy' object is not subscriptable' Help please -
Jinja for loop is not working after adding qs to iterator. Django
In my project I am using django-filter and when I am adding .qs to {% for product in products %} {% for product in products.qs %}. In the template result filters are displaying, but products are not. Here are my files. html <form method="get"> {{ filterA.form.as_p }} {{ filterB.form.as_p }} <input type="submit" value="Press" class="filter-go"> </form> {% for product in products.qs %} <div class="product" onclick="location.href='{% url 'items' product.id %}'"> <img src="{{product.image.url}}" alt="Img is not found ("> <p class="product-title">{{ product.title }}</p> <b><p class="product-price">{{ product.price }} &#8381;</p></b> </div> {% endfor %} views.py def index(request): con = { 'services': Service.objects.all(), 'products': Product.objects.all(), 'galery': GaleryImage.objects.all(), 'product_types': Category.objects.all(), 'filterA': FilterA(request.GET, queryset=Product.objects.all()), 'filterB': FilterB(request.GET, queryset=Product.objects.all()), } return render(request, 'index.html', con) def product(request, pk=None): try: a = Product.objects.get(id=pk) except: return render(request, 'error404.html') context = { 'id': pk, 'product': a, } return render(request, 'product.html', context) filters.py class FilterA(django_filters.FilterSet): class Meta: model = Product fields = ['category'] class FilterB(django_filters.FilterSet): CHOICES = ( ('ascending', 'По дате (А-Я)'), ('descending', 'По дате (Я-А)'), ) CHOICES2 = ( ('price_low', 'По цене по возрастанию'), ('price_high', 'По цене по убыванию'), ) orderDate = django_filters.ChoiceFilter(choices=CHOICES, method='filter_by_date', label='') orderPrice = django_filters.ChoiceFilter(choices=CHOICES2, method='filter_by_price', label='') class Meta: model = Product fields = { 'price': ['lt', 'gt'], } def filter_by_date(self, queryset, … -
supervisor does not start process (django server with waitress) as user
I have added the username=myname in the supervisor config files. Then I executed: sudo supervisorctl reread all sudo supervisorctl reload all sudo supervisorctl restart all And then I killed all the running processes to make sure they are restarted with the new config. However, one of my processes, a django server, keeps starting as root. Why is it not starting under the respective username? ps aux | grep server.py > root 4286 19.2 0.5 1336924 180920 ? Sl 17:22 0:02 python server.py server.py: from waitress import serve from omics_server.wsgi import application if __name__ == '__main__': serve(application, port='8123', url_scheme='https', threads=12, max_request_body_size=20*1073741824) -
Can I upload my Python Django web app on Cpanel without buying and installing Cloud Linux
Hey guys i have made my django project successfully and I was ready to upload my django project to cpanel Linux shared Hosting which I bought but when I searched on Google on how to upload Django project to cpanel I found that there is a option in cpanel called Setup Python App which gives us features to upload Python Apps and this option is only shown on cpanels which have CloudLinux but I don't have CloudLinux and it is paid. My cpanel is only showing me Application Manager kind of thing under Software Option which I think could be an alternative to upload my app. Am I right, can I really do that with Application manager thing or is there any free way to upload my Django App on my bought cpanel. I bought Linux shared hosting in cpanel and bought a domain too. Please Help. -
What does request.GET.get('page') mean?
What does request.GET.get('page') mean? Also can someone explain what is happening here: def post_list(request): object_list = Post.published.all() paginator = Paginator(object_list, 3)# 3 posts in each page page = request.GET.get('page') try: posts = paginator.page(page) except PageNotAnInteger: # If page is not an integer deliver the first page posts = paginator.page(1) except EmptyPage: # If page is out of range deliver last page of results posts = paginator.page(paginator.num_pages) return render(request, 'blog/post/list.html', {'page': page, 'posts': posts}) -
Can I upload Django project on Cpanel without CloudLinux installed
Hey guys i have made my django project successfully and I was ready to upload my django project to cpanel Linux shared Hosting which I bought but when I searched on Google on how to upload Django project to cpanel I found that there is a option in cpanel called Setup Python App which gives us features to upload Python Apps and this option is only shown on cpanels which have CloudLinux but I don't have CloudLinux and it is paid. My cpanel is only showing me Application Manager kind of thing under Software Option which I think could be an alternative to upload my app. Am I right, can I really do that with Application manager thing or is there any free way to upload my Django App on my bought cpanel. I bought Linux shared hosting in cpanel and bought a domain too. Please Help. -
Django db_index=True and Meta Indexes in Django 3.1 and PostgreSQL: what is the difference and what is best practice
There is a pretty old question about it here and I don't think it quite answers the difference and what should be used: Database indexes in Django 1.11: difference between db_true, indexes and index_together At any rate, there is: db_index. For example: test_int = models.IntegerField(db_index=True) Meta models.Index class Meta: indexes = [ models.Index(fields=['last_name', 'first_name']), models.Index(fields=['first_name'], name='first_name_idx'), ] I guess I'm not seeing entirely what the benefit is of one over the other and what the convention is for use. There is nothing explicitly saying the documentation. I guess it is easier to read using models.Index Suggestions? -
Is it worth to learn Flask? How powerful is that?
I learned Python and i would like to use it and make money with that. I worked with django about a few days but i didn't like that. Should i learn Flask? Can I make good websites with Flask? Is it worth to learn? -
Django get filename without url
I get a file with this commannd: src = request.POST.get('src', '') But the output is: https://url.com/path/filename.jpg How can I just get path/filename.jpg? regards Christopher -
Why custom RESTful Django Authentication triggers AttributeError :- Exception Value: 'PasswordInput' object has no attribute 'startswith'
I was working on a Signup Page, where REST API Authentication is used. superuser created as username:foo and password:bar but when i run the server, and tries to login in Django admin. password = forms.CharField(widget=forms.PasswordInput()) ** This is the Error throw ** Error Page -
Django: Pass LDAP Credentials to 3rd Party SDK
I'm new to Django and developing an app for internal use. I have configured it with the django_auth_ldap module for authenticating to LDAP. Once the user has authenticated there are automation tasks for them to execute that use 3rd party SDKs (also LDAP auth required). Below is a simple function in my views.py config that will create a session using the SDK, but is there a way to pass the authentication of the user to the function? views.py def create_session(hostname, username, password): """Create an API Session using an SDK.""" session = SDK(hostname, username=username, password=password) return session @login_required def list_info(request): if request.method == 'POST': form = Form(request.POST) if form.is_valid(): session = create_session(form.cleaned_data['host'], ?username?, ?password?) host_info = session.get() note = 'Information from {}: '.format(form.cleaned_data['host']) dataset = pd.json_normalize(host_info) session.invalidate_cookie() else: note = 'API call has failed. Try again.' return render(request, 'list_info.html', {'form':form, 'note':note, 'dataset':dataset.to_html(index=False, justify='left', classes='table table-stripe')}) else: form = Form() return render(request, 'list_info.html', {'form':form}) I originally created CLI apps using the click module but have been trying to convert them to Django. Is there an easier approach to this? -
Page not found error in django where it is not supposed to rise
I am building a video player app in django. But, when going to the register route, I get this error: Page not found (404) Request Method: GET Request URL: http://localhost:8000/users/login/%7B%25%20url%20'register'%20%7D I don't even have a url called users/login/register. And I have checked my urls.py. Here it is: urlpatterns = [ path('register/',views.register,name='register'), ] And here is the link that leads to this route: <a href="{% url 'register' }">Register</a> I have built many apps with django but have never encountered an error like this. Why am I getting this error? -
How can I return a redirect and file in Django
I'm working on a form that when submitted has the option to export a PDF. This is great but I would also like to be able to return a new URL for the user to be redirected to as well as downloading the file. Something that combines render() or redirect() with FileResponse()