Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Owner_id cannot be null. DRF relational database
I am building relations with my tables in the database. Currently i have a tutorial lesson with 3 tables. for example (auth_user table, partyEvent table, friends table). Now a user should be able to create just one partyEvent. Friends can join any number of partyEvent created by the users. The owner id in the Friends model tells the partyEvent and User 'the friend' belongs to. I am able to restrict the users to create only one partyEvent. But when i try to register friends to a partyEvent, the owner's id is not sent. Instead the default value in: owner = models.OneToOneField('auth.User', related_name = 'party', on_delete=models.CASCADE, default='1') is rather sent. Why is that happening? models class PartyEvent(models.Model): name = models.CharField(max_length=100, blank=False) location = models.CharField(max_length=100, blank=False) owner = models.OneToOneField('auth.User', related_name = 'party', on_delete=models.CASCADE, default='1') class Friends(models.Model): name = models.CharField(max_length=100, blank=False) owner = models.ForeignKey('auth.User',related_name = 'friends', on_delete=models.CASCADE, default='1') serializers class FriendsSerializer(serializers.HyperlinkedModelSerializer): owner = serializers.ReadOnlyField(source='owner.id') class Meta: model = Friends fields = ('id','name','owner') -
How do you Create Groups and Permissions in Django model from Active Directory Groups with django-python3-ldap?
I have two groups that I have created in django. I created billing_users and billing_admins. I also have two groups of users in ldap, internalBilling-admin and internalBilling-users. I currently have django-python3-ldap authentication working. But I have to log into Django and manually set the user as a is_staff and is_superuser to allow the user to login into the admin the default admin console. In addition, I have to assign them to the group that they belong to. Question 1: Is there a way that I can have the flags automatically set based on the Django group they belong to? Question 2: Is there a way that I can have the Active Directory user's group set the Django group set the user in the proper Django group using django-python3-ldap? The author states the following: The LDAP_AUTH_CLEAN_USER_DATA and LDAP_AUTH_SYNC_USER_RELATIONS settings are your friends here. Check out the docs here: https://github.com/etianen/django-python3-ldap#available-settings But I don't understand how LDAP_AUTH_CLEAN_USER_DATA and LDAP_AUTH_SYNC_USER_RELATIONS work because there are no examples of it being implemented. -
How to show API description with django_rest_swagger 2.1.1
For 0.3 version, DRF is able to read info data in swagger settings and render in swagger UI. SWAGGER_SETTINGS = { ...... "info": { 'contact': 'xxxxx@github.com', 'description': 'This document intends to describe all Restful APIs.', 'title': 'GSLB API document', }, "USE_SESSION_AUTH": True, } But for version 2.1.1, it seems info field is not supported in swagger_settings? The title can be passed as following: schema_view = get_swagger_view(title='My Restful API') But seems there is no way to pass the description to get_swagger_view, thus I am not able to show description on swagger UI. Is there a workaround in this version? Thanks. -
I am trying to find a python library to make a website application related to grid games as a part of a project
I tried making the game using the Tkinter library...but i wasn't able to integrate it with django to use it as a web application...it comes only as a desktop application. Will the following python libraries be helpful in making the game? 1)Kivy 2)PySide 3)PyQt or Is there any other python library which I can use to make a web based grid game? -
How can I add a New Folder in a Python Project using VS2015 right click menu?
I'm developing a Django app using Python Tools for Visual Studio 2015. I would like to add in the templates folder another folder called logradouros, but I just have these options: How can I add the "Add New Folder..." option in this context menu? -
How do perform django http request[post or get ] via javascript ajax
//django code for getting form data class CreateStore(ClassMixinItem,CreateView): form_class = ItemForm success_url = '/index' //javascript code //need help here -
How to view .csv files in web browser using django?
I want to view the uploaded .csv file in web browser, but currently it is downloading instead of rendering. My application is buit upon django framework. (or) Is there any python API available to convert .csv file to .pdf format? -
Django user login doesn't work
I am able to successfully sign up. When the user is signed up, they are signed in successfully. But after that the separate login doesn't work. I have pretty much copied and pasted the code from the codes for signing up and I have no clue what is wrong here. here is the forms.py: class loginView(View): form_class=Login template_name='users/login.html' def get(self,request): form=self.form_class(None) return render(request,self.template_name,{'form':form}) def post(self,request): form=self.form_class(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username=username, password=password) login(request,user) return render(request, 'home/index.html') return render(request, self.template_name, {'form': form}) here is the views.py: class loginView(View): form_class=Login template_name='users/login.html' def get(self,request): form=self.form_class(None) return render(request,self.template_name,{'form':form}) def post(self,request): form=self.form_class(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username=username, password=password) login(request,user) return render(request, 'home/index.html') return render(request, self.template_name, {'form': form}) Thank you! -
Unexpected arguments while saving contents
I am a newby in django . I tried to make an feedback app but I am not able to save the contents . It show "unexpected argument "name" " my code is views.py def index(request): return render(request, 'index.html') def positive(request): if(request.method=="POST"): confirm_message = " " context = {'confirm_message': confirm_message} name = request.POST['name'] suggest = request.POST['suggest'] improve = request.POST['improve'] posi = positive(name=name , suggest=suggest , improve=improve) posi.save() confirm_message = "Thanks for the message . We Will get right back to you." context = {'confirm_message': confirm_message,} return render(request,'positive.html',context) else: return render(request,'positive.html') def negative(request): if(request.method=="POST"): confirm_message = " " context = {'confirm_message': confirm_message} name = request.POST['name'] upset = request.POST['upset'] change = request.POST['change'] negi = negative(name=name , upset=upset , change=change) negi.save() confirm_message = "Thanks for the message . We Will get right back to you." context = {'confirm_message': confirm_message,} return render(request,'negative.html',context) else: return render(request,'negative.html') models.py class positive(models.Model): name = models.CharField(max_length=50,default=None) suggest = models.CharField(max_length=100) improve = models.CharField(max_length=150) created_at = models.DateTimeField(default=datetime.now) def __str__(self): return u'Name : %s suggest: %s \nimprove: %s ' % (self.name,self.suggest,self.improve) class negative(models.Model): name = models.CharField(max_length=50,default=None) upset = models.CharField(max_length=100) change = models.CharField(max_length=100) def __str__(self): return u'Name : %s upset: %s \nchange: %s ' % (self.name,self.upset,self.change) -
Dropping field in model after wrote all viwes
I have a model with some fields. I wrote some views "def" and forms. I need to drop one field and want to add fields to that model. if I do this, how bad it will affect my views and forms? -
JSON vs. MySQL for static data
I'm about to begin work on a web app with a large amount of static data. The data is real-world diseases so there is a slight possibility that some of that data will need to be updated every now and again(so I suppose its not truly static). There will never be any user interaction with the database, if data is ever changed it will only be done by me personally. My initial goal was to make this application client-side only since its only consists of tables you select that will lead to a disease. I wanted to use a JSON file and store all the information in there but even then it seems I need some server-side language. This being the case I'm considering writing this app with the Django framework. Should I use a MySQL database or use JSON? Would this have been possible to do on the client-side only if I do want to use JSON? Which method would be faster for parsing data? -
HTML/CSS - Django application that displays current time and date on all devices
I am trying to create a basic Django application which just shows the current time and date of the client system and in the client's format. I have managed to make an HTML page that does this but it does not work on smartphones. This is the code: <html> <head> <style> body { padding: 0.8em; color: white; font-family: Roboto, sans-serif; background-image: url("hkjhjh.jpg"); background-size: cover; } </style> <title>Date and Time</title> </head> <body> <script type="text/javascript"> document.write ('<p>Current time is: <span id="date-time">', new Date().toLocaleString(), '<\/span>.<\/p>') if (document.getElementById) onload = function () { setInterval ("document.getElementById ('date-time').firstChild.data = new Date().toLocaleString()", 50) } </script> </body> </html> How do I integrate it with Django so that it works on most devices? On a side note, how do I go about making sure the HTML code follows 'progressive enhancement'? -
Django Model _meta API non-editable
I want to use django-reverse-admin, however, fields that can not be edited are not taken into account here. For example, a DateTimeField As I understand, the search of fields goes here: related_fields = [f for f in model._meta.get_fields() if (f.one_to_many or f.one_to_one) and f.auto_created and not f.concrete] But I did not find it in the documentation, how to get this field How can I fix this so that others can also use it? -
Django - Can't serving Static Files in production
(first, sorry for my bad english) i'm having a problem serving the static files in a Digital Ocean server. In develpment in my own computer all works perfect but i can't serve the statics in production, even the admin statics. This is what i have in the settings.py STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) STATIC_ROOT=os.path.join(os.path.dirname(os.path.dirname(BASE_DIR)), 'static/') Well, the command collect static work perfect and send the static files to my folder /home/username/project/static if i check the folder i have all the static files but... the browser send the 404 error. I try a lot of combinations in settings even hardcoded routes but always the same... The site give me this addres for static http://myserverip:8000/static/admin/css/base.css But i can't see the files always 404 Thanks!!! -
how to get urls for scrapy from external app
Given your standard scrapy app: import scrapy class QuotesSpider(scrapy.Spider): name = "quotes" def start_requests(self): urls = [ 'http://quotes.toscrape.com/page/1/', 'http://quotes.toscrape.com/page/2/', ] for url in urls: yield scrapy.Request(url=url, callback=self.parse) How do I pull urls from an external source? Am I using a web service? Am I using django or a database connection? Is scrapy expecting us to hardcode this? -
Django-Registration redux password change forwards to index page
I can use the Django-Registration redux to login and register and it works fine except for the password change which forwards to: http://127.0.0.1:8000/?next=/accounts/password/change/ which lands on the homepage. These are my app urls: class MyRegistrationView(RegistrationView): def get_success_url(self,user): return('/createprofile/') urlpatterns=[ url(r'^$', views.index, name='index'), url(r'^city/(?P<city_name_slug>[\w\-]+)/$', views.show_city, name='show_city'), url(r'^user/(?P<username>[\w\-]+)/$', views.show_profile, name='show_profile'), url(r'^search/$', views.search, name='search'), url(r'accounts/register/$', MyRegistrationView.as_view(), name='registraion_register'), url(r'^accounts/', include('registration.backends.simple.urls')), url(r'^createprofile/$', views.createprofile, name="createprofile"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) This is the link the I use to change password: <p> forgot your password? Ney bother. <a href="{% url 'excurj:auth_password_change' %}">Reset password</a> </p> This is the password_change_form.html form stored in the same place as other registration forms: {% extends 'base.html' %} {% load i18n %} {% load crispy_forms_tags %} {% block content %} <form method="post" action="."> {% csrf_token %} {{ form|crispy }} <input type="submit" value="{% trans 'Submit' %}" /> </form> {% endblock %} This is the result from http://127.0.0.1:8000/accounts/: -
Integration of Desktop Application with Xblock on open EDX platform?
I am building a board game like chess using TKINTER library of python. But I am not sure whether my application will be integrable with Xblock. So I tried to run simple program of Desktop application in XBlock from Tkinter import * root = Tk() var = StringVar() label = Message( root, textvariable=var, relief=RAISED ) var.set("Hey!? How are you doing?") label.pack() root.mainloop() Again I wrote this code in my xblock python file corresponding to some handler but it is not working and I am not getting where to use it in Xblock so It gives output on student view so that student can play this game and teacher would be able to evaluate this. I am not able to run this in django application also. Suggest something so that I can achieve this??? -
Should templates, views, and models go in the Django config app?
Is it considered against Django "best practices" to place templates, views, or models inside the Django config app? (The same app with settings.py) Templates are probably a "no" because template files in a templates directory under the config app will not be found by default, I had to add a django.template.loaders.filesystem.Loader to load them. Thank you for any advice. -
Django admin inlines to parent model
I have several related models. In django admin I want to create Appeal. As can be seen from the models, I need to select from the Assignment list, but in my case, most often, it needs to be created from scratch. Django admin provides this option if I click on "+" Then, inside the Assigment, I need to select ClientProfile, but again, in most cases, I need to create it again, which means I'll click on the "+" But as can be seen from my models, ClientProfile refers to User, and more often, it also needs to be created anew, and so again press on "+" And the most terrible thing in this situation is that User refers to the model of Address. The question is, is it possible to do something so that you do not have to press 3-5 times to "+"? Each press is accompanied by the opening pop, and it's not very convenient. I'm thinking about the inheritance of forms or models themselves, creating several abstract models, I also thought about WizardView, which I could not integrate into Django-admin. I'm confused and do not understand how to do it right. The problem is that I built … -
Django 1.7, postgresql, jquery datatables, and connections not being released
I'm developing a page using jquery DataTables, django 1.7 and postgresql. I setup my DataTables to retrieve information from my django backend (set serverSide option to true). After some testing, i noticed that i kept getting this error from django OperationalError: FATAL: sorry, too many clients already And upon checking pg_stat_activity, i've already reached the default 100 connections. I then checked the rows retrieved from pg_stat_activity and i noticed that there were a lot of "IDLE" connections. From what i read, the idle connections mean that the requests finished. These should have been released but for some reason, they are not being released causing the error i've already checked CONN_MAX_AGE as suggested in this SO post Django ORM leaves idle connections on Postgres DB but my CONN_MAX_AGE is zero. i've tried placing db.close_old_connections() in my fetch views which are referenced in the ajax of my DataTables but either i'm not using it properly or it's not working because the connections aren't closing I am quite at my wit's end on how to fix this and i couldn't find any other similar situations compared to mine Thanks -
Django admin unregister Sites
I've been trying to unregister the admin for sites in django by doing the following: from django.contrib.sites.models import Site admin.site.unregister(Site) However this gives me an error stating that "Site" is not registered (even though it showed up in admin before). If I try doing the following I get no errors but "Site" stays in the admin: from django.contrib.sites.models import Site admin.site.register(Site) admin.site.unregister(Site) I need the sites app and cannot take it out of INSTALLED_APPS in settings. However the admin for it is utterly useless to me. Any ideas on what I am doing wrong here? Thanks! -
Access Uploaded Media File From View
I am hoping to have a user upload a file (a CSV) then access it in my views.py in order to use my own code to read it. However, I keep getting the error: [Errno 2] No such file or directory: 'D:/media/data.csv' For reference, my project is stored under the following directory on my PC: D:\Python\[PROJECT_NAME] Here is what my settings.py looks like: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' and my views.py: import os from django.conf import settings def create_chart(request): ... file = File.objects.get(id=4) file_ = open(os.path.join(settings.MEDIA_ROOT, file.file.url)) If I go into my admin, I can click on an entry and access the file. However when trying to get it in views.py it is a no go. I am absolutely befuddled by this issue and any help would be appreciated. -
Django Image Upload in Database Absolute Path Rather Than Relative
My model: class MedicineType(models.Model): name = models.CharField(max_length=100) image = models.ImageField(upload_to='images/', max_length=255, null=True) in settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' Now, when I do upload image from the browser, the url of the image is being stored in the database as an absolute path. For example, an image named 'example.png' is going to have http://localhost:8000/media/images/example.png But I want that only the relative path would be stored in the database. Not with the localhost and port. How Do I do that? -
Django Unique Field Throws Error for None Value
I'm getting a duplicate key value violates unique constraint "users_user_email_key" DETAIL: Key (email)=(None) already exists. error when trying to create a second user that doesn't have an email. Email field definition: email = models.EmailField(verbose_name='email address', max_length=255, unique=True, null = True, blank = True) From the form creating the user: def clean_email(self): email = self.cleaned_data.get('email') if email: if email == "": return None else: return email else: return None What am I doing wrong here? All input is appreciated, thanks! -
How to avoid race condition in updating model field to newest timestamp
I need to keep track of the most recent time a user was mentioned in a post, and update this field each time a new post is created based on it's post time. My current code looks like this: from django.db.models.signals import post_save from django.dispatch import receiver from messageboard.models import Post @receiver(post_save, sender=Post) def user_last_mentioned_updater(sender, instance, **kwargs): for users in instance.mentions: user.last_mentioned = max(user.last_mentioned, instance.timestamp) user.save() However, if two posts are processed concurrently, this could potentially leave the last_mentioned field at the timestamp of the earlier post. Unfortunately, F doesn't support the max operation, when I try it I get a TypeError: unorderable types: datetime.datetime() > F(): user.last_mentioned = max(F('last_mentioned'), instance.timestamp) How can I avoid this race condition? If it matters, for the moment I'm using Postgresql for the ORM, although this may be subject to change.