Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Email verification after signup code working good but not email send
How to solve this problem that code run work and terminal show that Content-Transfer-Encoding: 7bit Subject: Activate your service account. From: webmaster@localhost To: yeasincse2012@gmail.com Date: Sat, 30 Dec 2017 04:24:49 -0000 Message-ID: <20171230042449.1841.3324@1.0.0.127.in-addr.arpa> Hi uu, Please click on the link below to confirm your registration: http://127.0.0.1:8000/activate/MTc/4sf-5894ea0e96ff8411ac73/ [30/Dec/2017 04:24:49] "POST /signup/ HTTP/1.1" 200 63 when check mail but not mail found? This code given link pastebin.com here that -
Where are the historical models?
The doc says: When you run migrations, Django is working from historical versions of your models stored in the migration files. But I can't see them there. I have data migrations with RunPython operations, but no historical models there as well. Could it be that Django generates them on the fly? How does it do it? And while we're at it, let me confirm if I understand it correctly. Historical models are models as they were when a migration was written? Except for some limitations, like no custom methods. -
Django Custom User admin page
I am currently trying to implement my admin page for the custom user model I have made. I have added a field called 'email_confirmed', and I am trying to get this to display on the Admin page. This is the model: class User(AbstractUser): """User model.""" abstract = True username = None email = EmailField(_('email address'), unique=True) email_confirmed = BooleanField(default = False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'second_name'] objects = UserManager() def get_full_name(self): fname = self.first_name lname = self.last_name return '{} {}'.format(fname, lname) def email_confirmed(self): return self.email_confirmed As you can see I have tried writing a method called email confirmed to get this to work, however it didn't work. This is the UserAdmin I have in my admin.py: @admin.register(get_user_model()) class UserAdmin(UserAdmin): class Meta: model = get_user_model() fieldsets = ( (None, {'fields': ('email', 'password')}), (_('Personal info'), {'fields': ('first_name', 'last_name', 'email_confirmed')}), (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), (_('Important dates'), {'fields': ('last_login', 'date_joined')}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email', 'password1', 'password2', 'email_confirmed()'), }), ) list_display = ('email', 'first_name', 'last_name', 'is_staff', 'email_confirmed') search_fields = ('email', 'first_name', 'last_name', 'email_confirmed') ordering = ('email',) Thanks for the help -
How to create django project in Windows?
I tried of creating project in Windows When I type django-admin.py startproject projectname it takes but it won't created in folder . Everything is installed and previous project also running fine .Please help me out ! -
Migrate existing live Django site from one server to another along with user records intact
I have deployed a Django site on GoDaddy Django "droplet" for a while and users have been using the site to keep their records. Now that GoDaddy is discontinuing the service, I would like to migrate the entire site with all records intact to DigitalOcean. How does one go about doing this? -
Pycharm type hinting for querysets
I use python 2.7 and use docstring for type hinting in pycharm. Having set :rtype of methods to list of ClassName it provides great code completion. I wanted to know whether I can do sth similar for querysets. (eg sth like :rtype: Queryset of ModelName) -
How to append a database table created by a django model
I am following the tutorials https://simpleisbetterthancomplex.com/tutorial/2017/02/18/how-to-create-user-sign-up-view.html on making a simple user registration website. The key model defined in model.py is from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() which creates the table profile in the database. My question is how do we append this table to include information like user's first/last name and email. I know those information is stored in auth_user, but it would nice to have everything on one table. I am new to django platform. Any explanation or reference is greatly appreciated. -
Django Dynamic Form with Json Input
I know this question is bit vague but i could not find exact solution anywhere. I am at loss having very poor knowledge on UI. Any help will be greatly appreciated. I have a simple Json like below passing to site.html template. { "datacenter1" : ["IP1", "IP2",...,"IPn"], "datacenter2": ["IP1", "IP2",...,"IPn"], "datacenter3": ["IP1", "IP2",...,"IPn"], ..... ..... "datacentern": ["IP1", "IP2",...,"IPn"], } I want to create form for User with datacenter as main section with radio button and IPs are subsections with check boxes below datacenter. User should be able to select one datacenter and multiple/all IPs of that specific DC o datacenter1 (Radio) IP1 IP2 IP3 ..IPn (Check) o datacenter2 (Radio) IP1 IP2 IP3 .. IPn (Check) o datacenter3 (Radio) IP1 IP2 IP3 .. IPn (Check) ..... o datacentern (Radio) IP1 IP2 IP3 .. IPn (Check) SUBMIT number of datacenter and its IPs are variable, so Json size keeps varying all the time.I a looking for Django template than take the Json, iterate and create a for that looks like below. I have multiple solutions using bootstrap but no luck. Since I have almost zero knowledge on Javascript, Bootstrap i am so far direction less. -
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')