Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to disable automatic decompression for gzipped image data
I am creating a django web app for viewing and processing of medical images that are stored in a .gz format. The web app has a single model (Post) and form that collects metadata from users as well as one .gz file with a models.FileField call. In my views.py file, I can render a response and feed the path to the medical image to a javascript viewer as well as all the metadata about the image (e.g., type of patient, body part, etc.) that is simple plain text fields. The javascript viewer expects a compressed image (interacting with .gz files is standard in the field). Django seems to only serve these media files decompressed and the javascript viewer (someone else's project) does not like the decompressed data. So far, I have played around with ['Content-Encoding'] options, but I can't get anything working. Maybe I need separate view functions for the metadata and image data? In views.py: def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) rendered = render(request, 'maps/post_detail.html', {'post': post}) # rendered['Content-Encoding'] = 'gzip' return rendered @login_required def post_new(request): if request.method == "POST": form = PostForm(request.POST, request.FILES) #, instance=profile) if form.is_valid(): post = form.save(commit=False) post.contributor = request.user post.published_date = timezone.now() post.save() … -
Page not redirecting after form submit
I have a form which creates a new category. Previously, the form was in a different template which worked fine but since it's only a simple form I have decided to render it in modal form instead of redirecting to a different page. The user can add a new category, however the success message and the page rendering after the form submit is not shown. It only shows up if you refresh the page. The response message is 302. I've done similar method with other forms which worked perfectly fine. forms.py class CategoryModelForm(forms.ModelForm): def clean_name(self): print(self.cleaned_data['name']) name = self.cleaned_data['name'] try: Category.objects.get(name__iexact=name) except ObjectDoesNotExist: return name raise forms.ValidationError('Category Name already exists.') class Meta: model = Category fields = ['name'] views.py @method_decorator(login_required, name='dispatch') class CategoryView(TemplateView): template_name = 'content/category_list.html' def get_context_data(self, **kwargs): context = super(CategoryView, self).get_context_data(**kwargs) categories = Category.objects.all() user = self.request.user category_list = [] for category in categories: article_count = category.article_count(user) include = category.show or user.usertype_is_staff() or user.is_superuser requested_by = category.requested_by if category.requested_by else '' cat = { 'reference': category.pk, 'name': category.name, 'show': category.show, 'article_count': article_count, 'has_articles': article_count > 0, 'requested_by': requested_by, 'requested_by_name': requested_by.profile.full_name if requested_by and requested_by.profile.full_name else '-' } include and category_list.append(cat) context['categories'] = category_list context['form'] = CategoryModelForm(self.request.POST or None) … -
how to pass value from html to view in django?
i have code in html like this your major is {{user.userprofile.major}} this will correctly showing the major on webpage, but I want to use this string to get something from another table in view. How would I pass this string to view? -
How to Send Email to Django Oscar Registered Partners about Order Placed for there Products?
I want to Notify Django Oscar Partners through an Email stateing that there products has Order from customers. here Customers might place order from multiple Partners for multiple product. how can i send list of order placed for particular Partner and send Email. -
NOT NULL constraint failed: adminside_event.event_data
I have problem with my code which is i try to submit my Event form in the models. But when i run the form it will show the whole form (and another thing is that it will not show the values in the select box of the rounds) and when i click on the the submit button it will through an error.Please help me out this. VIEW SIDE CODE:-- def addevents(request): if request.method=="POST": name=request.POST['events'] est=request.POST['starttime'] eet=request.POST['endtime'] s=Event() s.ename=name s.event_start_time=est s.event_end_time=eet s.save() cats = request.POST.getlist('cats') for i in cats: s.categories.add(Category.objects.get(id=i)) s.save() roundd = request.POST.getlist('rround') for j in roundd: s.rounds.add(Round.objects.get(id=j)) s.save() return render(request,'adminside/addevents.html') else: rounds = Round.objects.all() categories = Category.objects.all() return render(request,'adminside/addevents.html',{'categories':categories,'rounds':rounds}) MODELS SIDE:- class Event(models.Model): ename=models.CharField(max_length=200) categories = models.ManyToManyField(Category) event_data = models.DateField() event_start_time = models.TimeField() event_end_time = models.TimeField() rounds = models.ManyToManyField(Round) EVENT PAGE FORM:- {% extends 'adminside/master.html' %} {% block content %} <div class="col-12"> <div class="card"> <div class="card-body"> <h4 class="card-title">Events</h4> <p class="card-description"> All fields are Compulsory </p> <form class="forms-sample" method="POST"> {% csrf_token %} <div class="form-group"> <label for="exampleInputEmail1">Add Event</label> <input type="text" class="form-control" name="events" id="exampleInputEmail1" placeholder="Enter Event"> </div> <div class="form-group"> <label>Categories:</label> <select class="form-control" multiple name="cats"> {% for i in categories %} <option value="{{ i.id }}">{{ i.cname }}</option> {% endfor %} </select> </div> <div … -
Send Only Current Page object to the template (django)
I am learning django from MDN.And i was working on locallibrary.There i got one problem. I want to send only books on author page but not all book,only current page's author book. If url is /author/1 then sent only book of author id 1, not all In AuthorDetailView i tried context['books']=Book.objects.filter(author__exact=Author.id). but it give error **TypeError at /catalog/author/1** **int() argument must be a string, a bytes-like object or a number, not 'DeferredAttribute'** When i write context['books']=Book.objects.filter(author__exact=1) then it send only authorid 1's book on all page. on author/2. so i want to send authorid 2's book on author/2. 3's book on author/3. But not all books on everypage. It doesn't make sense to send all objects when needed few. {% for book in books%} {% if author.id is book.author.id %} <li> <a href="{{ book.get_absolute_url }}">{{ book.title }}</a> ({{book.author}}) </li> {% endif %} This code do what i wanted but by sending all objects. I hope you understand what i want. Here is my models,views https://pastebin.com/yY6M5LUA -
Update Contacts using Python, Django and Graph
I'm trying to update contacts using Python and Microsoft Graph within a profile page I've created using Django. I can access contacts and get all the data I need, however I can't work out how to update the fields. The only information I can find is on the Graph website, however I can't work out how to translate this into usable code: PATCH PATCH https://graph.microsoft.com/beta/me/contacts/ Content-type: application/json { "title": "Mr", "givenName": "Steve" } I assume there is a way to just put this together as a simple link but I cannot work it out. I've tried the following: PATCH https://graph.microsoft.com/beta/me/contacts/{id}/title/Mr PATCH https://graph.microsoft.com/beta/me/contacts/{id}/title:Mr PATCH https://graph.microsoft.com/beta/me/contacts/{id}/title/$value==Mr but they all produce errors There are no tutorials for doing this with Python on the Microsoft site and it's proving very difficult to find any info on it. So hopefully someone can help out. Cheers! -
Module Not Found Error after moving directory and back
After moving my directory back and forth, I am recieving the below error. Not sure how to resolve this. The files are currently sitting in the directory they originated from. What seettings should I be looking at when I get an error like this. C:\Users\Nathan\AppData\Local\JetBrains\Toolbox\apps\PyCharm-P\ch-0\192.6817.19\bin\runnerw64.exe C:\Users\Nathan\PycharmProjects\DJANGO_TemplateApp\venv\Scripts\python.exe C:/Users/Nathan/PycharmProjects/DJANGO_TemplateApp/manage.py runserver 8000 Traceback (most recent call last): File "C:\Users\Nathan\PycharmProjects\DJANGO_TemplateApp\venv\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Nathan\PycharmProjects\DJANGO_TemplateApp\venv\lib\site-packages\django\core\management\commands\runserver.py", line 60, in execute super().execute(*args, **options) File "C:\Users\Nathan\PycharmProjects\DJANGO_TemplateApp\venv\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Users\Nathan\PycharmProjects\DJANGO_TemplateApp\venv\lib\site-packages\django\core\management\commands\runserver.py", line 67, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "C:\Users\Nathan\PycharmProjects\DJANGO_TemplateApp\venv\lib\site-packages\django\conf\__init__.py", line 79, in __getattr__ self._setup(name) File "C:\Users\Nathan\PycharmProjects\DJANGO_TemplateApp\venv\lib\site-packages\django\conf\__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) File "C:\Users\Nathan\PycharmProjects\DJANGO_TemplateApp\venv\lib\site-packages\django\conf\__init__.py", line 157, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\Nathan\AppData\Local\Programs\Python\Python37\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 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'DJANGO_TemplateApp' -
How to use less database look-ups during filter?
I have a section of code that makes several db calls and I am trying to optimize it. Is there a way to get rid of/combine: username = users.models.User.objects.filter(groups__name=group) or.. user_obj = users.models.User.objects.get(username=user) or combine them so that I am only making one database lookup during this transaction instead of two? for group in groups: username = users.models.User.objects.filter(groups__name=group) for user in username: form.instance.unread.add(user) user_obj = users.models.User.objects.get(username=user) user_obj.send_sms('memo') user_obj.send_email(user, 'memo') Also, I am new to web development; is this something I should worry about? -
Django request is loop when request take long time
I have an issue when making an ajax POST request. Sometimes My request is being looped when it takes a long time to respond. Somehow a new request similar to the previous request is made, and I don't know where is it from? I have tried to debug, create traceback, but have no idea where is it called. It usually happens when the request is made from the Chrome Browser on macOS. Do you guys have any idea why does it happen? Django version 1.11.17 -
I`m creating a calendar-app using django. Calendar must be vertical
For now I have realized this django-calendar . But i need vertical calendar(sorry, haven`t found any in English) On the left we have weekday headers and month names on the top. I started overriding python-calendar HTMLCalendar methods. I thought to write formatweekdayrow method, which would generate row of mondays, tuesdays .... sundays. But i got stuck as i dont fully understand how these all methods work. So the question is should i think over my idea of writing formatweekdayrow, or is it not possible to make vertical calendar like that? Or may be there is some simple and smarter way to do that? -
Pulled my docker django project but don't run
I create a dockerized version of my Django project in this fashion: create my Dockerfile create my docker-compose.yml create my .dockerignore on my machine all done, if i run docker-compose up all start. Then i build the project docker-compose build . and push to my hub repo docker push myrepo/myproject well, at this point i connect from another machine and i do: docker pull myrepo/myproject as you can see it download the image: but when i run it nothing appen: docker run d080812784c6 in my docker-compose file, into my web service i specify the command: command: python /Code/core/manage.py runserver 0.0.0.0:8000 ...how can i start my pulled docker image correctly? So many thanks in advance -
How to remove slashes inside hashed key in DRF API Key or is there any way to accept slashes in urls.py?
I created an API Endpoint in Django to generate an API Key with DRF API Key Module. The problem occurs sometimes. If the generated key has slashes in it, it can't be fetch by the other API Endpoint. There's no problem if I create it in Django admin side. I have tried to override the methods in the module so that it can be generated through the serializer. I can't trace the problem. #models.py class UserCompanyAPIKeyManager(BaseAPIKeyManager): key_generator = KeyGenerator(prefix_length=32, secret_key_length=32) class UserCompanyAPIKey(AbstractAPIKey): objects = UserCompanyAPIKeyManager() #some fields @classmethod def generate_prefix(self) -> str: key_generator = UserCompanyAPIKey.objects.key_generator try: key, prefix, hashed_key = key_generator.generate() except ValueError: # Compatibility with < 1.4 key, hashed_key = self.key_generator.generate() # type: ignore pk = hashed_key prefix, hashed_key = split(hashed_key) else: pk = concatenate(prefix, hashed_key) return pk, prefix, hashed_key #serializers.py class UserCompanyAPISerializer(serializers.ModelSerializer): def create(self, validated_data): pk, prefix, hashed_key = self.Meta.model.generate_prefix() validated_data['prefix'] = prefix validated_data['id'] = pk validated_data['hashed_key'] = hashed_key return super().create(validated_data) class Meta: model = UserCompanyAPIKey fields = ['id', 'name', 'expiry_date', 'user', 'company'] Working output us5z0Faxg2zEPDo99NmAOgEsf70MpHVb.pbkdf2_sha256$150000$RmkU1OFLKEtW$2YIEK7cZztwVjbqAEoQRLDzxujfTlQ2Fwx4skp2o1nk= Problem ( with slash ) eKi7lj4AvTEgorF7iKiFrzxQZlVD196C.pbkdf2_sha256$150000$ri39ifY6bmDj$DKQHFhTYQOzpEph6v8BUwbdxO/FcLjqDZa/nzq+ujJY= -
Strategy for serving Django Admin static files in k8s environment
Been messing with this most of the day and have been stumped. nginx-ingress isn't designed to serve static files per this Github issue. gunicorn isn't either per documentatoin WhiteNoise works locally with gunicorn, but doesn't seem to like nginx-ingress and just returns a: Resource interpreted as Stylesheet but transferred with MIME type text/html I've tried a few things, one of which: Was FROM python:3.7-slim, copying the app over and then installing nginx into the image. Doesn't seem like a good practice and couldn't get it working. The only other thing I can think of trying is a deployment and service just for the static files. However, not sure how to set that up, particularly the routing. Any suggestions, or guidance, on how to serve static files (particularly Django Admin) in a k8s setup? -
django admin site m sending email.html to user
\\admin from django.template.loader import render_to_string @admin.register(ParentsProfile) class ParentsProfile(admin.ModelAdmin): list_display = ('Father_Email','Fathers_Firstname' , 'Fathers_Middle_Initial', 'Fathers_Lastname', 'Request') ordering = ('Request',) search_fields = ('Request',) actions = ['Send_Email','Send_Email_Disapproved'] def Send_Email(self, request, queryset): html_content = render_to_string('Homepage/email.html') for profile in queryset: send_mail(subject="Invite", message=html_content, from_email=settings.EMAIL_HOST_USER, recipient_list=[profile.Father_Email]) i receive and email.txt not email.html, i dont know why.. please help me for this issue.. Email -
How to limit admin input after certain number of entries in Django admin?
I have been learning django for about 1 month while coming to django admin I want to limit data entries from admin not more than 5 so that when I want to display the model db on webpage be not more than 5, can you help me in this sorry if this too basic My model is class Top_5_Restaurants(models.Model): Restaurants=models.CharField(max_length=20) def __str__(self): return( self.Restaurants) class Meta: verbose_name = 'Top 5 Restaurant' verbose_name_plural = 'Top_5_Restaurants' Now I don't want more than 5 entries of Restaurants from admin interface, if admin tries entering more than 5 entries I want the entry option to blocked till admin deletes one of the entered database. -
'Category' object has no attribute 'post_set'
so I am trying to add a category system for posts by following a tutorial on this website https://djangopy.org/how-to/how-to-implement-categories-in-django/ (I changed my code up a little) Everything works like creating categories, adding a post, viewing a post, but if I try to go to the category page to view posts only in that category so /category/CATNAME but it shows me this error 'Category' object has no attribute 'post_set' models.py from django.db import models from django.contrib.auth.models import User from django.utils.text import slugify from markdownx.models import MarkdownxField from markdownx.utils import markdownify from taggit.managers import TaggableManager class Category(models.Model): name = models.CharField(max_length=100) short_desc = models.CharField(max_length=160) slug = models.SlugField() parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE) class Meta: unique_together = ('slug', 'parent',) verbose_name_plural = "Categories" def __str__(self): full_path = [self.name] k = self.parent while k is not None: full_path.append(k.name) k = k.parent return ' -> '.join(full_path[::-1]) def save(self, *args, **kwargs): value = self.title self.slug = slugify(value, allow_unicode=True) super().save(*args, **kwargs) class Thread(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=150) content = MarkdownxField() tags = TaggableManager() slug = models.SlugField(unique=True) category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title class Meta: verbose_name_plural = 'Threads' def get_cat_list(self): k = self.category breadcrumb = … -
a request with pandas importing is running on django, but all other requests involved with pandas are blocking
windows + apache2.4 + django 2.1.10 + python 3.7 apache conf is followed `Listen 80 ServerName xxx.xxxx.cn Alias /static/ "F:/PivotWeb/pivot/static/" Require all granted WSGIScriptAlias "/" "F:/PivotWeb/apache/django_python_web.wsgi" WSGIApplicationGroup %{GLOBAL} Require all granted ` WSGIApplicationGroup %{GLOBAL} is added to solve the first sub interpreter issue. The request involve many complex pandas manipulations. a request with pandas importing is running on django, but all other requests involved with pandas are blocking. It seems that pandas module could only process on request per time. -
How to assign permission to a group in views using django-guardian
Currently using django-guardian. I am not sure of what i am doing wrong but i am unable to add the permissions below to a group not saving it. I have created one group and a few users via ADMIN. I have added users to the group now I want to add the permission 'can_play_piano' to the group. models.py class Task(models.Model): task_group = models.ForeignKey(Group, on_delete=models.CASCADE, related_name='task_groups') slug = models.SlugField(unique=True, max_length=200, db_index=True, blank=True) content = models.CharField(max_length=230) created = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) class Meta: permissions = ( ('can_play_piano', 'Can play piano'), ) def __str__(self): return self.task_group.name def save(self, *args, **kwargs): self.slug = slugify(self.task_group.name) super(Task, self).save(*args, **kwargs) views.py def detail_page(request, id): # Get the group id group = get_object_or_404(Group, id=id) # Get the task id task = get_object_or_404(Task, id=id) add_task_to_group = assign_perm('can_play_piano', group, task) add_task_to_group.save() # this is not saving print(add_task_to_group) context = {'group': group} return render(request, 'snippet/detail.html', context) I have intentionally not included request.method == 'POST' just for the sake of the question. result of 'print(add_task_to_group) in terminal' wiki is just a name placeholder wiki | wiki | can_play_piano I would appreciate any help. -
django Custom Template is not rendering for password_change_form.html
I have a password_change_form.html which is custom formatted on the website. I'm overriding the Django default template with my template. But, it is not rendering my template. It just rendering the default template. I have created a custom formated template base.html <div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="{% url 'password_change' %}">Change password</a> <div class="dropdown-divider"></div> password_change_form.html {% extends 'home/base.html' %} {% block body %} <h2> Change password </h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-primary">Change password</button> </form> {% endblock %} urls.py from django.contrib import admin from django.urls import path, include from Shopping.cart import urls urlpatterns = [ path('', include('Shopping.cart.urls')), path('accounts/', include('django.contrib.auth.urls')), path('admin/', admin.site.urls), ] I wanted to see my template overrides the Django default template -
django admin send email to user
\admin.py @admin.register(ParentsProfile) class ParentsProfile(admin.ModelAdmin): list_display = ('Father_Email','Fathers_Firstname' , 'Fathers_Middle_Initial', 'Fathers_Lastname', 'Request') ordering = ('Request',) search_fields = ('Request',) actions = ['Send_Email','Send_Email_Disapproved'] def Send_Email(self, request, queryset): html_content = "Your Registration has been approved.\n\nPlease use this %s as your username and %s as your password. \nYou may now start enrolling your student using this link https://...../Plogin_form/ \n\n\n REGISTRAR " for profile in queryset: send_mail(subject="Invite", message=html_content %(profile.Father_Email,profile.Parent_Password), from_email=settings.EMAIL_HOST_USER, recipient_list=[profile.Father_Email]) # use your email function here def Send_Email_Disapproved(self, request, queryset): # the below can be modified according to your application. # queryset will hold the instances of your model for profile in queryset: send_mail(subject="Invite", message="Our Apology,\n\n Your Registration has been Disapproved " + profile.Father_Email + "\n\n\n REGISTRAR" + "", from_email=settings.EMAIL_HOST_USER, recipient_list=[profile.Father_Email]) i have this code to send an email to user, how do i convert my html_content into HTML? so that i can design my message to user? -
Django Custom user model creation NOT NULL constraint failed error
Im creating a custom user model with AbstractUser on django and i get that error when i create new user. Im using shell for create user: CustomUser.objects.create(email="testmaiil2323@gmail.com", name="test name aasxs", business_name="asdkasdk sl", password="testpass234") Im succefull created superuser with command createsuperuser, but when i make a new users django tells me: django.db.utils.IntegrityError: NOT NULL constraint failed: apirest_customuser.business_id from django.db import models from django.contrib.auth.models import AbstractUser from django.contrib.auth.base_user import BaseUserManager from django.utils.translation import ugettext_lazy as _ class Business(models.Model): name = models.CharField(max_length=150, unique=True) def __str__(self): return self.name class Profile(models.Model): name = models.CharField(max_length=150, unique=True) def __str__(self): return self.name class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_('The Email must be set')) if not extra_fields.get('business_name'): raise ValueError(_('The Business name must be set')) if not extra_fields.get('name'): raise ValueError(_('The Name must be set')) if not password: raise ValueError(_('The Passowrd must be set')) email = self.normalize_email(email) business = Business.objects.create(name=extra_fields.get('business_name')) profile = Profile.objects.create(name=extra_fields.get('name')) user = self.model(email=email, business=business, profile=profile, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): """ Create and save a SuperUser with the … -
How can I use the static images in ReactJS connected to Django?
I have configured Django and ReactJS and I want the static images to be loaded as well as the CSS and js files from ReactJS components to be loaded during the development. I have added a webpack.config.js file for configuration but it's not providing the result. This is the webpack.config.js file module.exports = { module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader" } }, { test: /\.css$/, use: "css-loader" }, { test: /\.(jpe?g|png|gif|woff|woff2|eot|ttf|svg)(\?[a-z0-9=.]+)?$/, loader: "url-loader?limit=100000" } ] } }; When I run npm run dev, this is what I get. Also when I run the python manager.py runserver for starting the local server and try the link out, I'm getting only the HTML content and not the HTML with styling and the images are not embedded. This is the file structure and you can see the hash of the image being outputted. What should I do in order to get the output correctly? -
Implementing Jupyter notebook into Django web app
I would like to know if there's a way to show a jupyter notebook on a Django page? The reason for this is, I would like to create a few live Data Analytic scenarios and showcase it on my Django site where each of these projects gathers data from source stores the info into an SQLite database for later use in a Machine learning project that I can showcase also on my Django site I've looked around I have not come across any scenarios like this. If you have any ideas feel free to post them :) Kind Regards Faz -
Django formset - custom input HTML
I need to expand a formset's field, so instead of {{ form.name }} I'm using something like <input type="text" name="{{ form.name }}" ... > My custom implementation does not print the formset prefix, so the HTML I get is <input type="text" name="name" ... > But what I would need to have the form working properly with formset is <input type="text" name="attachments-3-name" ... > where attachments-x is automatically added. How can I get that? I noted there's an helper for ID (auto_id) which prints something similar: id_attachments-3-name; is there something similar for names?