Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to include links in blog post
I have built a blog with Django. In my BlogPost model I have a text field named "content". When I compose a blog post via the admin panel, any custom HTML (links, code blocks, external images) that I enter is rendered in the template as static, literal text - not it's true semantic HTML. I want to create a blog that allows blog posts to use markdown. No one else is making posts except me, and there is not client-facing form throughout the entire site (except the admin login page). How do I turn off escaping so that I can use custom HTML like italics, bold, links, external images, h1's, h3's, paragraphs, etc in my blog posts? I have been trying to find a resource to learn from but am coming up short. Should I use a preconfigured markdown app, or roll my own? -
how to have options in urls in django 2.0
In Django 1 I used to have url choices like this: url('meeting/(?P<action>edit|delete)/', views.meeting_view, name='meeting'), How I do this in Django 2.0 with the <> syntax: Maybe something like this? path('meeting/(<action:edit|delete>)/', views.meeting_view, name='meeting'), -
Django New lines in view variable
I am sending email with Django using Sendgrid. I have a variable message for the message that will send, however the message holds the value of a few other variables. I would like them to be on different lines to make the email easier to read. Here is what I have, although it is not working. if form.is_valid(): name = form.cleaned_data.get('name') phone = form.cleaned_data.get('phone') email = form.cleaned_data.get('email') party_size = form.cleaned_data.get('party_size') form_message = form.cleaned_data.get('message') listing_address = listing.address message = name + "\n" + phone + "<br>" + email + "<br>" + party_size + "<br>" + listing_address send_mail('New Lead', message, 'leads@studentcribz.com', ['email@gmail.com'], fail_silently=False) The email is being sent as this: garrett 1234234<br>g@d.com<br>2<br>address would be here Although I would like this: garrett 1234234 g@d.com 2 address would be here -
birthday_year&birthday_month&birthday_day cannot be gotten
birthday_year&birthday_month&birthday_day cannot be gotten. I wrote in views.py @require_POST def regist_save(request): regist_form = RegisterForm(request.POST or None) profile_form = ProfileForm(request.POST or None) context = { 'regist_form': regist_form, 'profile_form': profile_form, } if request.method == "POST" and regist_form.is_valid() and profile_form.is_valid(): try: username = regist_form.cleaned_data.get('username', None) email = regist_form.cleaned_data.get('email', None) exist_user = User.objects.get(Q(username=username)) exist_email = User.objects.get(Q(email=email)) if exist_user != "": messages.warning(request, 'That user name is already used.') if exist_email != "": messages.warning(request, 'That email is already used.') return render(request, 'registration/regist.html', context, messages) except User.DoesNotExist: regist = regist_form.save(commit=False) regist.is_staff = True regist.save() profile = profile_form.save(commit=False) profile.user = regist sex = request.POST.get("sex", "") year = request.POST.get("year", "") month = request.POST.get("month", "") day = request.POST.get("day", "") profile.sex = sex profile.birthday_year = year profile.birthday_month = month profile.birthday_day = day profile.save() return render(request, 'registration/detail.html') else: return render(request, 'registration/regist.html', context) in forms.py class ProfileForm(forms.ModelForm): class Meta: model = NewUser fields = ( "birthday_year", "birthday_month", "birthday_day", "sex" ) in models.py class NewUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birthday_year = models.CharField(max_length=100, null=True, default=None) birthday_month = models.CharField(max_length=100, null=True, default=None) birthday_day = models.CharField(max_length=100, null=True, default=None) sex = models.CharField(max_length=100, null=True, default=None) in regist.html <form class="form-horizontal" action="/accounts/regist_save/" method="POST"> <div class="form-group-lg"> <label for="id_username">username</label> {{ regist_form.username }} </div> <div class="form-group-lg"> <label for="id_email">email</label> {{ regist_form.email }} </div> <div class="form-group-lg"> <label … -
Django sendfile with nginx failed to send the file as attachment
I'm using django-sendfile for sending a large file as attachment to the UI. This works with sendfile.backends.simple backend but when I use sendfile.backends.nginx, it returns 404 error on nginx logs. I think there was something wrong with my nginx configuration. views.py class FileDownloadView(View): def get(self, request, id_file): obj = FileCombined.objects.get(id_file=id_file) return sendfile(request, obj.path, attachment=True) settings.py SENDFILE_BACKEND = "sendfile.backends.nginx" SENDFILE_ROOT = os.path.join(BASE_DIR, 'media') SENDFILE_URL = '/media' /etc/nignx/sites-enabled/myapp server { # simple reverse-proxy listen 80; server_name localhost; sendfile on; # serve static files location /static { proxy_pass http://127.0.0.1:8000/static; } location /media/ { internal; root /home/foo/project/django-combine/media; } location / { proxy_pass http://127.0.0.1:8000; } } nginx/access.log 127.0.0.1 - - [30/Dec/2017:08:20:01 +0530] "GET /file/id/5114a7721b6943fb31fc143a20adbec630bb5eb2516d7574b881454209338eed/download/ HTTP/1.1" 404 208 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/52.0.2743.116 Chrome/52.0.2743.116 Safari/537.36" 127.0.0.1 - - [30/Dec/2017:08:25:01 +0530] "GET /file/id/5114a7721b6943fb31fc143a20adbec630bb5eb2516d7574b881454209338eed/download/ HTTP/1.1" 404 208 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/52.0.2743.116 Chrome/52.0.2743.116 Safari/537.36" -
How to customize username validation
I am trying to customize username validation for the django.contrib.auth User model. It says Usernames may contain alphanumeric, _, @, +, . and - characters. but I'd like to make it so that it would be invalid if the user made a username with @, ., -, +. How would I go about overriding this validation so when the user creates a username it is using my custom validation instead of the original UnicodeUsernameValidator? I am using my own custom User model, but i'm inheriting from AbstractBaseUser Is there a simple way to add my username validation? -
django - use environment variables in debian not working
It might be simple thing but I just can't seem to get it running. in my Django project's settings, I have these db settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.getenv('DB_NAME'), 'USER': os.getenv('DB_USER'), 'PASSWORD': os.getenv('DB_PWD'), 'HOST': 'xxxx.yyyyy.eu-central-1.rds.amazonaws.com', 'PORT': '', } } and in /etc/environment I have set the variables and also in .profile. but this is just not working and I am getting: (1045, "Access denied for user 'www-data'@'132.31.48.116' (using password: NO)") If I remove and hardcode the credentials, it works. so obviously my env variables are located in wrong place. can someone please give some look at it? I am using Debian 4.9.51-1 (2017-09-28) x86_64 in ec2 server -
Django: Limit to size of database-backed sessions?
Django's documentation (here) state that cookie-based sessions can exceed the 'standard' of 4096 bytes per cookies. What about database-backed sessions, is there a limit to the amount of data that can be stored in the session? I didn't see anything in the documentation, nor on SO. For my project, I'll need to save ~50KB to a user's database-backed session. Let me know if you need more info. -
Cannot send email using django and nginx(gunicorn) on digital ocean droplet
I deployed a website using django + nginx + gunicorn on a ubuntu droplet. And I use the email function of django. However, every time I tried to send email, I got a 502 error in my website. And my nginx error log is: [error] 24933#24933: *30944 upstream prematurely closed connection while reading response header from upstream, client: 45.34.23.99, server: server.cn request: "GET /confirmation-email-send/3/ HTTP/1.1", upstream: "http://unix:/tmp/server.cn.socket:/confirmation-email-send/3/", host: "server.cn", referrer: "https://server.cn/signup/contestant" Settings.py in django: EMAIL_USE_SSL = True EMAIL_HOST = 'smtp.sina.com' EMAIL_HOST_USER = '****@sina.com' EMAIL_HOST_PASSWORD = '****' EMAIL_PORT = 465 EMAIL_FROM = '****h@sina.com' /etc/nginx/sites-available/server.cn: server{ charset utf-8; listen 80; listen 465; server_name server.cn; location /static { alias /path/to/static; } location / { proxy_set_header Host $host; proxy_pass http://unix:/tmp/server.cn.socket; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/server.cn/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/server.cn/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot if ($scheme != "https") { return 301 https://$host$request_uri; } # managed by Certbot } The function of sending email works well when I run the website at localhost. So I think the problem is in deploying. I've seen some similar questions but the methods provided can not solve my problem. -
Need helping creating a Poke (think Facebook) app using Django
So I'm having trouble completing this task. Basically, it's supposed to only be two pages. One is a login/registration page. The other is a page with a table that allows you to Poke other users. I've made the login/reg page work (with validations) and I've gotten the logged in user to not appear on the table on the 2nd page. I've also used Jinja to display the logged in user's name on the html. Now, I'm still missing a few things. How to display the number of people that have poked you using Jinja. A list of people that have poked you and how many times they have done so. Getting the actual poke buttons to function and track the logged in user poking the corresponding user on the table. I think I'm heading in the right direction but am really struggling with the Poke functionality. Can you guys and girls lend a hand? Thanks! Here is the link to a pastebin containing all the code from both apps, or see the code below. Edit: Please see the link here to see my progress so far. Please use the username: jdoe@gmail.com and password: password in order to login and view … -
Correct way of starting a session with Django REST Framework
I want to use the SessionAuthentication of DRF, so I looked for solutions for starting the session. I found several answers suggesting to create a basic password authentication which calls Django's login function in the end, so it looks something like this: def authenticate(self, request): #Check credentials, etc login(request, user) return user, None This however didn't work for me, because the login functions tries to get the request.user attribute, which triggers DRF to start it's own authentication process calling my basic authenticationen and thus creating an infinite loop. My next approach was to call the login function inside of the post function of my authentication view: def post(self, request, format=None): #Authentication already done by DRF, so no errors expected username = request.data.get('user') password = request.data.get('password') user = authenticate(request=request, username=username, password=password) login(request, user) But now everything is done multiple times for each login, because DRF launches the authentication before the function, then I need to get the user again and lastly DRF authentication is launched a second time by the login function. This works so far, but isn't very effective and I am pretty sure there are better ways of doing that (without bypassing DRF). -
JQuery Validator and Django
I have a code in views: def check_username(request): if HttpRequest.is_ajax and request.method == 'GET': username = request.GET['username'] if User.objects.filter(username=username).exists(): print('duplicate') # have this for checking in console return HttpResponse(False) else: return HttpResponse(True) else: return HttpResponse("Zero") It takes the request from JQuery and that print('duplicate') works right, printing only when I have duplicate. My JS code: $("#formregister").validate({ rules: { username: { required: true, remote: "http://127.0.0.1:8000/accounts/checkname" } }, messages: { username: { required: 'you MUST have username', remote: 'gogogog' } } }); }); "You MUST have username" works properly, but I can't get remote message. What am I doing wrong? Thanks! -
Using for loop in Python HTML template to load images
I'm pretty new to Python so sorry for the newbie question. Using Django, I'm trying to load a few hundred images from a remote server. I simply want to load three per row. I've created an object in the view which does a images.object.all() query and returns it to the template. All I want to do is loop through the images and place a break at the end of each 3rd image. My code is {% for image in images %} <img width="200px" src="http://www.somewebsite.com/{{ image.url_pre_string }}{{ image.filename }}.{{ image.extension }}" /> {% endfor %} I've tried doing an if else inside the for loop but I need a counter variable to count the images and that just fails badly. Is there an easy way to do this in Django? -
UnboundLocalError: local variable 'form' referenced before assignment in Django
So i'm working on a django project and this is my views.py file: def new_topic(request, pk): board = get_object_or_404(Board, pk=pk) user = User.objects.first() # TODO: get the currently logged in user if request.method == 'POST': form = NewTopicForm(request.POST) if form.is_valid(): topic = form.save() return redirect('board_topics', pk=board.pk) else: form = NewTopicForm() return render(request, 'new_topic.html', {'form': form}) When i ran my server, i got an error saying UnboundLocalError: local variable 'form' referenced before assignment This is my new_topic.html file {% extends 'base.html' %} {% block title %}Start a New Topic{% endblock %} {% block breadcrumb %} <li class="breadcrumb-item"><a href="{% url 'home' %}">Boards</a></li> <li class="breadcrumb-item"><a href="{% url 'board_topics' board.pk %}">{{ board.name }}</a></li> <li class="breadcrumb-item active">New topic</li> {% endblock %} {% block content %} <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-success">Post</button> </form> {% endblock %} -
Displaying word/pdf document with django in html giving problems
I am trying to display word files and pdf files that are user uploads. I am getting the error: Reverse for 'project.file.path' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []. This is my iframe <iframe src="https://view.officeapps.live.com/op/embed.aspx?src={% url 'project.file.url' %}"> </iframe> I am using office 360 to read the word file. My urls are like this: urlpatterns = [ # ... the rest of your URLconf goes here ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) How can I fix this error, and are there better alternatives for displaying word documents with Django? My user uploads are stored within the media directory folder. The media folder and the Django project folder are at the same directory level. -
Django dynamic model design
I have a table that contains a dynamic number of entries, each entry contains data (like id, name, date) and also 3 radio buttons. class Entry(models.Model): id = ... name = ... data = ... selected_option = ... I want to save all of the entries in the DB when the user submits the form. I was wondering what would be the best way to design the model for this. -
Copy file into another folder with django?
I need to upload profile images into diferent folders in Django. So, I have a folder for each account, and the profile image have to go to the specific folder. How can I do that? Here is my uploadprofile.html <form action="{% url 'uploadimage' %}" enctype="multipart/form-data" method="POST"> {% csrf_token %} <input type="file" name="avatar" accept="image/gif, image/jpeg, image/png"> <button type="submit">Upload</button> </form> And here is my view in views.py def uploadimage(request): img = request.FILES['avatar'] #Here I get the file name, THIS WORKS #Here is where I create the folder to the specified profile using the user id, THIS WORKS TOO if not os.path.exists('static/profile/' + str(request.session['user_id'])): os.mkdir('static/profile/' + str(request.session['user_id'])) #Here is where I create the name of the path to save as a VARCHAR field, THIS WORKS TOO avatar = "../../static/profile/" + str(request.session['user_id']) + "/" + str(img) #THEN I HAVE TO COPY THE FILE IN img TO THE CREATED FOLDER return redirect(request, 'myapp/upload.html') -
Django queryset union appears not to be working when combined with .annotate()
I have the following queryset photos = Photo.objects.all() I filter out two queries. a = photos.filter(gallery__name='NGL') b = photos.filter(gallery__name='NGA') I add them together, and they form one new, bigger queryset. c = a | b Indeed, the length of a+b equals c. a.count() + b.count() == c.count() >>> true So far so good. Yet, if I introduce a .annotate(), the | no longer seems to work. one = photos.annotate(c=Count('label').exclude(c__lte=4) two = photos.filter(painting=True) all = one | two one.count() + two.count() == all.count() >>> False How do I combined querysets, even when .annotate() is being used? Note that query one and two both work as intended in isolation, only when combining them using | does it seem to go wrong. -
Limiting one appointment per user
I'm trying to make it so users are only able to schedule one appointment. Here I am modifying the save method. What I am trying to figure out is how to see if that user already has an appointment. def save(self, *args, **kwargs): if Appointment.objects.filter(owner=user_pk).exists() and not self.pk: # if you'll not check for self.pk # then error will also raised in update of exists model raise ValidationError('You have already scheduled an appointment.') return super(Appointment, self).save(*args, **kwargs) In my views.py I already have something that will raise an error if an appointment with that user already exists. But i'm thinking this is not enough and that there should be something at the model level. appointments = Appointment.objects.filter(owner=request.user) if appointments.exists(): raise PermissionDenied('You have already scheduled an appointment.') -
AttributeError: 'module' object has no attribute 'lru_cache' while installing Django 2
I'm using ubuntu and I got python 2.7 and python 3.4.3 installed on my OS. I'm trying to install Django 2 and it does not supports python 3, I get this error while trying to install it using pip install -U Django or pip install Django --upgrade: Traceback (most recent call last): File "", line 17, in File "/tmp/pip_build_alex/Django/setup.py", line 32, in version = import('django').get_version() File "django/init.py", line 1, in from django.utils.version import get_version File "django/utils/version.py", line 61, in @functools.lru_cache() AttributeError: 'module' object has no attribute 'lru_cache' Complete output from command python setup.py egg_info: Traceback (most recent call last): File "", line 17, in File "/tmp/pip_build_alex/Django/setup.py", line 32, in version = import('django').get_version() File "django/init.py", line 1, in from django.utils.version import get_version File "django/utils/version.py", line 61, in @functools.lru_cache() AttributeError: 'module' object has no attribute 'lru_cache' I've read this question and another one, only to see that answers are offering OP to install a lower version of django!, but that's not a real answer to such question. I tried alias python=python3 to set python 3 as default python but failed to get a working solution. How can I install Django 2 in a OS with 2 versions of python without getting this … -
Django - could not parse the remainder: '[loop.index] [duplicate]
This question already has an answer here: Django - iterate number in for loop of a template 2 answers Both name and data are lists being returned from a view template: {% for row in data %} <table class="table"> <tr> <td>{{% name[loop.index] %}}</td> </tr> {% for league in row %} <tr> <td>{{ league.name }}</td> </tr> {% endfor %} </table> {% endfor %} Exception: Django Version: 1.11.7 Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: '% name[loop.index] %' from '% name[loop.index] %' any help would be appreciated -
Exited with exit code 3 on running heroku local
I tried to use the heroku command line tool following the tutorial on https://devcenter.heroku.com/articles/heroku-local It exited with exit code 3. $ heroku local [OKAY] Loaded ENV .env File as KEY=VALUE Format 01:53:43 web.1 | [2017-12-30 01:53:43 +0000] [13114] [INFO] Starting gunicorn 19.4.5 01:53:43 web.1 | [2017-12-30 01:53:43 +0000] [13114] [INFO] Listening at: http://0.0.0.0:5000 (13114) 01:53:43 web.1 | [2017-12-30 01:53:43 +0000] [13114] [INFO] Using worker: sync 01:53:43 web.1 | [2017-12-30 01:53:43 +0000] [13119] [INFO] Booting worker with pid: 13119 01:53:43 web.1 | [2017-12-30 01:53:43 +0000] [13119] [ERROR] Exception in worker process: 01:53:43 web.1 | Traceback (most recent call last): 01:53:43 web.1 | File "/usr/lib/python2.7/dist-packages/gunicorn/arbiter.py", line 515, in spawn_worker 01:53:43 web.1 | worker.init_process() 01:53:43 web.1 | File "/usr/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 122, in init_process 01:53:43 web.1 | self.load_wsgi() 01:53:43 web.1 | File "/usr/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 130, in load_wsgi 01:53:43 web.1 | self.wsgi = self.app.wsgi() 01:53:43 web.1 | File "/usr/lib/python2.7/dist-packages/gunicorn/app/base.py", line 67, in wsgi 01:53:43 web.1 | self.callable = self.load() 01:53:43 web.1 | File "/usr/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 65, in load 01:53:43 web.1 | return self.load_wsgiapp() 01:53:43 web.1 | File "/usr/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp 01:53:43 web.1 | return util.import_app(self.app_uri) 01:53:43 web.1 | File "/usr/lib/python2.7/dist-packages/gunicorn/util.py", line 366, in import_app 01:53:43 web.1 | __import__(module) 01:53:43 web.1 | File "/home/palak/python-getting-started/gettingstarted/wsgi.py", … -
Highcharts Data Parsing List of lists
I'm using Django and I am trying to parse the data I am putting into my template to load into high charts. This is the first I'm using High Charts and I was unable to locate a way of parsing it this way. Right now my data is presented like [["Date", "Product1", "Product2"],["Dec 28 2017", 2, 2], ["Dec 29 2017", 2, 2]] How do I make a column chart where the bars are under each day. Thanks -
Does Django automatically detect the end user's timezone?
I am building an application in Django which allows the end-user to retrieve information which is sensitive to the time of day (12 am to 12 am) on a given day. I store this information in my database as an integer representing the seconds since midnight in 30-minute increments. I was looking at Django's timezone documentation: https://docs.djangoproject.com/en/2.0/topics/i18n/timezones/ and found myself confused on whether or Django automatically uses the end-users time, or if I must collect this information and account for it in my views. Any information would be helpful! Thanks. -
Get parameter value in template
I have such url pattern: url(r'^drinks/(?P<drink_name>\D+)/',TemplateView.as_view(template_name='drinks/index. html'),name="drink") How can I get access to drink_name parameter value in template.