Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problem passing list to a template Django
I'm trying to pass a list of books from views.py to a html template. I took the datetime example and modify it but is nott working. here is my views.py: `class BookViewSet(viewsets.ModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer` `def theBooks(request): t = template.loader.get_template('templates/index.html') the_books = Book.objects.all() c = template.Context({'books': the: books}) html = t.render(c) return HttpResponse(html) ` And my template is: `<!DOCTYPE html> <html lang="es"> <head> <meta charset="UTF-8"> <title>Current Time</title> </head> <body> {# This is a comment #} {# check the existence of now variable in the template using if tag #} {% if now %} <p>The books are: {{ books }}</p> {% else %} <p>now variable is not available</p> {% endif %} </body> </html>` -
Python Multiprocessing with Django
I wrote a piece of code where i take N number of entries from a Database using PyMySql, i map these entries to a certain function, then they are returned and updated in the main process, now what i did is that i made this into a function, and i started calling it from a Django view by creating a new thread, my problem is after a certain time (usually 1 hour to 3 hours) (the more the cores and processes the less the time), the entire django server blocks along with the function processing, i have all of this inside a docker container, so the entire container blocks, i'm using the standard multiprocessing/threading python modules, i wonder if any of you had this problem before ? PS: i cannot really share the code since it is not mine -
Django How to Set and get cookie render to other template?
i am beginner in django and i dont know much but go through from django documentation but didnt get the idea . i want to set the cookie for my driver. i am sending a mail to drivers a link with uuid. The thing is i am posting my driver uuid by a href on every template passing through in hidden field by form . but i want to set and render to all pages till driver booking confirmed. These are my model and i am showing my first template which is i am sending to drivers in mail. when they hit a link after that i want the cookie to set in it and after driver book for car . i want to save in my db the car which is booked by for eg John. Model.py driver_firstname = models.CharField( max_length=64, blank=True, null=True ) driver_lastname = models.CharField( max_length=64, blank=True, null=True ) driver_email = models.EmailField( blank=True ) driver_token_id = models.UUIDField( default=uuid.uuid4, unique=True, blank=False, null=False, ) Views.py @csrf_protect def rentacar_list(request, page_number=1): all_cars = Car.objects.all().order_by('-id') if menu_config.menu_item_rentacar_list_show_unavailable == 0: all_cars = all_cars.exclude(car_available=0) else: all_cars = all_cars cars_page = Paginator(all_cars, menu_config.menu_item_rentacar_list_pagination) args['cars'] = cars_page.page(page_number) template = Template.objects.get(template_default__exact=1) template_page = template.template_alias + str("/rentacar/rentacar_cars_list.html") return … -
How to attach hidden MIME images in an email with Python(Djago)
I am trying to send an email with Django that contains an embedded image. This is the gist of the code, it works, but it sends the image as an attachment. I don't want the message to be visible as an attachment. I also dont want to link the image to a server somewhere. Basically I want the image to be embedded in the mail, but dont want the attachment to be visible. How do I do this? msg = EmailMultiAlternatives() fp = open('test.jpg', 'rb') msg_image = MIMEImage(fp.read()) msg_image.add_header('Content-ID <myimage>') msg.attach(msg_image) fp.close() -
Execute group task after one group task finished in celery
right now i am implementing celery tasks in my appplication. I want that my task perform chaining But somehow, the chain doesn't work, the group work but the chain doesn't work. The process that I want is I want that the GROUP_A will be processed after i process the GROUP_B and so on. I have tried using chord but still got no idea. Below is my simple chain performing group task in celery. Thank for your attention guys. GROUP_A = [] GROUP_B = [] GROUP_C = [] GROUP_D = [] for i in range(3): GROUP_A.append(A.s(i+1)) GROUP_B.append(B.s(i+1)) GROUP_C.append(C.s(i+1)) GROUP_D.append(D.s(i+1)) job = chain( group(GROUP_UPDATE_LEECH_CHECKER), group(GROUP_REPORT_LEECH_CHECKER), group(GROUP_UPDATE_EXM_POINT), group(GROUP_WARN_LEECHING_USER) ) job.apply_async() Regards, Meikelwis Wijaya -
RelatedObjectDoesNotExist at /admin/login/ User has no profile
I am learning django and was creating porject in it. I was able to login to admin page through http://127.0.0.1:8000/admin But after adding profile code for every user I am getting below error Error Error screenshot user/models.py from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) image=models.ImageField(default='default.jpg',upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self): super().save() img=Image.open(self.image.path) if img.height>300 or img.width >300: output_size=(300,300) img.thumbnail(output_size) img.save(self.image.path) user/views.py from django.shortcuts import render,redirect from django.contrib.auth.forms import UserCreationForm from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm,UserUpdateForm,ProfileUpdateForm def register(request): if request.method=="POST": form=UserRegisterForm(request.POST) if form.is_valid(): form.save() # it will save user in database #form.cleaned_data is dictionary it will contain the data from form username=form.cleaned_data.get('username') messages.success(request,f'Your account has been created!') return redirect('login') else: form=UserRegisterForm() # instance of UserCreationForm() class will create form in template as we are passing there return render(request,'users/register.html',{'form':form}) @login_required() def profile(request): if request.method == "POST": u_form=UserUpdateForm(request.POST,instance=request.user) p_form=ProfileUpdateForm(request.POST,request.FILES,instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account has been updated!') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context={ 'u_form':u_form, 'p_form':p_form } return render(request,'users/profile.html',context) users/forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile class UserRegisterForm(UserCreationForm): email=forms.EmailField() class … -
Django - Reference to model with 2 attributes
Currently i'm starting with a usermanagement app. The case is that we have an User (the default django one) and an UserMail. The UserMail has an OneToOneField to User with reference to the username. mail_username= models.OneToOneField(User, to_field='username', on_delete=models.CASCADE) Because we also use the database of UserMail for another app, I want the password to be in the same table, which would look like this: mail_password = models.CharField(max_length=128) But the mail_password has to be the password from the corresponding User.username. Is there a nice way to do this? -
What is the Django setup for session?
I want to save sessions in server side instead of db. right now my project using db to store sessions, as per documentation i removed 'django.contrib.sessions' from installed app but its giving error RuntimeError: Model class django.contrib.sessions.models.Session doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. . So, what is the actual setup for session? -
Pillow png compressing
Im making a simple app that able to compress images with jpeg and png format using Pillow library, python3 and Django. Made a simple view that able to identify formats, save compress images and give some statistics of compressing. With images in jpeg format it works really fine, i got compressicons close to 70-80% of original size, and it works really fast, but if i upload png i works much worse. Compression takes a long time, and it only 3-5% of original size. Trying to find some ways to upgrade compress script, and stuck on it. Right now ive got this script in my compress django view: from django.shortcuts import render, redirect, get_object_or_404, reverse from django.contrib.auth import login, authenticate, logout from django.contrib.auth.models import User from django.http import HttpResponse, HttpResponseRedirect from django.http import JsonResponse from django.contrib import auth from .forms import InputForm, SignUpForm, LoginForm, FTPForm import os import sys from PIL import Image from .models import image, imagenew, FTPinput from django.views import View import datetime from django.utils import timezone import piexif class BasicUploadView(View): def get(self, request): return render(self.request, 'main/index.html', {}) def post(self, request): form = InputForm(self.request.POST, self.request.FILES) if form.is_valid(): photo = form.save(commit=False) photo.name = photo.image.name photo.delete_time = timezone.now() + datetime.timedelta(hours=1) photo.user … -
Settings locales for Alpine docker image
I run a Django application on an Alpine Docker image. My problem is that I am unable to set the locales to display dates in French. -
Multiple OpenLayers map markers with same model, but different content
I am working on a farming management tool that helps farmers handle their files about a specific crop set. The crop sets are indicated by markers on a map (specifically on OpenLayers) and if the farmer clicks on a marker it displays a file handling modal. The farmer can download, preview, delete and upload as many files as he can manage in this modal. Now the problem comes along, there are multiple crop sets and each with their own individual files. How do I still use the same model, form and views for each marker, but have different data? models.py: class UploadModel(models.Model): document = models.FileField(upload_to='uploads/') forms.py class UploadForm(forms.ModelForm): class Meta: model = UploadModel fields = ('document',) view.py def model_form_upload(request): path = "media/uploads/" docs = sorted(os.listdir(path)) if request.method == 'POST': form = UploadForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('form') else: form = UploadForm() return render(request, 'mapapp/form.html', { 'form': form, 'docs': docs }) def delete(request, doc): path = "media/uploads/" os.remove(path + doc) return redirect('form') def download(request, doc): path = "media/uploads/" file_path = path + doc if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel") response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) return response raise Http404 form.html: <div id="map"></div> <div id="marker1"><img src="{% … -
Database connection in Pydev Eclipse
I have created one django project in pydev IDE it was sounds much better than pycharm IDE..But now I got some issues to connect to database (postgresql). I didn't find any useful documentation from internet as well..can anyone help me to connect my database using Pydev IDE. Fed up with this a lot..someone help me please... -
Django urls.py mechanism
Recently, I started my web project using django, with reference to some youtube tutorials. In that, I have created a project named "admin" and created an app named "user". From many tutorials, they have created separate urls.py for both project and app. But in my case, only the project's urls.py is working. For example, I have defined the index[home page] view in project's urls.py and login view in app's urls.py. when I try to access the login as it shows "The current path, login, didn't,t match any of these" Can anyone help me to find out the solution for this... -
Django ideas/tips for Czech Republic Groupon
I am poor , but i am not blackhat! Sorry guys, I will be honest. I am „poor“ guy from Eastearn Europe (Czech Rep). I work here like programmer. I know college maths and programming. Some guy transformed Groupon to czech environment, names Slevomat. He was also „poor“ czech programmer. Nowdays he is millionaire. Do you have any business ideas like Groupon to transform? I am sorry that i write contra rules of StOv, but i use and like Django framework. We have to use open source in Eastearn Europe, we are poor. You are rich and i don´t want your money illegally. I need just advice how to help me and my country. Thanks. -
In flask, Is it possible to use url convertor without splitting them using slash '/'?
I have a route: @app.route("/login/<user>/<timestamp>") def user(user, timestamp):. But, I need it in this form - @app.route("/login/<user><timestamp>") def user(user, timestamp):. i.e without the slash('/'). Is there any way to do it ? -
ca not find static file in django
my file view.py contain a funtion def blog(request): return render(request, 'home/blog.html') In my url : urlpatterns = [ url(r'^$', blog, name='cover'), url('diaoibou/', blog, name='blog')] When use the the url r'^$, i find the static files and my web application diplay the images , and when use the url diaoibou do not find the statics files [18/Sep/2018 10:04:34] "GET /diaoibou HTTP/1.1" 301 0 [18/Sep/2018 10:04:34] "GET /diaoibou/ HTTP/1.1" 200 9124 [18/Sep/2018 10:04:34] "GET/diaoibou/static/css/bootstrap.css HTTP/1.1" 200 9124 [18/Sep/2018 10:04:34] "GET /diaoibou/static/css/style.css HTTP/1.1" 200 9124 [18/Sep/2018 10:04:34] "GET /diaoibou/static/css/popup-box.css HTTP/1.1" 200 9124 [18/Sep/2018 10:04:34] "GET /diaoibou/static/js/jquery-1.11.0.min.js HTTP/1.1" 200 9124 -
Optimizing custom template tag which makes API call
I have this template tag which works well but when I use it many times in template whole page loads too long. How can I improve this? @register.simple_tag def converted_currency(amount, currency, default_user_currency, date=timezone.now()): c = CurrencyConverter('http://www.ecb.int/stats/eurofxref/eurofxref-hist.zip', fallback_on_wrong_date=True, fallback_on_missing_rate=True) converted_value = c.convert(amount, currency, default_user_currency, date=date) return Decimal(converted_value).quantize(Decimal("0.00")) Used library: https://pypi.org/project/CurrencyConverter/ -
Running a Django Celery Beat taks depending on some Model date field
Is there some way to relate Django celery tasks for each record saved in the database? For example, if I want to each user receives an email depending on what date the user wants it. Maybe I wrong thinking the solution to problems like this is solve by Django celery, can any help me? -
Django & Python : Format a FloatField in django form by adding separators
Well I dont know how to do this on django, so please help me do so. my float field is like : montant= forms.FloatField(initial="0",required = False) I want to show separators in my numbers to be lisible Example: when I write on the field the number is like : 1000000.00 what I need when writing on the field is I want the number looks like : 1 000 000.00 Any help please ? Thank You in advance -
Django testing, assert CSV content is present
I am doing a test to check the contents of a csv file using assertContains(): response = client.get('/abc/1/a_b_csv') print(response.content) self.assertContains(response.content, 'aakash') I tried different options such as self.assertContains(response,'aakash') but didn't get any result. Sometimes there is the error: AttributeError: 'bytes' object has no attribute 'status_code' Any suggestions? -
Docker connect host mysql for django
I am trying to connect to my host mysql from docker container but I don't know how to connect. I have a django project for that I followed Django Docker I am using this tutorial this one is working fine for djnago and postgres. I am using mac and I am using mamp server I want to connect my djnago app to my host mysql. My docker file code is: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ And my docker compose file is: version: '3' services: db: image: postgres web: build: . command: python3 manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db This one is working fine but I am trying to connect my django app to my host mysql. I don't know how to connect host mysql from my docker. -
how to use a sessionWizard subclass as a url path in django
how do I use the django-formwizard sessionwizard subclass as a url path how to use a sessionWizard subclass as a url path in django -
In django_select2, the field_id parameter is getting not passed in ajax url
While I am using django_select2, the field_id parameter is not getting passed to get URL select2/fields/auto.json. Due to this, it throws 404 error. Is there any configuration I am missing? django_select2 - LIB_VERSION = '4.0.5' python3.6 django2.1 -
Search button displaying wrong result django?
I am creating a simple blog app with the help of django. This is my models: class categories(models.Model): Title = models.CharField(max_length=40, default='GST') class Blog(models.Model): User = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True) Date = models.DateTimeField(default=datetime.now) Blog_title = models.CharField(max_length=255) Description = RichTextUploadingField(blank=True, null=True,config_name='special') Blog_image = models.ImageField(upload_to='blog_image', null=True, blank=True) Category = models.ForeignKey(categories,on_delete=models.CASCADE,related_name='Categories', null=True, blank=True) This is the views I created for search: def search(request): template = 'blog/blog_list.html' query = request.GET.get('q') if query: result = Blog.objects.filter(Q(Blog_title__icontains=query) | Q(Description__icontains=query) | Q(Category__Title__icontains=query)) else: result = Blog.objects.filter(User=self.request.user).order_by('id') return render(request, template) In my Template: <form method='GET' class="form-horizontal" action="{% url 'blog:search' %}"> <div class="box-body"> <div class="form-group"> <label for="inputEmail3" class="col-sm-2 control-label">Search</label> <div class="col-sm-10"> <input name="q" value="{{request.GET.q}}" placeholder="Search"> </div> </div> </div> <div class="box-footer"> <button type="submit" class="btn btn-info pull-right">Go</button> </div> </form> I dont know what is going wrong in the code...When I search for some Blog_title or description it gives a blank page... Can anybody help me to figure out what went wrong in the code.. Thank you... -
Django responds to options request despite the lack of Authorisation token
I'm testing responses from a rest api. If a user does not send a token, I expect that a 403 response will be sent. In the test (below) I create a user, create and grab their auth token (for use in other tests) and test if i can send an options request with no authentication. When testing the endpoint with an external request, i get the response: { "detail": "Authentication credentials were not provided." } But my code is returning status 200 with the response to the options request. I've checked that nowhere in the code i force_authentication(..., and self.client.credentials.__dict__) returns a blank dictionary. Why is django returning the request when permission_classes = (permissions.IsAuthenticated,)? View: from rest_framework import permissions class getUserOptions(views.APIView, ReturnMetadata): permission_classes = (permissions.IsAuthenticated,) def options(self, request): field_meta = self.user_metadata(request) return Response(field_meta) Test: from django.contrib.auth import get_user_model from rest_framework import status from rest_framework.test import APIClient from rest_framework.authtoken.models import Token class basic_functionality(APITestCase, TestCase): def setUp(self): self.user_details = {...} self.client = APIClient() self.user_model = get_user_model() user = self.user_model.objects.create(username=self.user_details['username']) user.set_password(self.user_details['password']) user.first_name = self.user_details['first_name'] user.last_name = self.user_details['last_name'] user.email = self.user_details['email'] ... user.is_active = self.user_details['is_active'] user.save() self.client.force_login(user) user_temp = self.user_model.objects.get(username=self.user_details['username']) self.user_token = Token.objects.get_or_create(user=user_temp)[0] class user_options(basic_functionality): def request_user_options(self, payload): """ Test getting options for the …