Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ImportError after installing djangocms-blog: cannot import name 'python_2_unicode_compatible' from 'django.utils .encoding'
I currently installed django-cms and djangocms-blog. When I run migrate, it throws the following error. Some ressources suggest to install six, which however is already satisfied in my venv. I use the latest Python, pip and django versions. These are the guides I followed to set up djangocms and djangocms-blog. Any solution to this? Requirement already satisfied: webencodings in c:\users\jonas\appdata\local\prog rams\python\python38-32\lib\site-packages (from html5lib>=0.999999999->djangocms -text-ckeditor>=3.5->djangocms-blog) (0.5.1) Requirement already satisfied: asgiref~=3.2 in c:\users\jonas\appdata\local\prog rams\python\python38-32\lib\site-packages (from django>=1.1->django-taggit-templ atetags->djangocms-blog) (3.2.3) Requirement already satisfied: sqlparse>=0.2.2 in c:\users\jonas\appdata\local\p rograms\python\python38-32\lib\site-packages (from django>=1.1->django-taggit-te mplatetags->djangocms-blog) (0.3.0) Collecting django-js-asset Downloading django_js_asset-1.2.2-py2.py3-none-any.whl (5.8 kB) Building wheels for collected packages: djangocms-text-ckeditor, django-taggit-t emplatetags, django-filer, easy-thumbnails, django-sekizai, django-treebeard, dj ango-classy-tags, djangocms-admin-style, django-appdata Building wheel for djangocms-text-ckeditor (setup.py) ... done Created wheel for djangocms-text-ckeditor: filename=djangocms_text_ckeditor-3. 9.0-py3-none-any.whl size=2009460 sha256=7f2a93b1858ad9c776ea9d286bf96924070a8d7 03ffb5d4510f3b74d39ca57d2 Stored in directory: c:\users\jonas\appdata\local\pip\cache\wheels\0c\7b\1e\e3 908562c925cdc1dbcd7c4bd2447f8a11f6716a7d99f3c04b Building wheel for django-taggit-templatetags (setup.py) ... done Created wheel for django-taggit-templatetags: filename=django_taggit_templatet ags-0.2.5-py3-none-any.whl size=7824 sha256=798816cf8c5154b3cd9d133dd906c8e40945 53de30f114a76fe8829d08a7c66c Stored in directory: c:\users\jonas\appdata\local\pip\cache\wheels\82\a4\66\54 1f4c683657632200e1e8ea3a89698e88ede94c1232365f00 Building wheel for django-filer (setup.py) ... done Created wheel for django-filer: filename=django_filer-1.7.1-py3-none-any.whl s ize=1572351 sha256=89983e63dedf4ecef67b3c0f929f9cf53281cd232a8afa72e9c97e2b3d9e3 d34 Stored in directory: c:\users\jonas\appdata\local\pip\cache\wheels\01\26\cd\d8 64a98a0a882ae18c7c0551af158f82193a7e5daa88a86572 Building wheel for easy-thumbnails (setup.py) ... done Created wheel for easy-thumbnails: filename=easy_thumbnails-2.7-py2.py3-none-a ny.whl size=65532 sha256=b0c81ae967ea8073bba11192946e3e2a4af3928c5be5010445c6cf6 d21f37964 Stored in directory: c:\users\jonas\appdata\local\pip\cache\wheels\e4\3f\d4\3c 7af17dfe56f754d3fe9a3c610aaeff28eaad840778039d1f Building wheel for django-sekizai (setup.py) ... done … -
Rendering test as template: {% static %} not working
Django==3.0.6 I'm trying to let an admin user use template tags. I mean, like this: The filter gets id and renders a huge picture tag. views.py class PostDetailView(DetailView): model = Post def get(self, request, *args, **kwargs): self.object = self.get_object() post_body = "{% autoescape off %}\n{% load image %}\n{% load static %}\n" + self.object.body + "{% endautoescape %}" return HttpResponse(Template(post_body).render(Context())) # Breakpoint At breakpoint (shown in the code above) post_body equals: {% autoescape off %} {% load image %} {% load static %} <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.<p> {{ 1|img }} <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse … -
How can i create a notification system by django
Is there anyway to create a notification system for my website by django without django channels. If there is way how? -
Python + Django (total price and items are not changing!)
I have this in cart.html : Cart when I do the changes that I will show below the total price that's in the end with green plus is changed but the total price and items that are up are not showing at all after the changes I make ! so I do this : in class OrderItem I add : @property def get_total(self): total = self.product.price * self quantity return total then I go to my template -----> cart.html and I change the static total price of $40 to this : <div style="flex:1">${{item.get_total}}</div> and everything is alright with those changes but then I do changes as below in class Order I add : @property def get_cart_total(self): orderitems = self.orderitem_set.all() total = sum([item.get_total for item in orderitems]) return total @property def get_cart_items(self): orderitems = self.orderitem_set.all() total = sum([item.quantity for item in orderitems]) return total then I go to views.py and do this change : from context = {'items':items} ----> context = {'items':items, 'order':order} then do those changes in cart.html : <th><h5>Items: <strong>3</strong></h5></th> ------> <th><h5>Items: <strong>{{order.get_cart_items}}</strong></h5></th> <th><h5>Total: <strong>$43</strong></h5></th> -----> <th><h5>Total: <strong>${{order.get_cart_total}}</strong></h5></th> So from changes that I do from class Order and below nothing changes on runserver ! views.py models.py -
How to keep a SECRET_KEY secret in Django?
The Django documentation suggests keeping the SECRET_KEY in environmental variables rather than in the settings.py file. Why is this considered safer? The environmental variables are plain text-files which offer the same level of protection as settings.py. Even if the file rw permissions are set to root-only, I assume that this is not hard to break. My question is: which other options are there to store the SECRET_KEY? Or the master key used for encryption. From django-encrypted-secrets: django-encrypted-secrets works by using a key (stored locally in master.key file or read from the environment variable DJANGO_MASTER_KEY) and reading/writing secrets to the encrypted file secrets.yml.enc. If there is no other option than a plain text-file or environmental variable stored locally. How can this one be protected properly? -
django_select2 - limit the returned text to a specific field in module
I am using django_select2 in my application. I would like to search and display only according to one field of a model. models.py: class Venue(models.Model): venue_name = models.CharField(max_length=50) venue_city = models.CharField(max_length=50) venue_country = models.CharField(max_length=50) def __str__(self): return f"{self.venue_name}, {self.venue_city}, {self.venue_country}" forms.py: from django import forms from .models import from django_select2 import forms as s2forms class VenueForm(forms.ModelForm): class Meta: model = Venue fields = ['venue_name', 'venue_city', 'venue_country'] widgets = { 'venue_city': s2forms.ModelSelect2Widget(model=Venue, search_fields=['venue_city__icontains']), 'venue_country': s2forms.ModelSelect2Widget(model=Venue, search_fields=['venue_country__icontains']), } The above code successfully filter by venue_city field. Nevertheless, it returns the whole __str__(self). How can I make it to return only the city and country fields, so that users will see only the city or country from the dropdown list of the respective <input>s? -
Module not found error when trying to use shell_plus of django-extensions
I am trying to use the shell_plus that populates your shell with all your models. I put into INSTALLED_APPS: django_extensions. As soon as I try to run python manage.py shell_plus I get $ python manage.py shell Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\Cody\AppData\Roaming\Python\Python37\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Cody\AppData\Roaming\Python\Python37\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\Cody\AppData\Roaming\Python\Python37\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Cody\AppData\Roaming\Python\Python37\site-packages\django\apps\registry.py", line 122, in populate app_config.ready() File "C:\Users\Cody\AppData\Roaming\Python\Python37\site-packages\django\contrib\admin\apps.py", line 24, in ready self.module.autodiscover() File "C:\Users\Cody\AppData\Roaming\Python\Python37\site-packages\django\contrib\admin\__init__.py", line 26, in autodiscover autodiscover_modules('admin', register_to=site) File "C:\Users\Cody\AppData\Roaming\Python\Python37\site-packages\django\utils\module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "C:\Program Files (x86)\Python37-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\Cody\AppData\Roaming\Python\Python37\site-packages\django_extensions\admin\__init__.py", line 21, in <module> from django_extensions.admin.widgets import ForeignKeySearchInput File "C:\Users\Cody\AppData\Roaming\Python\Python37\site-packages\django_extensions\admin\widgets.py", line 7, in <module> from django.contrib.admin.templatetags.admin_static import static ModuleNotFoundError: No module named 'django.contrib.admin.templatetags.admin_static' If I am to comment out django_extensions and run python manage.py shell the shell works and defaults to ipython. Any … -
how to UPLOAD video file to DJANGO via program
model.py from django.db import models class Post(models.Model): video = models.FileField(upload_to='filesInput/') csv = models.FileField(upload_to='filesInput/') csvTimeL = models.CharField(max_length = 50, default = '00:00:02.02') csvTimeR = models.CharField(max_length = 50, default = '00:00:02.4') urlTimeL = models.CharField(max_length = 50, default = 3) urlTimeR = models.CharField(max_length = 50, default = 8) siteUrl = models.CharField(max_length = 300) def __str__(self): return self.siteUrl class Result(models.Model): inputData = models.ForeignKey(Post, on_delete = models.CASCADE) resVideo = models.FileField() def __str__(self): return self.resVideo.url So I want to upload videofile to Result.resVideo Here how I do it with TextField: python manage.py shell >>> from posts.models import Post, Result >>> a = Post.objects.get(id = 3) a.result_set.create(text = 'text') The problem is: I don't know how to explain django the connection of the video file to Post() and the video file itself. I also got the respond from another forum for uploading the video to Post(): from django.core.files.base import ContentFile from .models import Post video_name = 'video.webm' with open(video_name, 'rb') as f: video_content = f.read() instance = Post() instance.video.save(video_name, ContentFile(video_content)) instance.save() But i need to upload it to the Result.resVideo with "connection" to Post. -
Referral System on Django
I am working on a cashback website. I need help with creating referral links for users and tracking the number of users that registered through a users referral link. Also, Is there a way I can let the users get a fraction of what their referred users have earned? -
Template not showing context variable
I created an app called marketing app which customizes messages to be written on top of home page. My problem is that these messages are not showing when everything configured and I don't know why is that might be the template because {{ marketing_message.message }} is only not showing This is the model: class MarketingMessage(models.Model): message = models.CharField(max_length=120) active = models.BooleanField(default=False) featured = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) start_date = models.DateTimeField( auto_now_add=False, auto_now=False, null=True, blank=True) end = models.DateTimeField( auto_now_add=False, auto_now=False, null=True, blank=True) def __str__(self): return str(self.message[:12]) This is the view: from marketing.models import MarketingMessage class HomeView(ListView): model = Item paginate_by = 10 template_name = "home.html" def get_context_data(self, **kwargs): context = super(HomeView, self).get_context_data(**kwargs) context['marketing_message'] = MarketingMessage.objects.all() return context This is the template: {% if marketing_message %} <div id="top-alert"class="alert alert-light" style="padding-top:85px; margin-bottom:-24px;"> <a href="#" class="close" data-dismiss="alert">×</a> <div class="container" style="text-align:center"> <strong> Marketing Message ! : </strong> {{ marketing_message.message}} </div> </div> {% endif %} -
Django 3.x Python 3.x Ajax : NoReverseMatch + jquery on change triggers only once
form on the page: views.py: @login_required def render_erkb_form(request,trans_id,coach_id): context = {} try: context['transfer'] = Transfer.objects.get(pk=trans_id) clients_assign_form = ErkbRamsis(transfer_id=trans_id, coach_id=coach_id, prefix=trans_id) context['clients_assign_form'] = clients_assign_form return TemplateResponse(request,'forms/erkb.html', context) except Exception as e: return HttpResponse('%s %s <P>Somthing went wrong!</p>' % (e,e.args),status=500) @login_required def clients_assign(request, trans_id): context = {} try: transfer = Transfer.objects.get(pk=trans_id) first_coach = transfer.service.legs.first() if request.method == "POST": clients_assign_form = ErkbRamsis( request.POST or None, files=('transfer_clients','coach','coach_clients',), transfer_id=transfer.pk, prefix=transfer.pk, ) if clients_assign_form.is_valid(): # get data and save it to database # Works Fine if clients_assign_form.is_valid() == False: # Do Some Action clients_assign_form = ErkbRamsis(transfer_id=trans_id,prefix=trans_id) context['clients_assign_form'] = clients_assign_form return TemplateResponse(request,'forms/erkb.html', context) except Exception as e: return HttpResponse('%s %s <P>Somthing went wrong!</p>' % (e,e.args),status=500) forms.py class ErkbRamsis(forms.Form): def __init__(self, *args, **kwargs): self.transfer_id = kwargs.pop('transfer_id') transfer = Transfer.objects.get(pk = self.transfer_id) if 'coach_id' in kwargs: self.coach_id = kwargs.pop('coach_id') leg = Leg.objects.get(pk = self.coach_id) else: leg = Leg.objects.filter(service = transfer.service).first() super(ErkbRamsis, self).__init__(*args, **kwargs) self.fields['transfer_clients'] = forms.ModelMultipleChoiceField( queryset=Client.objects.filter(related_pnr = transfer.service.related_pnr), widget=forms.SelectMultiple( attrs={ 'class':"erkb_source form-control", 'style':"height:100%;width:100%;", }, ), label=False, required=False, ) self.fields['coach'] = forms.ModelChoiceField( queryset=Leg.objects.filter(service = transfer.service), widget=forms.Select( attrs={ 'class':"erkb_coach form-control", 'data-trans':transfer.pk, } ), initial=leg, label=False, required=False, ) self.fields['coach_clients'] = forms.ModelMultipleChoiceField( queryset = leg.clients, widget=forms.SelectMultiple( attrs={ 'class':"erkb_destination form-control", } ), label=False, required=False, ) def clean(self, *args, **kwargs): transfer_clients = self.cleaned_data.get('transfer_clients') coach … -
Display distinct values in a form admin using a m2m relationship class - Django
I'm trying to display only the distinct names in the django admin form. Here are the 3 class: class Topping(models.Model): name = models.CharField(max_length=200) class Pizza(models.Model): name = models.CharField(max_length=200) toppings = models.ManyToManyField(Topping) class C(models.Models): pizza = models.ForeignKey(Pizza, on_delete=models.CASCADE) When I get in the admin page to add a new record on C table, the same pizza appears different times, example: Pepperoni Pepperoni Hawaiian Hawaiian Hawaiian What I expected it was something like that: Pepperoni Hawaiian Thank you! -
AJAX delete POST request in Django Python
I'm building a simple TO-DO Django web application following csdojo tutorial here. I wanted to add Ajax in both addTodo & deletedTodo. Although addTodo is working properly but deleteTodo always render me to a JSON page with whatever return. This is my first Django web app, please help me locate the bug, MUCH THANKS!! urls.py from django.contrib import admin from django.urls import path from hello.views import view from todo.views import todo_view, addTodo, deleteTodo urlpatterns = [ path('admin/', admin.site.urls), path('sayHello/', view), path('todo/', todo_view, name = "todo_view"), path('addTodo/', addTodo, name = "addTodo"), path('deleteTodo/<int:todo_id>/', deleteTodo, name='deleteTodo'), ] views.py def addTodo(request) : if request.is_ajax and request.method == "POST": new_item = TodoItem(content = request.POST['content']) new_item.save() ser_instance = serializers.serialize('json', [ new_item, ]) return JsonResponse({"new_item": ser_instance}, status=200) else : return JsonResponse({"error": new_item.errors}, status=400) def deleteTodo(request, todo_id) : if request.is_ajax and request.method == "POST": item = TodoItem.objects.get(id=todo_id) item.delete() return JsonResponse({'url': reverse('todo_view')},status=200) else : return JsonResponse({"error": item.errors}, status=400) todo.html {% extends "base.html" %} <title>{% block title %} Vixtrum to do list {% endblock title %}</title> {% block content %} <h1>To do list</h1> <ul id="list"> {% for todo_item in all_items %} <li id="todo-{{todo_item.id}}">{{ todo_item.content }} <form class="deleteTD" action="/deleteTodo/{{todo_item.id}}/" method="post" style="display: inline; margin: 10px;">{% csrf_token %} <input type="submit" value="Delete" class="btn btn-outline-danger" … -
How to access reversed relationship using Django rest framework
Here are my models : class Profile(models.Model): user = models.ForeignKey(User, related_name="profile", on_delete=PROTECT) plan = models.ForeignKey(Plans, on_delete=PROTECT) full_name = models.CharField(max_length=2000) company_name = models.CharField(max_length=50, null=True, blank=True) activation_token = models.UUIDField(default=uuid.uuid4) activated = models.BooleanField(default=False) thumb = models.ImageField(upload_to='uploads/thumb/', null=True, blank=True) renew_data = models.DateField() is_paid = models.BooleanField(default=False) And as u see the Profile model have user field that is related to the Abstract user of django framework. now here is how i call them using an API : Serializers class ProfileSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Profile fields = ['company_name'] class UserSerializer(serializers.HyperlinkedModelSerializer): profile_set = ProfileSerializer( read_only=True, many=True) # many=True is required class Meta: model = User depth = 1 fields = ['username', 'id', 'profile_set'] But when I call the API it shows only the fields username and 'id but not the profile_set -
django form is submitting but the object is not saved in the database
Actually i'm working on the library management system project everything is working fine except return book functionality. My project contains books, students and issue and returning the book with fine if it is there. I was making a return book function i made the logic but and it is correct also but it is not saving into the database. Even the calculations which i wanted is done but it is not submitting. I'm doing from last 3 days. Please help me, if you get some idea. And please, let me know if you required any other files. models.py for return Book class ReturnBook(models.Model): actual_return_date = models.DateField(default=datetime.today) book = models.ForeignKey(Book, on_delete=models.CASCADE) student_name = models.ForeignKey(Student, on_delete=models.CASCADE) fine_amount = models.IntegerField(default=0) def __str__(self): return self.book.book_name + ' is returned by ' + self.student_name.first_name + ' ' + self.student_name.last_name forms.py for return book class ReturnBookForm(forms.ModelForm): class Meta: model = ReturnBook fields = [ 'actual_return_date', 'book', 'student_name', 'fine_amount' ] urls.py for return book and returned book path('issuedbooks/<int:pk>/returnbook/', views.returnBook, name='return-book'), path('returnedbook/', views.TransactionandReturnBook, name='returned-book'), returnbookform.html {% extends "lms/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="section"> <form method="POST" action="{% url 'returned-book' %}"> {% csrf_token %} <fieldset class="form-group"> <div class="card mt-4 detail-view-header"> <h3 class="text-center mt-2 font-weight-bold" … -
Gunicorn - starting server issue?
I am having this issue to start my gunicorn server, but it seems like it's failing to start the server after I did reload daemon and enable my updated gunicorn system. I checked two or three times to make sure all's correct, so alls correct. Pls see the image below: enter image description here - Also, see the errors I received after I started it: Active: failed (Result: resources) May 09 14:40:03 avidfisherman systemd[1]: Failed to start Gunicorn server for superlists-staging.bdienterprises.com. Anyone here is familiar with this issue? Your help would be so appreciated! Thank you! -
Django redirect with data
def view_post(request, post_id): """Display a blog post""" blogpost = BlogPost.objects.get(id=post_id) context = {'blogpost': blogpost} return render(request, 'blogs/blogpost.html', context) def new_post(request): """Create a new blog post""" if request.method != 'POST': # No data submitted; create a blank form. form = BlogPostForm() else: # POST data submitted; process data. form = BlogPostForm(data=request.POST) if form.is_valid(): form.save() return redirect('blogs:index') # Display a blank or invalid form. context = {'form': form} return render(request, 'blogs/new_post.html', context) def edit_post(request, post_id): blogpost = BlogPost.objects.get(id=post_id) if request.method != 'POST': # Initial request; pre-fill form with current blogpost. form = BlogPostForm(instance=blogpost) else: # POST data submitted; process data. form = BlogPostForm(instance=blogpost, data=request.POST) if form.is_valid(): form.save() view_post(request,post_id) # Display form with original contents context = {'blogpost': blogpost,'form': form} return render(request, 'blogs/edit_post.html', context) The code above should process a user's edited post, and then redirect to the post that has been edited. Redirect doesn't allow data to be sent to my knowledge, so I tried to nest a function to no avail. I've seen online that cookies / messages may be a solution. If so, how might I implement it? -
Nginx proxy server to another proxy server Gateway timeout
It's my first time deploying an application on a deployment environment so I am a complete beginner at this, I have an nginx proxy server (call it server1) on an instance with an exposed IP to the internet & it routes requests to another server on a different instance (call it server2) that hosts my Django application, the conf file for server1 goes like this : `server{ server_name _; location / { proxy_pass_header Authorization; proxy_pass http://10.156.0.4:80; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_http_version 1.1; proxy_set_header Connection “”; proxy_buffering off; client_max_body_size 0; proxy_read_timeout 36000s; proxy_redirect off; } listen 443 ssl; listen [::]:443 ssl; include snippets/self-signed.conf; include snippets/ssl-params.conf; } server{ listen 80; listen [::]:80; server_name _; return 302 https://35.246.244.220;} and the second server: server{ listen 80; listen [::]:80; server_name _; location / { proxy_pass_header Authorization; proxy_pass http://10.156.0.4:8880; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_http_version 1.1; proxy_set_header Connection “”; proxy_buffering off; client_max_body_size 0; proxy_read_timeout 36000s; proxy_redirect off; } location /static/ { alias /opt/app/mydjangoapp/staticfiles/; autoindex off; } } I am running my django application using this command python manage.py runserver 0.0.0.0:8880 & I also did collectstatic before running the application. Everything works fine when i edit proxy_pass in … -
How to get custom column from MYSQL table through Django
I would like to get specific column from DV table based on input from user. db : animal weight height cat 40 20 wolf 100 50 first i need to get what animal user wants input1='cat' and then information about the input1 like weight or height input2='weight' animalwho=Wildlife.objects.get(animal=input1) So if i put animalwho.weight it give me 40 But i want to get column based on input2 as input 2 might be height or any other I tried animalwho.input2 but it does not work. Is that possible to get column based on input2? Would apopreciate any help -
Path does not find in django
I am working on a django project. The project includes 2 apps namely jobs and blog. The url.py of the main project file is: from django.contrib import admin from django.urls import path,include from django.conf import settings from django.conf.urls.static import static import jobs.views urlpatterns = [ path('admin/', admin.site.urls), path('', jobs.views.home, name= 'home'), path('blog/', include('blog.urls')) ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) You can understand that I am calling the output of the jobs in the home. The url.py of the blog is: from django.urls import path from . import views urlpatterns = [ path('', views.allblogs, name= 'allblogs'), ] and the views.py of the blog is: from django.shortcuts import render def allblogs(request): return render(request, 'blog/allblogs.html') This gives an error that the blogs/ can not be found. The webpage shows that it tries to find the page in this ditrectory: ...project\jobs\templates\blog\allblogs.html I dont know why it is trying to find it in jobs where it should search for it in blogs folder. Can someone help? May be I have done something silly.. -
django-invitations JSON view errors
I simply want to be able to have a user send an email invite to multiple users via an email input field that allows up to 30 emails. I've tried using django-multi-email-field but don't want to have to do more work than necessary. django-invitations already does the invite keys for me so I want to be able to get the json-invite url to work. I get the errors Method Not Allowed (GET): /invitations/send-json-invite/ Method Not Allowed: /invitations/send-json-invite/ when going to that url. I have not modified the package at all but inside the invitations/views.py there is this: class SendJSONInvite(View): http_method_names = [u'post'] @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): if app_settings.ALLOW_JSON_INVITES: return super(SendJSONInvite, self).dispatch( request, *args, **kwargs) else: raise Http404 def post(self, request, *args, **kwargs): status_code = 400 invitees = json.loads(request.body.decode()) response = {'valid': [], 'invalid': []} if isinstance(invitees, list): for invitee in invitees: try: validate_email(invitee) CleanEmailMixin().validate_invitation(invitee) invite = Invitation.create(invitee) except(ValueError, KeyError): pass except(ValidationError): response['invalid'].append({ invitee: 'invalid email'}) except(AlreadyAccepted): response['invalid'].append({ invitee: 'already accepted'}) except(AlreadyInvited): response['invalid'].append( {invitee: 'pending invite'}) except(UserRegisteredEmail): response['invalid'].append( {invitee: 'user registered email'}) else: invite.send_invitation(request) response['valid'].append({invitee: 'invited'}) if response['valid']: status_code = 201 return HttpResponse( json.dumps(response), status=status_code, content_type='application/json') I tried adding 'get' to the http_method_names as well as creating a "pass" … -
How to exclude values of manytomanyfields from from POST method( Django Rest Framework )
I have a Blog project where users can Post,comment and like the posts. When displaying entire Posts (ListCreateView method,ie POST&GET) it displays whoever liked the post but in POST method(as mentioned in attached picture) it exposes the list of entire users as options to like (in attached photo, voters means list of registered users with Blog project, for test purpose they named as a,b,c ) How can I avoid voters (I mean list of people who can like Post ) from CreateView ? My projects works fine but I want to avoid the major data expose. SERIALIZERS.PY class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = "__all__" class LikeSerializer(serializers.ModelSerializer): class Meta: model = Post exclude = ("voters",) MODELS.PY class Post(models.Model): ... voters = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="votes",blank=True) -
Django Template counter++
I am trying to complete this exact code wrote on PHP and Laravel but using Django: @php $a = 0; @endphp @foreach($images as $image) @if($a % 2 == 0) <li class="grid-item"> <!--<li class="grid-item2">--> <img class="img img-fluid"src="{{ route('image.file',['filename' => $image->image_path]) }}" /> </li> @php $a = $a+1; @endphp @else <li class="grid-item grid-item--width2"> <!--<li class="grid-item2 grid-item--width2">--> <img class="img img-fluid"src="{{ route('image.file',['filename' => $image->image_path]) }}" /> </li> @php $a = $a+1; @endphp @endif @endforeach It just simple enter using pair numbers into the if condition or not, for any foreach cycle. and this is what I have on Django: {% for photography in photographies.all%} {% if number|divisibleby:2 == True %} <li class="grid-item"> <!--<li class="grid-item2">--> <img class="img img-fluid" src="{{ photography.image.url }}" /> </li> {{number|add:1}} {% else %} <li class="grid-item grid-item--width2"> <!--<li class="grid-item2 grid-item--width2">--> <img class="img img-fluid" src="{{ photography.image.url }}" /> </li> {{number|add:1}} {% endif %} {% endfor %} The views.py: def home(request): #añadido number = 0 photographies = Photography.objects #añadido return render(request, 'photographies/home.html', { 'photographies':photographies, 'number':number }) #añadido The biggest problem I have right now is that for some reason the variable number which on any for cycle it reset to cero so always enter into the if condition. -
Form in footer through base html not working on other pages with forms django
So I'm using LoginView for my login page for example but on the login page the newsletter signup form in my footer also turns into a login form. I tried using my own view and changing the newsletter signup for to form2 in context but it doesn't work. I guess because newsletter signup is a form it's getting passed any other form on whichever page I'm on. Any ideas? -
How to convert // to / in url address in python django and apache -- linux
At first, thank you for reading :X Problem + Description: I'm redirecting http traffic from any ip address on port 80 to 10.0.0.1:8080 (django) via linux apache and iptables. When web user issue a request to this url (hello.gggstatic.com/generate_204******), I handle path to /generate_204*** url address, via this rule: re_path('.*generate_204.*', lambda r: HttpResponseRedirect('splash/')),. Buuuuut, users are seeing `//splash/` instead of `/splash/` in browser. `http://10.0.0.1:8080//splash/` #django 404 not found users must see: `http://10.0.0.1:8080/splash/` #django can handle it and via "include('splash.urls')" Problem: How to manage/remove/handle "//" in url address bar !!?? Log: [09/May/2020 13:43:36] "GET //generate_204 HTTP/1.1" 302 0 Not Found: //captive_splash/ [09/May/2020 13:43:36] "GET //splash/ HTTP/1.1" 404 2328 my urls.py file in django-project: urlpatterns = [ re_path('/static/', serve,{'document_root': settings.STATICFILES_DIRS}), re_path('.*generate_204.*', lambda r: HttpResponseRedirect('splash/')), path('', lambda r: HttpResponseRedirect('splash/')), #path('admin/', admin.site.urls), path('splash/', include('splash.urls')), ] my urls.py file in django-application: urlpatterns = [ re_path('^$', views.start, name='start'), re_path('index/$', views.start, name='start'), path('validation', views.validation, name='validation'), path('bye', views.goodbye, name='goodbye'), ] My apache config: <VirtualHost *:80> ServerName hello.gggstatic.com ServerAdmin webmaster@localhost RewriteEngine On RewriteCond %{HTTP_HOST} ^hello.gggstatic.com$ RewriteRule ^(.*)$ http://10.0.0.1:8080 [L,NC,R=302] ErrorLog ${APACHE_LOG_DIR}/android_error.log CustomLog ${APACHE_LOG_DIR}/android_access.log combined </VirtualHost>