Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Multi-user web application Django
I am looking exploring new architectures for my multi-user web application. Currently I have a base model, for whatever model I want to restrict for belonging to a user: class UserModel(models.Model): owner = models.ForeignKey(User, on_delete=models.DO_NOTHING) class Meta: abstract = True For whatever task on my system, which I manipulate models which descend from UserModel I want to make sure the only data it touches is its own data. What I am doing now is passing around the logged User. But I am looking for a more robust architecture, to avoid some contributor eventually forget about filtering the data (or filling in the correct user). Is there any Django package or technique which is already extensively tested for this pretty common situation? -
How do I pass in a python pandas.Dataframe object as an argument to a celery task?
I would like to pass a pandas dataframe object as an argument to a celery task. Is there a way I can achieve this? I understand that dataframe objects are not JSON serializable and therefore cannot be used as arguments based on my current setup. -
Django password_reset email through app-engine mail api
I'm trying to figure out how to get the built-in password_reset view to leverage appengine's mail api instead. Is this possible? I've got several of my own custom views leveraging appengine's mail api just fine, but the default password_reset view I'm guessing tries to use regular send_mail and expects valid smtp settings. I'd prefer not to put my google user/pass in local_settings.py. Is it possible to override send_mail in password_reset? -
Redirection within Django using Classbased (generic) views
I have created a functional Django (1.11.5) system which allows me to add numerous Bikes to Manufacturer due to the foreign key capabilities. Unfortunately I can't get my head around how I correctly can redirect user to (PrimaryKey) Manufacturer after the user has updated the Bike information. My views uses Class Based Views for deleting, creating, and updating both the Manufacturer and Bikes. Below I have displayed both the views.py and URL.py I have within my App. views.py from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.core.urlresolvers import reverse_lazy from .models import Manufacturer, Review class ReviewUpdate(UpdateView): model = Bike fields = ['bike_body'] success_url = reverse_lazy('manufacturers:index') URLs.py url(r'bike/(?P<pk>[0-9]+)/$',views.BikeUpdate.as_view(), name="bike-update"), -
Change text in Django / Python and website get down
im editing a Django/Python website, i just want to change the text of one word and upload but the website falls when i change any text. The website is using Amazon Beanstalk and RDS. -
Is it possible to do a stream http request with Django?
We're working on software that needs to be able to handle 10+ gb files. My fall back is simply chunking the data and making repeatitive POST requests to django, however I was wondering if Django and WSGI could handle "transfer-encoding: chunked" for a single http request? -
Inputs are not showing in django form
My form inputs are not showing. It's just a button. i think homepage.html doesn't getting this form Forms.py class NameForm(forms.Form): your_name = forms.CharField(label='Your name', max_length=100) Views.py def get_name(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = NameForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required # ... # redirect to a new URL: return HttpResponseRedirect('/') # if a GET (or any other method) we'll create a blank form else: form = NameForm() return render(request, 'mainApp/homepage.html', {'form': form}) homepage.html {% extends "mainApp/wrapper.html" %} {% block title %}Главная{% endblock %} {% block content %} <h1>Main page</h1> {% include "mainApp/includes/somehtml.html" %} <br> <form action="/account/username/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit" /> </form> <br> {% endblock %} It shoes only "Submit" button. How can I fix it? -
Django, select image from previous uploaded images
I have a Post model which has a ImageField. class Post(models.Model): headline = models.CharField(max_length=255) lead = models.TextField(blank=True, null=True) body = models.TextField(blank=True, null=True) image = models.ImageField(upload_to="posts", blank=True, null=True, max_length=255) In my ModelForm, the file input for the image works perfectly, but I was wondering how to let the user choose between uploading a new image, or selecting one from all the images that have been previously uploaded to the site. Any pointers? -
Django - Cannot 'migrate'
I am currently trying to deploy my new changes to my raspberry-pi, but with I run python manage.py migrate I receive the error below: Applying CloudRoni.0007_auto_20180129_2007...Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/pi/CloudRoni/cloudronienv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/home/pi/CloudRoni/cloudronienv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/pi/CloudRoni/cloudronienv/local/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/pi/CloudRoni/cloudronienv/local/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/pi/CloudRoni/cloudronienv/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/home/pi/CloudRoni/cloudronienv/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/pi/CloudRoni/cloudronienv/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/pi/CloudRoni/cloudronienv/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/home/pi/CloudRoni/cloudronienv/local/lib/python2.7/site-packages/django/db/migrations/migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/home/pi/CloudRoni/cloudronienv/local/lib/python2.7/site-packages/django/db/migrations/operations/models.py", line 97, in database_forwards schema_editor.create_model(model) File "/home/pi/CloudRoni/cloudronienv/local/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 303, in create_model self.execute(sql, params or None) File "/home/pi/CloudRoni/cloudronienv/local/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 120, in execute cursor.execute(sql, params) File "/home/pi/CloudRoni/cloudronienv/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 80, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/home/pi/CloudRoni/cloudronienv/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) File "/home/pi/CloudRoni/cloudronienv/local/lib/python2.7/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/pi/CloudRoni/cloudronienv/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 63, in execute return self.cursor.execute(sql) File "/home/pi/CloudRoni/cloudronienv/local/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py", line 326, in execute return Database.Cursor.execute(self, query) django.db.utils.OperationalError: unable to open database file When I try … -
Ubunti Server 16.04: Running Django on Apache
I am having troubles getting apache to run django. I am able to run "python3 manage.py runserver 192.168.1.230:80" and it will run everything fine. But once I try to have apache run it, I will get a "500 internal server error". I have watched multiple youtube videos and also read many articles. The main articles I have followed are: https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/modwsgi/ and https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-ubuntu-14-04 I am not sure what to do next. I have looked at my error.log and can't find anything to help my particular situation. Here is my /etc/apache2/apache.conf file: # This is the main Apache server configuration file. It contains the # configuration directives that give the server its instructions. # See http://httpd.apache.org/docs/2.4/ for detailed information about # the directives and /usr/share/doc/apache2/README.Debian about Debian specific # hints. # # # Summary of how the Apache 2 configuration works in Debian: # The Apache 2 web server configuration in Debian is quite different to # upstream's suggested way to configure the web server. This is because Debian's # default Apache2 installation attempts to make adding and removing modules, # virtual hosts, and extra configuration directives as flexible as possible, in # order to make automating the changes and administering the … -
Display foriegnkey fields in Django template for a CreateView
I am trying to display a checklist in the CreateView using the values in the ForeignKey fields for descriptions. models.py class Structure(models.Model): name = models.CharField(max_length = 30) description =models.CharField(max_length = 300, null=True, blank=True) def __str__(self): return self.name class SelectedFramework(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) structure = models.ForegignKey(Structure) selected = models.BooleanField(default = False) views.py class FrameworkCreateView(generic.CreateView): model = SelectedFramework fields =['structure', 'selected'] template_name = 'catalogue/structure.html' def form_valid(self, form): form.instance.user = self.request.user return super(FrameworkCreateView, self).form_valid(form) structure.html {% extends 'catalogue\base.html' %} {% block container %} <h2>{% block title %}Structures{% endblock title %}</h2> <form action="" method="post"> {% csrf_token %} {% for field in form %} <div class="col-sm-10">{{form.structure}} {{form.selected}}</div><br> {% endfor %} </div> </form> {% endblock %} The code above works but will display the ForeignKey 'structure' as a dropdown list with the values of __str__. Is there a way to display string for structure.name and structure.description with the checkbox from selected in the CreateView? -
Creating online python Editor
I want to create an online editor where users can come in, write python code and are able to run the code and view their results. I want something like kaggle's kernel editor for python as shown in image below I want to do the backend in python with some library like Flask or Django. My actual problem is how do I proceed with the implementation. My initial idea is to have some js editor that lets user write the code and when user hits "Run", I would send an ajax call to the web-server with the contents of the code editor. The web server would in turn run the code and return the response which would be displayed to another box showing output. My actual concern here is, how do I avoid execution of malicious code? Suppose user writes something that tries to download some data from directories he is not supposed to access, what would be the proper safeguard against it? -
Passenger Django on Centos / Plesk
Followed https://support.plesk.com/hc/en-us/articles/115002701209-How-to-configure-Django-application-in-Plesk- to get my Django 1.11 application up and running on a fresh Centos VPS with Plesk Onyx. Happy with progress as would normally use wsgi on Ubuntu as clearly the app is being seen/recognised but I'm getting an error. Traceback (most recent call last): File "/usr/share/passenger/helper-scripts/wsgi-loader.py", line 325, in <module> app_module = load_app() File "/usr/share/passenger/helper-scripts/wsgi-loader.py", line 62, in load_app eturn imp.load_source('passenger_wsgi', startup_file) File "/var/www/vhosts/example.com/httpdocs/app/passenger_wsgi.py", line 8, in <module> if sys.executable != INTERP: os.execl(INTERP, INTERP, *sys.argv) File "/var/www/vhosts/example.com/biems-app-venv/lib64/python2.7/os.py", line 312, in execl execv(file, args) OSError: [Errno 2] No such file or directory I have followed Passenger + Dreamhost + Django Error but my python seems to exist if I'm to use the one in the virtual-env and not the system wide version. I've updated the database configuration but have not yet sorted the statics/media files but cannot see this causing a problem? My passenger.wsgi looks like import sys, os app_name = 'biems' env_name = 'biems-app-venv' cwd = os.getcwd() sys.path.append(cwd) sys.path.append(cwd + '/' + app_name) INTERP = cwd + '/' + env_name + '/bin/python' if sys.executable != INTERP: os.execl(INTERP, INTERP, *sys.argv) sys.path.insert(0, cwd + '/' + env_name + '/bin') sys.path.insert(0, cwd + '/' + env_name + '/lib/python2.7/site-packages/django') sys.path.insert(0, cwd + … -
Django profile View
Hi I am new to Django and tried existing answers but did not work for me. I would appreciate your help! I have two logins 1 with facebook and 1 with django. I have this profile view in my page. if you login with facebook you can access your profile page and change it. but if you login with a not social account (regular user object) you get redirected to home page not profile.If you go to django admin page all users are listed in user page. if you go to profile page on admin, there are only social auth users from facebook. What can I do to resolve the issue? Thanks in advance. here is the code: @login_required(login_url="/") def profile(request, username): if request.method == 'POST': profile = Profile.objects.get(user=request.user) profile.about = request.POST['about'] profile.slogan = request.POST['slogan'] profile.skill = request.POST['skill'] profile.save() else: try: profile = Profile.objects.get(user__username=username) return render(request,'profile.html',{'user':user}) except Profile.DoesNotExist: return redirect('/') -
How to force HTTPS in a Django project using Cloudinary?
I am using Cloudinary in my Django project to upload and store my images. Something like this: class MyModel(models.Model): logo = CloudinaryField('Logo', blank=True, null=True) In my serializers, if I call something like: mymodel = MyModel.objects.get(pk=1) return mymodel.logo.url What is being returned is a cloudinary url but only with http. How do I fix this? How do I get https? -
Django ugettext_lazy not working for interpolated strings in forms
I have form: class UserForm(forms.Form): fname = forms.CharField(max_length=30, label=_('First Name'), validators=[Alpha()]) lname = forms.CharField(max_length=30, label=_('Last Name {name}').format(name='XXXX'), validators=[Beta()]) i am rendering this form using form.as_p, when i change my language First Name gets translated but for some reason Last Name {name} which using format method for string interpolation is not getting translated, translation for this string is also present in the language catalog. My Django version is 1.8. -
Get objects of a certain quality from many to many field
Say I have the following model: class Project(Model): name = CharField() users = ManyToManyField(), through="Membership") @property def developers(self): ??? class Membership(Model): user = ForeignKey(AUTH_USER_MODEL) project = ForeignKey(Group) level = IntegerField() class Meta: unique_together = ("user", "project") Say there are two levels: developer and tester. Which code shall be written instead of ??? so that project.developers returns a queryset of all users related to the project as developers? -
Save object model with keywords in Django
I'm using drum template to build a reddit style website and I want to populate my database with some entries. My problem is that I'm not able to add a Link and the corresponding keywords. I was trying this (I add a few more attributes to the model): keywords_list = ['key1_test','key1_test'] u = User.objects.get(username = username) obj = Link( link = 'www.example.com', user = u, pub_date = datetime.datetime.now(), title = 'Title', description = 'blabla', fb_shares_ts = '', fb_reactions_ts = '', fb_comments_ts = '', fb_engagement_ts = '' ) for key in keywords_list: keyword, _ = Keyword.objects.get_or_create(title=key) obj.keywords.add(AssignedKeyword(keyword=keyword),bulk=False) obj.save() It gives me this error: django.db.utils.IntegrityError: NOT NULL constraint failed: generic_assignedkeyword.object_pk -
Django FilterSet set initial value
I am new to Django, so if this is a fairly obvious question, I apologise. We are using Django_Filterset in our project. I have been asked to set a default filter value for a foreign key column in the model class RegFilter(django_filters.FilterSet): class Meta: model = models.Reg fields = { 'id': ['exact'], 'nom_id': ['icontains'], 'nom_name': ['icontains'], 'product__name': ['icontains'] } The product name should default to a product already in the db when the initial screen is displayed - any idea how this can be achieved? Appreciate your help. -
Wagtail check user page permission
I have site made in django with Wagtail CMS. In that page menu is generated from templatetag i made. The problem is for now authenticated and anonymous users can see only public pages. I need to show in that menu also private pages, but only that pages which user has permission to view. I easily managing in wagtail admin how to set that permission, but how i can check if user has view permission for specific page in backend or template? if context['request'].user.is_authenticated(): private_categories = Page.objects.live().in_menu().not_public() for category in private_categories: if HERE I NEED TO CHECK IF USER HAS PERMISSION TO VIEW CATEGORY: categories.append(category) -
Django pre_save signal and ModelAdmin custom error message
I have a model whose pre_save() signal is connected to a remove service (json, REST, etc.) in the following way: before saving locally, query the remote service, asking for remote insertion remote service does its things, the main being checking that a relevant entry does not already exist. On success (HTTP 201), all is good, the local model uses the remote service response to populate the db. on failure, the service returns an HTTP 400 (the status code is debatable but that is for a different question on SO :-) ) The error response is in the following form: {'local_model_field': [u'This element already exists']} The local model pre_save signal then raises a ValidationError: raise ValidationError(json_response['local_model_field'][0]) This works nicely. Now, on the django admin, when I try to simulate the remote insertion of an already-existing object, I get a 500 page, which is fine but not ideal. Is there any way to have the pre_save() error bubble all the up to the ModelAdmin and be displayed as a standard error message, populated with the relevant content? I have tried the following but to no avail: def changeform_view(self, request, object_id=None, form_url='', extra_context=None): """ trying to display the right message when pre_save() fails … -
SyntaxError simply a ] while using Django
Hi everyone I get this weird error can someone please help. The error is: File "C:\Users\myshop\myshop\urls.py", line 26 ] ^ SyntaxError: invalid syntax and the urls.py is this: from django.conf.urls import include, url from django.contrib import admin from django.conf import settings from django.conf.urls.static import static app_name='shop' urlpatterns = [ url('admin/', admin.site.urls), url(r'^', include('shop.urls', namespace='shop'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) This one looks like Django is acting up and is annoying me. -
How to document a Django project?
How should I go about documenting a Django project? I'm not talking about an app that I'm creating that I'll push to github. It's basically internal documentation that will help new developers that we employ to get up to speed with the system. (I guess that's the point of documentation in general) Should I be documenting each and every view function, model or form as below: def home(request): """View that renders the home page.""" class MyModel(models.Model): "Documentation regarding my model.""" It seems like a bit of overkill. Are there perhaps some good projects that I can look at for inspiration? -
Process large dictionary response in chunks for operations
I have a large dictionary response by which i am creating object in bulk. Since It is a simple object creating in bulk, so it's taking too much time. I am trying to do it by multiprocessing or thread. So I can create bulk object in pieces of data(by single file) and store them together at end. here is my function def create_obj(self, resp): school_db = Schools.objects.bulk_create( [Schools( **{k: v for k, v in value.items() })for key, value in resp.items() ]) return school_db and sample of my large dictionary response- response = { 'A101': { 'VEG': True, 'CONTACT': '12345', 'CLASS': 'SIX', 'ROLLNO': 'A101', 'CITY': 'CHANDI', }, 'A102': { 'VEG': True, 'CONTACT': '54321', 'CLASS': 'SEVEN', 'ROLLNO': 'A102', 'CITY': 'GANGTOK', }, } So is there any way to split up the dictionary into 15-20 chunks by which I can use multiprocessing to process. Any help would be appreciated. -
Django - {{ MEDIA_URL }} not working as expected
I'm having a slight problem where my Django media tag isn't working properly. This doesn't return the path I expect - which would be '/media/uploads/image_name_goes_here/', and instead I get '/uploads/image_name_goes_here/' even though I have specified in my settings.py that the MEDIA_URL = '/media/'. My upload_to path in the models for the Image is the following function.. def img_path(instance, filename): return ('uploads/%s' % (filename)) class Image(models.Model): ... image_url=models.ImageField(upload_to=img_path,null=True) ... My html: <img src='{{ MEDIA_URL }}/{{ Image.img_path }}'/> Any ideas on why the 'media/' bit of the URL does not show up?