Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot change thread mode after it is set IIS django
I have created a project using django and i have used COMtypes for accessing power-point. It is working fine on local host development but when i hosted it on IIS its giving me error "Cannot change thread mode after it is set". comtypes.CoInitializeEx(comtypes.COINIT_MULTITHREADED) powerpoint = comtypes.client.CreateObject("PowerPoint.Application") powerpoint.Visible = 1 powerpoint_file = powerpoint.Presentations.Open(download_path) powerpoint_file.SaveAs(convert_path, 32) powerpoint_file.Close() powerpoint.Quit() comtypes.CoUninitialize() -
Django ORM get only field in foreignkey relationship
I have database tables like this class Message(models.Model): text = models.CharField(max_length=200) length = models.CharField(max_length=100) receivers = models.IntegerField() Network(models.Model): name = models.CharField(max_length=100) is_down = models.BooleanField(default=False) class SMSLog(models.Model): receiver = models.CharField(max_length=200) message = models.ForeignKey(Message, related_name='log') network = models.ForeignKey(Network) status = models.CharField(max_length=200) I need just three fields in my query i.e. text, log__receiver and log__network__name. I tried like this Message.objects.all().prefetch_related('log').only('text', 'log__receiver', 'log__network__name') The above query does not work. How to do query like above in django ORM ? -
admin specific app in django
I'm using Django 1.11 I want to create an admin specific app which is only accessible by admin interface. I want to create an app to add country and state records which can be added or edited only by Admin from /admin. Also, these records can be used by any application to populate a select field in adding a record like address. Where to create a model for this? Is it possible to create a admin specific app only? -
NameError: name 'sheet' is not defined
I got an error,NameError: name 'sheet' is not defined .I wanna parse excel and print the content. I wrote class ReadData(): def __init__(self, sheet_path): self.book = xlrd.open_workbook(sheet_path) self.sheet = self.book.sheet_by_index(1) self.companies = [] def read(self): for row_index in range(2, sheet.nrows): rows = sheet.row_values(row_index) print(rows) x = ReadData('./data/excel1.xlsx') x.read() I really cannot understand why this error happens.Should I add something to use init ?How can I fix this? -
django user management adding user with ajax
In django library, there is a user management where it allows adding of users to the database. I have a web page that allows creation of user, but what I want to do is to be able to create users remotely from another domain, by posting the username password etc over ajax to django. in urls.py: url(r'^user/add/$', UserCreateView.as_view(), name='user_add'), views.py: class UserCreateView(SingleObjectCreateView): user = UserForm view_permission = permission_user_create def form_valid(self, form): user = form.save(commit=False) user.set_unusable_password() user.save() messages.success( self.request, _('User "$s" created successfully.') % user ) return HttpResponseRedirect( reverse('user_management:user_set_password', args=(user.pk,)) ) my ajax post from the other domain: $.ajax({ type: "POST", url: "https://mydjangourl/accounts/user/add/", data: { username: "testusername", first_name: "firstname", last_name: "lastname", is_active: "on", submit: "" } }); When I created a user from my django app, I compared the form data being posted with my personal JavaScript app, both posted the same form data over, but when I checked the database no new user was being created from my personal app.. Am I posting it wrongly? Note: csrftoken authentication has been disabled as it is not required. We are running in an offline environment. -
Compare with return value from a simple_tag
I'm using simple_tag to compute a value in django template. My current code looks like, {% for param_a in params_A %} {% for param_b in params_B %} <p>{% awesome_tag param_a param_b %}</p> # other_stuffs {% endfor %} {% endfor %} Now I want to skip other_stuffs if the returned value from awesome_tag is foo. I know I can do this in the view and then pass the items in the context, but I was wondering if there's any better Django template way to do this. -
Custom Authentication Backend in Django
How to write a custom authentication backend in Django taking scenario as Phone Number & OTP(One-Time Password) to authenticate against each user. How to authenticate each user in form of multiple conditions. If email is verified and password exist ( authenticate using email and password). If phone is verified and exist( authenticate using phone and otp or if password exist then auth using phone and password). -
Full Calendar in Django show events
I am new to both Django & FullCalendar so any assistance that can be provided is greatly appreciated. My ultimate aim is to display events from an O365 calendar in Django using FullCalendar. Putting aside the O365 integration for now at this stage I am just trying to get FullCalendar to display the current events in my model. I have tried to emulate the solutions posted here FullCalendar in Django and here Fullcalendar Does not display data but unfortunately the events are not displaying. Here is my code: models.py from my app called "bookings" from django.db import models class Events(models.Model): event_id = models.AutoField(primary_key=True) exchange_id = models.CharField(max_length=255,null=True,blank=True) event_start = models.DateTimeField(null=True,blank=True) event_end = models.DateTimeField(null=True,blank=True) event_subject = models.CharField(max_length=255,null=True,blank=True) event_location = models.CharField(max_length=255,null=True,blank=True) event_category = models.CharField(max_length=255,null=True,blank=True) event_attendees = models.CharField(max_length=255,null=True,blank=True) def __str__(self): return self.event_subject views.py. I've commented out the bits from the other solutions posted that relate to drop selection of category type. I have also tested using the below script in bookings.views.py, without success. from bookings.models import Events @method_decorator(login_required, name='dispatch') class CalendarPage(TemplateView): template_name = 'calendar.html' def event(request): all_events = Events.objects.all() # get_event_types = Events.objects.only('event_category') # if filters applied then get parameter and filter based on condition else return object if request.GET: event_arr = [] # … -
Trying to use CSS in Django Hello World
Right now I'm trying to use some basic CSS in my Django Hello World program. I can get "Hello World" to display, but the CSS effect isn't work. Currently this is what I have in my main URL: from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'',include('firstapp.urls')), ] And this is what I have in my app URL. from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), ] This is my views file. from django.shortcuts import render from django.http import HttpResponse def index(request): context = {"variable":"Hello World"} return render(request, "base.html", context) My base.html file {% load staticfiles %} <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Title of the document</title> <link rel='stylesheet' href='{% static "css/base.css" %}'/> </head> <html> <p>{{ variable }}</p> <script src="{% static "base.js'" %}"></script> </body> </html> And my base.css file. h1 { color: 00FFFF; } Lastly, I added this piece of code on the bottom of my settings file. STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn") Ideally the page should show up with "Hello World" in a cyan color...unfortunately it just shows "Hello World" in … -
Validate and get the user using the jwt token inside a view
I am using django-rest-framework for the REST API. Also, for JSON web token authentication I am using django-rest-framework-jwt. After a successful login, the user is provided with a token. I have found how to verify a token with the api call, but is there any way to validate the token inside a view and get the user of that token, similar to request.user? -
Static Files are not found (404) when Debug is False
I want to see how my app works in production and i changed settings in my local machine, so i used below settings in settings.py DEBUG = False ALLOWED_HOSTS = ['127.0.0.1', 'localhost'] STATIC_URL = '/assets/' STATIC_ROOT = os.path.join(BASE_DIR, 'assets/') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) I used python manage.py collectstatic which copied all the files from folder static to assets when i set Debug = True files served from assets with 200, one example (http://localhost:8000/assets/js/jquery-2.2.4.js) but when i set Debug = False the static files are not found with 404 error. -
How to resolve “django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: users” in Django 1.7?
Show me this error, Im working on Django 1.7, What's the problem and how do I resolve it? -
How do you integrate Brackets LivePreview with a Django project?
How do you integrate Brackets LivePreview with a Django project running the built in web server (i.e. manage.py server). The LivePreview is taking the absolute path of the html files. Anybody knows? -
Restrict form field choices based on previous model choice in Django
I am currently attempting to create a DnD 5e Character creator using Django and SRD materials provided by WoTC. This is the first time I have ever used Django, and I am learning it as I go. I have come up against a bit of a challenge that has stone-walled me for a few days now. I have researched the issue, and after applying multiple techniques I thought may help, I've had limited luck. My question is this: I have a number of models representing Heroes, Races, Subraces, Classes, Backgrounds and so forth. I wish to be able to restrict a users ability to choose a Subrace, based on their selection of a race beforehand. So far I have this: models.py class Race(models.Model): race_name = models.CharField(max_length=200) race_size = models.CharField( max_length=2, choices=SIZE_CHOICE, default='M') race_speed = models.IntegerField( default=30) race_lang = models.CharField(max_length=200, null=True, blank=True) race_str = models.IntegerField(default=0, null=True, blank=True) race_dex = models.IntegerField(default=0, null=True, blank=True) race_con = models.IntegerField(default=0, null=True, blank=True) race_int = models.IntegerField(default=0, null=True, blank=True) race_wis = models.IntegerField(default=0, null=True, blank=True) race_cha = models.IntegerField(default=0, null=True, blank=True) skill_spend = models.IntegerField(default=0, null=True, blank=True) race_extra = models.TextField(max_length=2000, blank=True, null=True) race_source = models.CharField(max_length=200, blank=True) def __str__(self): return self.race_name class Meta: verbose_name = 'Race' verbose_name_plural = 'Races' class Subrace(models.Model): sub_name … -
Django 404 page goes to 500 page when there is a closing body tag in the template
We use Django 1.11 in our platform which is made up of quite a few applications. I am currently updating the look of our current 404 and 500 pages. I have an Error page Template and the 404 and 500 extend that template. When testing using an incorrect URL I am always diverted to the 500 page instead of the 404. If I remove the closing body tag from the template the 404/500 uses the and test with an incorrect URL the 404 page test fine. To Note: I have also tried hard coding a simple 404.html and whenever adding a closing body tag this issue still happens. Any ideas why the body tag could/would affect the 404 page loading in this way? -
Finding the Cross-Section of two List views in one Django template
I have two models that feed one view. models.py class Item(models.Model): item_name = models.CharField(max_length=100) item_type = models.ForeignKey(Item_type, on_delete=models.SET_NULL, null=True) owned_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)**** added_at = models.DateTimeField('date item added') updated_at = models.DateTimeField('last update') def __str__(self): return self.item_name class Item_status(models.Model): item = models.ForeignKey(Item, on_delete=models.SET_NULL, null=True) borrower = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) loaned_at = models.DateTimeField(default=None, blank=True, null=True) due_back = models.DateTimeField(default=None, blank=True, null=True) def __time__(self): return self.loaned_at def itemname(self): return (self.item.item_name) I have the following view views.py class LoanedItemsByUserListView(LoginRequiredMixin,generic.ListView): model = Item_status template_name ='catalog/item_status_list_borrowed_user.html' paginate_by = 10 def get_queryset(self): return Item_status.objects.filter(borrower=self.request.user).order_by('due_back') def get_context_data(self, **kwargs): context = super(LoanedItemsByUserListView, self).get_context_data(**kwargs) context['Owned_list'] = Item.objects.filter(owned_by=self.request.user, item_type = 1) context['Loaned_list'] = Item_status.objects.exclude(borrower=self.request.user).exclude(borrower__isnull=True) return context I would like to find the cross section of the 'Owned_list' and the 'Loaned_list' in a single template Something like <h2>Loaned Books</h2> {% if Owned_list %} <ul> {% for thing in Owned_list.item_name and in Loned_list.item.item_name %} <li> {{thing}} </li> {% endfor %} </ul {% else %} <p>There are no books in the library.</p> {% endif %} I have take a look at the django documentation here https://docs.djangoproject.com/en/1.11/topics/class-based-views/generic-display/, and around SO but not found exactly what I am looking for. Thanks! -
How to authenticate a user in websocket connection in django channels when using token authentication
I am using a frontend framework (Vuejs) and django-rest-framework for the REST API in my project. Also, for JSON web token authentication I am using django-rest-framework-jwt. After a successful login, the user is provided with a token. This token is passed into every request to fetch any API related stuff. Now I would like to integrate django channels into my project. So, after successful login, when the token is received in the client side, I would like to initiate a websocket connection. Then on the server (consumer), I would like to check if the requested user is not anonymous. If the requested user is anonymous, I would like to close the connenction or else accept it. This is how I have till now: client side: const socket = new WebSocket("ws://" + "dev.site.com"+ "/chat/"); routing.py: channel_routing = [ route("websocket.connect", ws_connect), ... ... ] consumers: def ws_connect(message): # if the user is no anonymous message.reply_channel.send({ "accept": True }) # else message.reply_channel.send({ "close": True }) In the documentation there's a decorator @channel_session_user_from_http which will provide a message.user. But I am using a token instead of a session. How can I check a user on connection when using token authentication, so that I can … -
Django .raw query fails (error 1064) -- but works in SQL
(using django 1.11.2, python 2.7.10, mysql 5.7.18) The following SQL query: SELECT transaction_transaction.id, sec_to_time(avg(time_to_sec(extract(HOUR_SECOND from transaction_transaction.transaction_datetime)))) AS average_time_of_day FROM transaction_transaction INNER JOIN store_store ON (transaction_transaction.store_id=store_store.id) INNER JOIN payment_method_card ON (transaction_transaction.card_id=payment_method_card.id) WHERE ( transaction_transaction.transaction_datetime BETWEEN '2017-08-31 00:00:00' AND '2017-08-31 23:59:59' AND store_store.company_id=2 AND payment_method_card.profile_id=8 ); Runs and returns the following result (as expected): +== id ==+== average_time_of_day ==+ |= 9422 =|===== 20:42:22.8695 =====| (This is run from HeidiSQL) Doing something similar (I think! but something is obviously wrong) via Django: average_time_of_day = Transaction.objects.raw( ''' SELECT transaction_transaction.id, sec_to_time(avg(time_to_sec(extract(HOUR_SECOND from transaction_transaction.transaction_datetime)))) AS average_time_of_day FROM transaction_transaction INNER JOIN store_store ON (transaction_transaction.store_id=store_store.id) %s WHERE ( transaction_transaction.transaction_datetime BETWEEN %s AND %s AND store_store.company_id=%s %s ); ''', [ 'INNER JOIN payment_method_card ON (transaction_transaction.card_id=payment_method_card.id) ' if profile_pk else '', start_datetime, end_datetime, company_pk, 'AND payment_method_card.profile_id=' + str(profile_pk) if profile_pk else '', ] ) Doing print average_time_of_day.query Outputs: SELECT transaction_transaction.id, sec_to_time(avg(time_to_sec(extract(HOUR_SECOND from transaction_transaction.transaction_datetime)))) AS average_time_of_day FROM transaction_transaction INNER JOIN store_store ON (transaction_transaction.store_id=store_store.id) INNER JOIN payment_method_card ON (transaction_transaction.card_id=payment_method_card.id) WHERE ( transaction_transaction.transaction_datetime BETWEEN 2017-08-31 00:00:00 AND 2017-08-31 00:00:00 AND store_store.company_id=2 AND payment_method_card.profile_id=8 ); And Django returns with the following error: ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the … -
Django Models Relationship Confusions
I have the following models: class UserPost(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) class User(AbstractUser): MALE = 'M' FEMALE = 'F' GENDER_CHOICES = ( (MALE, 'Male'), (FEMALE, 'Female') ) posts = models.ManyToManyField(Post, through='UserPost') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=100) content = models.TextField() status = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) When I run python manage.py makemigrations, it raises the following error: users.User.posts: (fields.E303) Reverse query name for 'User.posts' clashes with field name 'Post.user'. HINT: Rename field 'Post.user', or add/change a related_name argument to the definition for field 'User.posts'. There is a many-to-many relationship between User and Post models. Each user can like many posts and each post can be liked by many users. There is also a many-to-one relationship between User and Post models. Each user can write many posts and each post can be written by only one user. Shouldn't reverse query name for 'User.posts' be user_set by default. If so, why is this name clashing with field name 'Post.user'? Can someone explain the meaning of this error? Thanks. -
django - how to make clickable html text that sends data to model?
I want to display users around 10 clickable html "tags" (just text with some css that changes when clicked) on my form page. I want them to be able to select a maximum of 3 tags but no minimum requirement. I then want to take the sum of all clicks for each individual tag and do some calculations with them as a model method, like return the 3 most clicked tags. It's important that my tags are on the form page and are submitted at the same time as the form. So I guess they have to be part of my form. How would I go about doing this? An actual example would be tremendously helpful as I'm still very new to django and find the documentation (which I've looked at) somewhat hard to understand. -
Django template Module Import Error
Using Django version 1.9.5 and Python 3. Upon navigation to the url, I am getting the following error: ImportError at /music/ No module named 'django.templates' Request Method: GET Request URL: http://localhost:8000/music/ Django Version: 1.9.5 Exception Type: ImportError Exception Value: No module named 'django.templates' Exception Location: D:\Program Files (x86)\Python\lib\importlib\__init__.py in import_module, line 126 Python Executable: D:\Program Files (x86)\Python\python.exe Python Version: 3.5.0 Python Path: ['C:\\Users\\ang\\Desktop\\website', 'D:\\Program Files (x86)\\Python\\lib\\site-packages\\django-1.9.5-py3.5.egg', 'D:\\Program Files (x86)\\Python\\python35.zip', 'D:\\Program Files (x86)\\Python\\DLLs', 'D:\\Program Files (x86)\\Python\\lib', 'D:\\Program Files (x86)\\Python', 'D:\\Program Files (x86)\\Python\\lib\\site-packages'] The error seems to be coming from the import line. Checked syntax and tried to explicitly provided the path under TEMPLATES at DIRS but same result. Anyone encountered a similar issue? Found some similar issues raised but in different languages. Folder Structure for template: name_of_app/templates/inner_folder/html_file music/templates/music/index.html views.py from django.http import HttpResponse from django.template import loader # error gone if i remove this line from .models import Album def index(request): all_albums = Album.objects.all() template = loader.get_template('music/index.html') context = { 'all_albums': all_albums } return HttpResponse('test test') settings.py TEMPLATES = [ { 'BACKEND': 'django.templates.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.templates.context_processors.debug', 'django.templates.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] -
cache busting in django using CachedStaticFilesStorage
Using django 1.8, when I put STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.CachedStaticFilesStorage' in my settings.py, all the static files are no longer accessible. The app tries to look for https://hostname/static/jquery-ui-1.11.4/jquery-ui.d3260250e777.css instead of https://hostname/static/jquery-ui-1.11.4/jquery-ui.css I'm using nginx with memcached. Any ideas what I'm doing wrong? -
PayPal Authorize code not accepted - Django
I am trying to integrate PayPal into a django project that I am working on and I am getting an issue related to the Authorize code which is not giving me access to the api within my project when i try to run my server. Here is the code that I have inside of my views.py file. import paypalrestsdk from paypalrestsdk.openid_connect import Tokeninfo, Userinfo CLIENT_ID_PAYPAL = "...Y2tf" CLIENT_SECRET_PAYPAL = "...9PIej" paypalrestsdk.configure({ "mode":"sandbox", "client_id":CLIENT_ID_PAYPAL, "client_secret":CLIENT_SECRET_PAYPAL, "opentid_redirect_uri":"http://127.0.0.1", }) # the following is going open the connection for the paypal openid connection login_url = Tokeninfo.authorize_url({"scope":"openid profile"}) tokeninfo = Tokeninfo.create("access_token$sandbox$...72373be5e") tokeninfo = tokeninfo.refresh() tokeninfo = Tokeninfo.create_with_refresh_token(tokeninfo) userinfo = tokeninfo.userinfo() userinfo = Userinfo.get("access_token$sandbox$...172373be5e") logout_url = tokeninfo.logout_url() I am getting an access denied message within my terminal. paypalrestsdk.exceptions.BadRequest: Failed. Response status: 400. Response message: Bad Request. Error message: {"error_description":"Invalid authorization code","error":"access_denied","correlation_id":"...52866","information_link":"https://developer.paypal.com/docs/api/#errors"} Does anyone know how to where to get my authorization code because I have looked through the entire paypal developer site and I couldn't find it. -
Django - access class-based view's instance from middleware
I would like to do some stuff with views before actually processing them. I learned that process_view method of class-based middlewares might be helpful here. But the problem is that the only thing I managed to get from here is the actual class, but not its instance, which I would like to have. Code approach is as follows: class SomeView(View): class_attribute = "..." def __init__(self, *args, **kwargs): self.instance_attribute = "..." # ... class Middleware: # ... def process_view(request, view_func, view_args, view_kwargs): # access class_attribute print(view_func.view_class.class_attribute) # access instance_attribute print("I don't know, please help, thank you.") -
Django python contact email form error post not allowed 405
I dont know why i get this error in the bash: Method Not Allowed (POST): /curriculum/ [14/Sep/2017 20:47:24] "POST /curriculum/ HTTP/1.1" 405 0 views.py: from django.views.generic import TemplateView from Profile.forms import ContactForm from django.core.mail import send_mail, BadHeaderError, EmailMessage from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render, redirect from django.template import Context from django.template.loader import get_template Create your views here. class HomePageView(TemplateView): def get(self, request, **kwargs): return render(request, 'index.html', context=None) class ProjectsPageView(TemplateView): template_name = 'projects.html' class TutorialsPageView(TemplateView): template_name = 'tutorials.html' class ArticlesPageView(TemplateView): template_name = 'articles.html' class LanguagesPageView(TemplateView): template_name = 'languages.html' class VideosPageView(TemplateView): template_name = 'videos.html' class CurriculumPageView(TemplateView): template_name = 'curriculum.html' def post(self, request, **kwargs): form_class = ContactForm # new logic! if request.method == 'POST': form = form_class(data=request.POST) if form.is_valid(): contact_name = request.POST.get( 'contact' , '') contact_email = request.POST.get( 'email' , '') form_content = request.POST.get('message', '') # Email the profile with the # contact information template = get_template('templates/contact_template.txt') context = Context({ 'contact_name': contact_name, 'contact_email': contact_email, 'form_content': form_content, }) content = template.render(context) email = EmailMessage( "New contact form submission", content, "Your website" +'', ['juanmacedoal@gmail.com'], headers = {'Reply-To': contact_email } ) email.send() return redirect('curriculum') return render(request, 'PageJMMA/Profile/templates/index.html', { 'form': form_class, }) url.py: from django.conf.urls import url from Profile import views urlpatterns = [ …