Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
letsencrypt standalone certification not showing up on GET request
I was able to create certifications under the path /etc/letsencrypt/{{mywebdomain}}/ and set under my server where the ssl_cert and ssl_cert_key absolute pathfile locations for my nginx server. When I run the command sudo nginx -t I receive a successful configuration output and the nginx server is running in the reverse proxy for Django without any problems. But when I access the root of my website on my chrome browser, I'm receiving the "http://website.com" instead of "https://website.com". Please point me in the right direction if anyone was able to correctly encrypt their domain content with gunicorn-django-nginx configuration. My website snippet conf: upstream app_server { unix:/home/me/Documents/masterdomain/src/portfolio_revamp.sock; } server { client_max_body_size 4M; listen 80; listen [::]:80; listen 443 ssl; listen [::]:443 ssl; listen www.mysite.com:80; server_name example.com www.example.com; http://example.com; ssl_certificate /etc/letsencrypt/live/mysite.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/mysite.com/privkey.pem; root /home/akeem/Documents/SpencerMaster/src; index templates/home.html templates/main.html; location / { proxy_pass http://unix:/home/me/Documents/masterdomain/src/portfolio_revamp.sock; alias /home/me/Documents/master/templates/home.html; } location ~ /.well-known { allow all; } location /static { autoindex on; alias /home/me/Documents/masterdomain/static; } location /media { autoindex on; alias /home/me/Documents/masterdomain/media; } } I'm running a xenial ubuntu 16.04 server if that makes a difference. -
python.exe the fastcgi process exited unexpectedly
i have some reasons witch i am stuck to use django on windows machine. i was wondering how to configure django on a windows sesrver 2012 r2 with iis 8.5. so i followed the tutorial here. i did what the tutorial says and it is pretty much straight forward what i am gonna do for any kind of application i want to run with iis. but i get the following error the fastcgi process exited unexpectedly. here is what i have provided as executable for wfastcgi module: E:\venvs\...\Scripts\python.exe|E:\venvs\...\Lib\site-packages\wfastcgi.py i removed the wfastcgi.py part after | from handler mapping and error changed to script processor could not find the config for fastcgi configuration and i figured out the error must be related to the wfastcgi.py file. but i could not find the issue here. so i was wondering what can be the issue? and what are my options are here. has any one been able to use django on a windows machine?? -
Django - 2 URLS with same regex, but different variables and views
I have the following urls: url(r'^(?P<college_name>\w+)/$', views.detail, name="detail"), url(r'^(?P<photographer_username>\w+)/$', views.photographer, name="photographer"), It works when I do /college_name url, but when typing in a photographer such as website.com/johnsmith it only searches the first url pattern and then stops. If I put the photographer url pattern first, it works for photographers and not for colleges. How do I fix it so it works for both? -
Order of ManytoMany field in model changed when one object is replaced
I am trying to build a publication database for researchers. So my database has model classes Paper, Author and Journal. Journal is a foreign key to Paper while Author is a ManytoMany key to Paper. The model definition is thus: from django.db import models from django import forms from django.forms import ModelForm, Textarea # Create your models here. class Journal(models.Model): name = models.CharField(max_length = 100) organization = models.CharField(max_length = 100, blank = True) def __unicode__(self): return self.name class Author(models.Model): first_name = models.CharField(max_length = 20, blank = True) last_name = models.CharField(max_length = 20, blank = True) middle_name = models.CharField(max_length = 20, blank = True) full_name = models.CharField(max_length = 50) email = models.EmailField(blank = True) def __unicode__(self): return self.full_name class Paper(models.Model): paper_title = models.CharField(max_length=200) paper_year = models.IntegerField(blank = True, null = True) paper_volume = models.CharField(max_length = 100, blank = True, null = True) paper_number = models.CharField(max_length = 100, blank = True, null = True) paper_pages = models.CharField(max_length = 100, blank = True, null = True) paper_month = models.CharField(max_length = 15, blank = True, null = True) paper_doi = models.CharField(max_length = 50, blank = True, null = True) paper_abstract = models.TextField(blank = True, null = True) paper_keywords = models.TextField(blank = True, null = … -
Multiple Django apps under the same site
I am thinking of creating a content delivery web application using Django with a MySQL database, and after reading the docs a bit I noted that it is possible to create multiple apps in the same project/site directory. It may or may not apply to what I want to do, but I was wondering what the motivation behind this architecture is. Why would I want multiple web apps in one site? For example, Youtube was built around the Django framework, but the entire experience works seamlessly as one application? Is Youtube actually one large web application, or does the project use many applications packaged as one product? If so, why would that be a better option? -
Google OAuth for Calendar in Django
I'm trying to obtain access to some users' Google Calendars and for that I need to use OAuth. I have the following code in views.py: from django.shortcuts import render from django.http import HttpResponse from oauth2client.contrib.django_util.storage import DjangoORMStorage as Storage from oauth2client.client import flow_from_clientsecrets from app.models import CredentialsModel OAUTH_SCOPE = 'https://www.googleapis.com/auth/calendar' REDIRECT_URI = 'https://thisisinvented.jorgebaron' def index(request): #setting flow to get permission and code flow = flow_from_clientsecrets( '../client_id.json', scope=OAUTH_SCOPE, redirect_uri=REDIRECT_URI) authorize_url = flow.step1_get_authorize_url() code = request.GET.get('code', '') if code: #setting flow step2 to exchage code for access token credential = flow.step2_exchange(code) #initialising httplib2 instance and building a DriveAPI service http = httplib2.Http() http = credential.authorize(http) user, created = User.objects.get_or_create(username=username, email=email) #saving credentials to database if created == True: storage = Storage(CredentialsModel, 'id', user, 'credential') storage.put(credential) return HttpResponseRedirect('good to go') else: return HttpResponseRedirect(authorize_url) and when running python manage.py runserver get oauth2client.clientsecrets.InvalidClientSecretsError: Missing property "redirect_uris" in a client type of "web". Any clue of how to fix this? Thanks -
How to seperate Python Intepreter from Web Server in Django
Im making an app in django that contains a part tha does heavy calculations .I was wondering if i could execute the python code on a machine, then send the results on another machine that will run the webserver and django eachself .Can it be done ?if so please give some information on how i could do that .I want to make this happen because the system will crash if I make the calculations and serve the django application under the same machine . -
django case sensitive url changes the case automatically
I am using the following regex for my urls. url(r'^(?P<slug>[a-zA-Z0-9_-]+)/$',short_url, name='short_url') the URL is suppose to be case sensitive because I setup it that way in mysql for the slug field. when I do mysql query it does exactly what it is suppose to be. but when I change one letter like 'Y' http://127.0.0.1:8000/p/Y9j4oL/ to 'y' , django redirects to the above url again. http://127.0.0.1:8000/p/y9j4oL/ why is this happening ? and how to fix it? -
How would I compare two values with eachother? Django
In my template I have two models being displayed for comparison of cars. The cars have various attributes such as mileage, cost, fuel consumption etc. How would I compare those two variables? I know this can be done by using the "abs" function in python, but will it work within the template? --------------------------------------------- Car 1 Mileage | Comparsion | Car 2 Mileage --------------------------------------------- 643 | ? | 353 --------------------------------------------- An example of my template ^ -
The view music.views.favorite didn't return an HttpResponse object. It returned None instead
enter image description here Traceback (most recent call last): File "C:\Python34\lib\site-packages\django-1.10.6-py3.4.egg\django\core\handlers\exception.py", line 42, in inner response = get_response(request) File "C:\Python34\lib\site-packages\django-1.10.6-py3.4.egg\django\core\handlers\base.py", line 198, in _get_response "returned None instead." % (callback.module, view_name) ValueError: The view music.views.favorite didn't return an HttpResponse object. It returned None instead. [11/Mar/2017 15:34:57] "POST /music/1/favorite/ HTTP/1.1" 500 56886 -
Import custom module to Django
I'm making a django app and cannot import a custom module inside the views.py file. I'm trying to import class "Integrate" from auth.py inside modules folder from integrations/views.py I tried placing __init.py inside the app folder and modules folder but still doesn't work. views.py: from ..modules.auth import Integrate Powershell: from ..modules.auth import Integrate ValueError: Attempted relative import beyond toplevel package -
not arguments fully converted during string formatting
z = request.session['username'] mysqlquery is cursord.execute("delete from table where column = %s",z) getting error as not arguments fully converted during string formatting How to solve this? -
My flask project is not working when I try running it on localhost
I am trying to create a basic web-app with python in flask, however it does not let me view the output on my browser, I feel that my code is adequate, is it an issue with my computer? Should I change some settings? from flask import Flask app = Flask(__name__) @app.route('/') def index(): return ("This is the homepage") if __name__ == "__main___": app.run(debug = True) -
Django remove duplicates in queryset and access their list of foreign key
Here is my model: class Item(models.Model): title = models.TextField() class Storage(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) item = models.ForeignKey(Item, on_delete=models.CASCADE) rating = models.IntegerField(blank=True, null=True) review = models.CharField(max_length=1500, blank=True, null=True) class SocialProfile(models.Model): user = models.OneToOneField(User, unique=True) follows = models.ManyToManyField('self', related_name='followed_by', symmetrical=False) Say there are 4 users A,B,C,D. User A follows only B and C. I'm trying to do a view that when log in as User A. Show a list of items that B and C has (duplicates show only one time). And under each item, show their summary and ratings. I have something here: (user = User A here) //get a list of users that User A follows followings = user.socialprofile.follows.all() //get B and C's saved item, eliminate the duplicates context['following_saved_article'] = Item.objects.filter(storage__user__in=followings.values('user')).distinct() //get a flat list of all users A follows context['followings'] = list(followings.values_list('user', flat=True).order_by('user')) Then in the template: {% for item in following_saved_item %} {{ item.title }} {% for x in item.storage_set.all %} {% if x.user_id in followings %} {{ x.review }} {{ x.rating }} {% endif %} {% endfor %} {% endfor %} This seems too redundant, and I will have a pretty hard time if I want to sort reviews by user rating. Any suggestions? Thanks -
Django: select data from two tables with foreigin key to thrid
I have following models: class ProcessedText(models.Model): text_id = models.ForeiginKey('Text') word_id = models.ForeignKey('Dictionary') class Dictionary(models.Model): word = models.CharField(unique=True) class UserDictionary(models.Model): word_id = models.ForeignKey('Dictionary') user_id = models.ForeignKye('User') I want to make query using django ORM same with next sql SELECT * FROM ProcessedText, UserDictionary WHERE ProcessedText.text_id = text_id AND ProcessedText.word_id = UserDictionary.word_id AND UserDictionary.user_id = user_id How to do it in one query without using cycles? -
Alternative Admin in Django
Hello guys I would like to know if there's a way NOT to override Django Admin, but to build your own, with a custom template. I have searched on the internet but there seems to be no answer. I hope there is a person who knows the answer to my question. -
How can I convert a python object to string using the context?
I am trying to render object instances in django templates the way forms do it. So somewhere in a view an object instance gets created: my_object = MyObject() and passed to the template in the context: context['my_object'] = myobject. When the template is processed, the __str__() method of MyObject is called to create a string to be filled in. For MyObject it looks something like this: def __str__(self): """ Render template """ return mark_safe( render_to_string(self.template, {'options': self.options}) ) Since the object's template would like to add code to the CSS and JS blocks using sekizai, I need the rendering context. Is there a way (e.g., using an different method) to get this context? -
Django form Validation error not showing up also the form is not authenticating
Outcome needed : My main aim is to get a guest login that is user adds email address and then django checks for the email in the database if it finds one then error is shown else user is logged in. Problem : In my form when I add an email address then Django adds the email in the database but if I add that email again no error is shown also I am not being logged in Django. Version Using: appdirs==1.4.2 cffi==1.9.1 cryptography==1.7.2 Django==1.8.4 django-crispy-forms==1.6.1 django-registration-redux==1.4 enum34==1.1.6 idna==2.4 ipaddress==1.0.18 olefile==0.44 packaging==16.8 Pillow==4.0.0 pyasn1==0.2.3 pycparser==2.17 pyOpenSSL==16.2.0 pyparsing==2.1.10 requests==2.13.0 six==1.10.0 forms.py from django import forms from django.contrib.auth import get_user_model User = get_user_model() class GuestCheckoutForm(forms.Form): email = forms.EmailField() email2 = forms.EmailField(label='Verify Email') def clean_email2(self): email = self.cleaned_data.get("email") email2 = self.cleaned_data.get("email2") if email == email2: user_exists = User.objects.filter(email=email).count() if user_exists != 0: raise forms.ValidationError("This User already exists. Please login instead.") return email2 else: raise forms.ValidationError("Please confirm emails are the same") views.py from django.contrib.auth.forms import AuthenticationForm from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect, Http404, JsonResponse from django.shortcuts import render, get_object_or_404, redirect from django.views.generic.base import View from django.views.generic.detail import SingleObjectMixin, DetailView from django.views.generic.edit import FormMixin # Create your views here. from orders.forms import GuestCheckoutForm … -
Use of request parameter in view functions
def choice(request): return render(request,'LoginPage/choice.html') This is a sample view function from my views.py file. What's the use of the request parameter in the function call? Can it be used to keep a record of the user logged in when surfing the website? I'm really new to django. Please help -
Dynamic form choice/option field in djnago
I have made this web app https://notes12345.herokuapp.com The code of this app is here :- https://github.com/theparadoxer02/Notes What is want is to make the search form in such a way that when user select the year the choices for branches get generated dynamically , means only that branch options should come that of selected year, when when one is done selecting the branch , then the options for subjects should come that are related to selected year,branch above. So in this way i want to generate form . What should i learn? where should i modify file in views.py or models.py ? I am stuck with that . -
'QueryDict' object has no attribute 'association'
I try to register a member with same association-name as the admin but it throws me this error. Is there something i'm missing? Still a newbie so appreciate your help, folks! admin\models.py class Administrator(AbstractUser): ... association= models.ForeignKey(Association) class Meta: db_table = 'Member' member\models.py from pl.admin.models import Administrator class Association(models.Model): asoc_name = models.CharField(max_length=100) class Meta: db_table = 'Association' def __str__(self): return self.asoc_name forms.py class RegForm(forms.ModelForm): ... association = forms.ModelChoiceField(queryset=Association.objects.none()) ... class Meta: model = Administrator fields = [..., 'association', ...] def __init__(self, user, *args, **kwargs): super(RegForm, self).__init__(*args, **kwargs) self.fields['association'].queryset = Association.objects.filter( asoc_name=user.association) views.py def member_signup(request): if request.method == 'POST': form = RegForm(request.POST, request.user) if not form.is_valid(): return render(request, 'member/member_signup.html', {'form': form}) else: ... asoc = form.cleaned_data.get('association') ... Member.objects.create(... association=asoc, ...) user = authenticate(... association=asoc, ...) return redirect('/') else: return render(request, 'member/member_signup.html', {'form': RegForm(request.user)}) -
Django Oscar doesn't see products
I was added a new category, then I was added product type, then I was added a product. *screenshoot I can see my new category, but there is no products at all *screenshoot But, I can view it on my site follow link localhost:8080/catalogue/zelenaia-kraska_6/ . I can get this link from dashboard (product -> actions -> view on site) How to fix this problem? -
Django membership/dashboard plugin
I want to create a membership website where users can log in to a control panel separated from the admin panel. Inside the control panel users can edit their settings, view statistics and use paid services. What are the plugins I need to build this kind of websites? How I can improve the security and automate the workflow ? -
Provide default django login view under a url argument
What I want to lay out is a design that works similar to the following. I have a urls.py definition like: url(r'^(?P<slug>[-\w]+)/login/$', auth_views.login, name='customer_login'), url(r'^(?P<slug>[-\w]+)/logout/$', auth_views.logout, {'next_page': 'customer_login'}), where the slug identifies some client and I want to provide a login view for each client. What I am basically struggling with at the moment is the fact that the default django login view can't handle the additional kwarg slug. And I also want all the redirect_to links from the login & logout view to be based on that slug value. My question: Is there some solution for this problem? Is the above layout a bad design and should it be handled differently? -
Django add new object
I have project_detail page. Inside that page I have link which will redirect user to another page where user can add new members to current project. As you see from the code below I created form with 2 fields user and role. How to associate new members with current project? I tried next code but I have error when try to save new member. Here below you can see full trackback also. It seems to me system dont know in what project must be new member. I tested with 2 databases the sqlite and MS SQL SERVER. The result was same in both of them. How to fix this error. models.py: class Project(models.Model): ***FIELDS*** members = models.ManyToManyField(User, through='Membership',) class Membership (models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,) project = models.ForeignKey(Project, on_delete=models.CASCADE) role = models.CharField(max_length=20, choices=ROLE_CHOICES,) forms.py: class ProjectMembersForm(forms.ModelForm): class Meta: model = Membership exclude = ('project',) views.py: def project_detail(request, project_id): project = get_object_or_404(Project, pk=project_id, status='public') return render(request, 'project/project_detail.html', {'project': project}) def add_project_member(request, project_id): project = get_object_or_404(Project, pk=project_id) if request.method == 'POST': form = ProjectMembersForm(request.POST) if form.is_valid(): new_member = form.save() new_member.save() return render(request, 'project/project_detail.html', {'project': project, 'new_member': new_member}) else: form = ProjectMembersForm() return render(request, 'project/project_members.html', {'project': project, 'form': form}) urls.py: url(r'^projects/(?P<project_id>\d+)/$', project_detail, name='project_detail'), …