Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to deny permission to a user of one kind from accessing the view of other user through url in django?
In my project, I've got different types of Users like this: User |-Client |-Employee |-Technical Manager |-Service Manager |-Production Manager No user can access the view of other user by url. A client cannot access profile of a Technical Manager through the url /officer/profile which is assigned for Technical Manager's profile. In order to do so, In my Client class in the models.py, I used this code snippet: class Client(models.Model): class Meta: permissions = ( ('view_client', 'view_Client'), ) Then for each view I used a decorator like this: @permission_required(lambda u: u.has_perm('authentication.view_client')) Then I'm logging in as a technical manager and trying to access with this url: /client/profile Then I got the error function object is not iterable. I was creating my user in an app called authentication. The models,py looks like this: ' @python_2_unicode_compatible class Profile(models.Model): user = models.OneToOneField(User) user_sex = (('MALE', 'Male'), ('FEMALE', 'Female')) sex = models.CharField(max_length=6, default='Male', choices=user_sex) address = models.CharField(max_length=250, null=True, blank=True) city = models.CharField(max_length=250, null=True, blank=True) state = models.CharField(max_length=250, null=True, blank=True) country = models.CharField(max_length=250, null=True, blank=True) phone = PhoneNumberField(blank=True) zip = models.IntegerField(null=True, blank=True) about = models.CharField(max_length=250, null=True, blank=True) email_confirmed = models.BooleanField(default=False) account_type = models.IntegerField(default=-1) class Meta: db_table = 'auth_profile' class Employee(models.Model): user = models.OneToOneField(User) manager = … -
How to run Django App using nginx server
I am completely beginner and would like to know how to run django app on nginx. What I did: I already have django app I have already installed nginx While I am executing nginx restart then my page is displaying standard view. How to redirect it to my app ? what should I change in nginx.conf file ? I will be really thankful for your help, Thanks -
Django: Custom field after deleting still in cleaned_data
I've created a quite complex custom model field (including a custom from field and custom widget). Normally when I delete a field in my view (del form.fields['my_field']) it doesn't appear in cleaned_data afterwards. But when I del my custom field it's still in there. As a result Django still tries to use this field but it's not there any more. See construct_instance in django/forms/models.py. I've reread the Django documentation but couldn't find a hint. Any idea where to start searching or which methods are involved in this? Here is the model field: from django.contrib.postgres.fields.jsonb import JSONField class CustomField(JSONField): def from_db_value(self, data, expression, connection, context): if data is None: return data return Kit(data, self.model) def to_python(self, data): if isinstance(data, Kit): return data if data is None: return data return Kit(data, self.model) def get_prep_value(self, data): return data.as_json() def value_to_string(self, obj): return self.value_from_object(obj).as_json() def formfield(self, **kwargs): defaults = {'form_class': CustomFormField} defaults.update(kwargs) return super(CustomField, self).formfield(**defaults) Traceback: Traceback (most recent call last): File "…django/mysite/myapp/tests_views.py", line 88, in test_… }, follow=True) File "…/lib/python3.5/site-packages/django/test/client.py", line 541, in post secure=secure, **extra) File "…/lib/python3.5/site-packages/django/test/client.py", line 343, in post secure=secure, **extra) File "…/lib/python3.5/site-packages/django/test/client.py", line 409, in generic return self.request(**r) File "…/lib/python3.5/site-packages/django/test/client.py", line 494, in request six.reraise(*exc_info) File "…/lib/python3.5/site-packages/django/utils/six.py", line 686, … -
Making FileField link through ForeignKey object
How can i create a link to the particular file? models.py class Post(models.Model): .... class Presentation(models.Model): pres_id = models.AutoField(primary_key=True) description = models.CharField(max_length=100) upload = models.FileField(upload_to='presentation', null=True) def __str__(self): return self.description class Participant(models.Model): conference = models.ForeignKey(Post, related_name = 'members', on_delete=models.CASCADE, null=True, blank=True) #Post class presentation = models.ForeignKey(Presentation, related_name = 'pres', on_delete=models.CASCADE, null=True, blank=True) views.py def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) return render(request, 'plan/post_detail.html', {'post': post}) post_detail.html {% for part in post.members.all %} <a href="{{presentation.upload.url}}">{{part.presentation}}</a> {% endfor %} part.presentation returns only Presentation description. But I need also a file link. How can i solve this problem. Thanks. (Structure: there is a post with information about conference participants, presentations, etc. Presentation descriprion link should open a pdf file in browser) -
string concatenate in django template include
is this possible to do like this in django templates? {% for filename in filenames %} {% include filename+".html" %} {% endfor %} as you see i have list of filenames and i want to include all of them with for loop, i think i explained it well. and second question if filename is and integer can i convert to string? llike this: {% for filename in filenames %} {% include str(filename)+".html" %} {% endfor %} thanks. -
RelatedObjectDoesNotExist Error
Here is the model. I have created my own user model class Profile(models.Model): user = models.OneToOneField(User) favorite_food = models.CharField(max_length=100) def set_password(self, raw_password): self.user.set_password(raw_password) Here is the view: class UserFormView(View): form_class = UserForm template_name = 'templates/core/profile_form.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(): user = form.save(commit=False) username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) user.save() return render(request, self.template_name, {'form': form}) Here is UserForm class UserForm(forms.ModelForm): username = forms.CharField(max_length=10) password = forms.CharField(widget=forms.PasswordInput) class Meta: model = Profile fields = ['username', 'password', 'favorite_food'] Where seems to be the problem here? It also says that Profile has no user I have tried changing it to AbstractUser however, it also displays about an error about reverse accessor -
ModelForm disable imageField if empty
I have a form that allows users to upload an image. If they don't upload an image a default image is displayed. I want it that if they don't upload an image, the image field is disabled. I thought the if statement at the end of the form would work - but it didn't. Here's the form forms.py: class ProductForm(forms.ModelForm): class Meta: model = Product fields = ['name', 'description', 'url', 'product_type', 'price', 'image', 'image_url'] labels = { 'name': 'Product Name', 'url': 'Product URL', 'product_type': 'Product Type', 'description': 'Product Description', 'image': 'Product Image', 'image_url': 'Product Image URL', 'price': 'Product Price' } widgets = { 'description': Textarea(attrs={'rows': 5}), } if Product.image is None: form.fields['image'].disabled = True and here's the models.py: class Product(models.Model): user = models.ForeignKey(User) name = models.CharField(max_length=100) description = models.CharField(max_length=300) price = models.DecimalField(max_digits=10, decimal_places=2) url = models.CharField(max_length=200) product_type = models.CharField(max_length=100) image = models.ImageField(upload_to='product_images', default='product_images/default.png', null=True) image_url = models.CharField(max_length=200, blank=True) likes = models.IntegerField(default=0) def __str__(self): return self.name def get_absolute_url(self): return reverse('index', kwargs={}) I tried removing the default='product_images/default.png' - that didn't seem to work. I tried null=True and that seemed to crash the page. What am I missing? -
How to implement one-time tutorial for new users? Django + JS
I want to activate one-time scenario, for users who created their accounts first time, explaining things. As I guess, the only way is to add one more boolean to UserProfile and check in template and activate scenario in JS, if it's true or false. But the only disadvantage I see it that after first time this peace of code (if (first_time=True){..}) will be totally unnecessary. Am I right? This is the way most websites implement first-time-users tutorials? -
Adding a new html page in django app
Newer to django... and I'm trying to new html page in my django app and it doesn't seem to be rendering. I'm receiving a 404 error. Output of 404 error I've successfully added other pages using this method, but for some reason it's not working anymore. Steps I took: Added new html file to dashboards/templates folder Added new class to views.py Imported new class into urls.py and added to urlpatterns Troubleshooting: I've restarted Apache views.py from django.http import HttpResponse from django.conf import settings from django.views.generic import View from django.shortcuts import render from django.contrib.auth.models import User #from Minerva.backend.backend import CustomLDAPAuthBackend from django.contrib.auth.backends import RemoteUserBackend import logging #logger = logging.getLogger(__name__) ## Main Dashboard page class DashboardsView(View): def get(self, request): return render(request, "Dashboards.html") ## Documentation class DocumentationView(View): def get(self, request): return render(request, "Documentation.html") urls.py from django.conf.urls import url from Dashboards.views import DashboardsView from Dashboards.views import AmbulatoryQualityView, CancerCenterView, DecisionSupportView from Dashboards.views import EnterpriseQualityView, HumanResourcesView, IPAnalyticsView, ManagedCareView, DocumentationView from django.views.generic import TemplateView app_name = 'Dashboards' urlpatterns = [ url(r'^$', DashboardsView.as_view(), name='Dashboards'), url(r'^/Ambulatory Quality$', AmbulatoryQualityView.as_view()), url(r'^/Cancer Center Service Line$', CancerCenterView.as_view()), url(r'^/Decision Support$', DecisionSupportView.as_view()), url(r'^/Enterprise Quality$', EnterpriseQualityView.as_view()), url(r'^/Human Resources$', HumanResourcesView.as_view()), url(r'^/IP_Analytics$', IPAnalyticsView.as_view()), url(r'^/Managed Care$', ManagedCareView.as_view()), url(r'^/Documentation$', DocumentationView.as_view()), ] -
Why does Django create an index for ForeignKey with db_constraint=False
I want to shard my database so I can't use foreign key constraints. I have following models from django.db import models class A(models.Model): b_one_to_one = models.OneToOneField( 'B', on_delete=models.SET_NULL, db_constraint=False, null=True ) b_one_to_many_null = models.ForeignKey( 'B', on_delete=models.SET_NULL, db_constraint=False, null=True, related_name='+' ) b_one_to_many_nothing = models.ForeignKey( 'B', on_delete=models.DO_NOTHING, db_constraint=False, related_name='+' ) class B(models.Model): pass python manage.py makemigrations command generates following sql code BEGIN; -- -- Create model A -- CREATE TABLE `a` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY); -- -- Create model B -- CREATE TABLE `b` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY); -- -- Add field b_one_to_many_nothing to a -- ALTER TABLE `a` ADD COLUMN `b_one_to_many_nothing_id` integer NOT NULL; -- -- Add field b_one_to_many_null to a -- ALTER TABLE `a` ADD COLUMN `b_one_to_many_null_id` integer NULL; -- -- Add field b_one_to_one to a -- ALTER TABLE `a` ADD COLUMN `b_one_to_one_id` integer NULL UNIQUE; CREATE INDEX `a_b_one_to_many_nothing_id_4fca4209` ON `a` (`b_one_to_many_nothing_id`); CREATE INDEX `a_b_one_to_many_null_id_e498aa17` ON `a` (`b_one_to_many_null_id`); COMMIT; I understand that Django might want to create an index for b_one_to_many_null field due to on_delete=models.SET_NULL setting, but I don't understand why there is a need for an index for b_one_to_many_nothing field. Is there a way to turn this automatic index creation off or it's … -
How to schedule an email notification report with django-sql-explorer?
I'm searching for a reporting plugin for a soon to be developed django app and I checked some packages available in django. I am particularly interested in using django-sql-explorer because of its flexibility with the queries. But I can't seem to find a setting to allow me to schedule a report and then send to email the reports. There is an option to send reports to S3 but that is not really what I need. There is an option to email results via email but this only happens when the report is triggered manually. Would there be another way to allow me to schedule a report to be generated and then send the result to email recipients? -
Django - custom tags with assigning values
I am trying to build my own tags in django. this is my code when defining the tag: @register.inclusion_tag('post/templates/comment_block') def limit_amount_in_a_page(starting_index, topic_id=1, amount=5): comments = Comment.get_item_with_topic_id(topic_id) selected_comments = [] for index in range(starting_index, starting_index+amount): selected_comments.append(comments[index]) return {'selected_comments': selected_comments} this is how I use it: <div class="past_comments"> {% limit_amount_in_a_page starting_index=0 topic_id=1 amount=5 %} </div> this is the template: <ul> {% for comment in selected_comments %} <li> <div class="comment_body"> <div class="user_info_block"> <div class="content"> <div class="photo_profile"></div> <div class="user_info"></div> </div> </div> <div class="content_block"> <p>{{comment.content}}</p> </div> </div> </li> {% endfor %} However, I get this exception: get_item_with_topic_id() missing 1 required positional argument: 'topic_id' I tried to use the tag in the block without variable name, but still have the same error. -
Mocking Celery `self.request` attribute for bound tasks when called directly
I have a task foobar: @app.task(bind=True) def foobar(self, owner, a, b): if already_working(owner): # check if a foobar task is already running for owner. register_myself(self.request.id, owner) # add myself in the DB. return a + b How can I mock the self.request.id attribute? I am already patching everything and calling directly the task rather than using .delay/.apply_async, but the value of self.request.id seems to be None (as I am doing real interactions with DB, it is making the test fail, etc…). For the reference, I'm using Django as a framework, but I think that this problem is just the same, no matter the environment you're using. -
Django Channels send message from python websocket-client module
I have a Django Channels server which I intend to use as a websocket server. I am trying to send message to websocket with https://pypi.python.org/pypi/websocket-client I can pass the handshake phase and can see connect log in the terminal. However, when I send message to server, I can not see in consumers.py ws_message function that prints message. Also, I can not see the message in frontend. How can I send message to websocket ? -
django celery delay function errror
i use some math function where i create.this function take some images from html form and calculate some results,all in views.py, that calculation take long time to finish and this time the page stay on reloading ... i want to avoid that long time reloading and user I want to take that result where the function complete(results just update user table in specific column result) i try to follow this tutorial for this case but take this error message any time to put run button in html page error message : UnicodeDecodeError at /myslug/ 'ascii' codec can't decode byte 0xc4 in position 0: ordinal not in range(128) Request Method: POST Request URL: http://127.0.0.1:8000/my-slug/ Django Version: 1.11.3 Exception Type: UnicodeDecodeError Exception Value: 'ascii' codec can't decode byte 0xc4 in position 0: ordinal not in range(128) Exception Location: C:\python27\Lib\site-packages\redis\connection.py in _error_message, line 552 Python Executable: C:\python27\python.exe Python Version: 2.7.5 main --__init__.py --apps.py --test.py --celery.py --tasks.py --models.py --form.py --views.py --admin.py mysite --settings.py --urls.py --__init__.py --wsgi.py here my code celery.py from __future__ import absolute_import import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') app = Celery('mysite') app.config_from_object('django.conf:settings') # Load task modules from all registered Django app configs. app.autodiscover_tasks() settings.py # REDIS related settings REDIS_HOST = … -
Extends User Django rest framework
I would like to create a custom User in django, but i have a lot of problems. Here its mi code: models.py class Profesionales(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) dni = models.CharField(max_length=9) numColegiado = models.CharField(max_length=8) valoracionMedia = models.FloatField() numVotos = models.IntegerField() def __str__(self): return self.numColegiado, self.user.first_name Serializers.py class ProfesionalesSerializer(serializers.ModelSerializer): class Meta: model = Profesionales fields = ('numColegiado') class UserSerializer(serializers.ModelSerializer): profesionales = ProfesionalesSerializer class Meta: model = User fields = ( 'id', 'username', 'email', 'first_name', 'last_name', 'password', 'profesionales' ) def create(self, validated_data): profesional_data = validated_data.pop('profesionales') user = User.objects.create(**validated_data) Profesionales.objects.create(**profesional_data) return user views.py #Listar todos los profesionales o crear uno #profesionales/ class ProfesionalesList(APIView): def get(self, request ): profesionales = User.objects.all() profesionalSerializer = UserSerializer(profesionales, many=True) return Response(profesionalSerializer.data) def post(self, request): profesionalSerializer = UserSerializer(data=request.data) if profesionalSerializer.is_valid(): profesionalSerializer.save() return Response(profesionalSerializer.data, status=status.HTTP_201_CREATED) else: return Response(profesionalSerializer.errors, status=status.HTTP_400_BAD_REQUEST) Error!: OperationalError at /profesionales/ no such column: profesionales_profesionales.user_id Request Method: GET Request URL: http://127.0.0.1:8000/profesionales/ Django Version: 1.11.6 I'm new in django and i a bit lost!. Thanks! :) -
Django error: using a UDF inside a view model
Why do I get this error when I am trying to use get_success_url function inside the LoginView class: NameError: name 'get_success_url' is not defined views.py class LoginView(SuccessMessageMixin, FormView): form_class = AuthenticationForm template_name = 'registration/login.html' success_url = get_success_url() # url's name to redirect success_message = 'Welcome back %(username)s!' # A welcome message def form_valid(self, form): user = form.get_user() login(self.request, user) return super(LoginView, self).form_valid(form) def get_success_url(self): # find your next url here next_url = self.request.POST.get('next', None) # here method should be GET or POST. if next_url: return "%s" % (next_url) # you can include some query strings as well else: return reverse('home') # what url you wish to return -
How does Django loaddata know which fields make the natural key?
I am using Django's dumpdata to save data and loaddata to reload it. I am also using natural keys. My model looks similar to this: class LinkManager(models.Manager): def get_by_natural_key(self, url): return self.get(url=url) class Link(models.Model): objects = LinkManager() title = models.CharField(max_length=200) url = models.URLField() def natural_key(self): return (self.url, ) If I export and reimport the data, Django recognizes that the objects already exist and doesn't create duplicates. If I change the title, it correctly updates the objects. However, if I change the URL, it correctly treats it as a new object - although I forgot to mark url unique! How does it guess my intent? How does django know that my url field is the natural key? There is no get_natural_fields function. Django could call natural_key on the class instead of an instance to get the fields, but that seems really brittle: >>> [f.field_name for f in Link.natural_key(Link)] ['url'] The reason I want to know this is that I am writing my own special importer (to replace my use of loaddata), and I would like to take advantage of natural keys without hardcoding the natural key (or the "identifying" fields) for each model. Currently, I "identify" an object by it's unique … -
How can you define basic generic code blocks and insert them in other templates in Django?
I want to make my HTML site consist of single generic modules kind of like this pseudo-code. {% block body %} // Just a block inside the base html template file <div class="container_main"> {% block generic_sub_menu %} // This should be replaced with a generic submenu, which is defined in another html template file {% endblock %} Blah Blah Blah {% block generic_map_display %} // This should be replaced with a generic map display, which is defined in another html template file {% endblock %} </div> {% endblock %} So, I know how to use a base template and insert the body of a more specific template, which extends the base template. But how can I make a template which can be used everywhere with some generic HTML code which is not extending a specific template, but can be used to import some blocks of generic code by other templates? Is there a way to do this with blocks or do I have to research about some other technique in the Django Framework? -
Django - Creating a User Registration Form through a CreateView
I'm planning to create a user registration form through a CreateView. Is this possible? Here is the model: class Profile(models.Model): user = models.OneToOneField(User) favorite_food = models.CharField(max_length=100) In views: class CreateProfile(CreateView): model = Profile fields = ['user', 'favorite_food'] However, the user field only shows a dropdown box of the users. How do you make it ask for the username and password? -
Writing a GUI in HTML for a cross platform Python (Django) desktop application
I'm wanting to write a cross platform desktop application in Python, but I'm much more comfortable writing webapps using HTML, CSS, and JS, and frameworks like Django. So I'm wondering if there is any way to write a GUI for a Python desktop application as if it was a website. These are my requirements: To be able to write the front end in HTML, CSS, and JS, utilising existing libraries like Bootstrap, and AJAX To be able to write most of the backend like a traditional Django project, leveraging it's easy to use database handling. Still be able to do regular Python stuff as well (it's a P2P networking application, so I need to be able to make TCP and UDP connections, do some multithreading, etc). To be able to package it as for Mac, Windows, Linux and have the installation process as automatic as possible (no downloading of third party libraries to get my application working). I know this is a separate question, but I thought I should mention it in case any answers somehow prevent packaging my app in this way. I did find htmlPy which seems to do the first three, but it seems to be dead. … -
git add . shows 'killed 9' error when deploying in heroku
I am trying to deploy a django-app in heroku but when ever I try git add . I am getting error Killed:9 I am not understanding the error, also I tried various answers here in stackoverflow but still the results are the same. -
Error while Django form validation - TypeError: expected string or Unicode object, NoneType found
I'm testing various image uploading scenarios in an old Django installation I've got locally. While running the clean method in form validation for image uploading, I get the following error under a certain scenario: File "/home/hassan/.virtualenvs/myenv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in get_response response = middleware_method(request, response) File "/home/hassan/.virtualenvs/redditpk/local/lib/python2.7/site-packages/newrelic-2.56.0.42/newrelic/hooks/framework_django.py", line 331, in wrapper return wrapped(*args, **kwargs) File "/home/hassan/.virtualenvs/redditpk/local/lib/python2.7/site-packages/user_sessions/middleware.py", line 46, in process_response request.session.save() File "/home/hassan/.virtualenvs/redditpk/local/lib/python2.7/site-packages/user_sessions/backends/db.py", line 73, in save session_data=self.encode(self._get_session(no_load=must_create)), File "/home/hassan/.virtualenvs/redditpk/local/lib/python2.7/site-packages/django/contrib/sessions/backends/base.py", line 86, in encode pickled = pickle.dumps(session_dict, pickle.HIGHEST_PROTOCOL) TypeError: expected string or Unicode object, NoneType found What's the sceario? I'm disallowing filesizes beyond a certain limit, raising a validation error like so raise forms.ValidationError('File too big'). I've noticed the validation error gets raised successfully most of the times, but for certain very, very big files, I instead get the error shown above. Can anyone help me get to the bottom of this? I can add more information if required. -
Django REST - Show recent posts and recently searched keywords
I will be working on the front end Vue.js using the Django REST framework. I'm trying planning and designing a web service such as a shopping mall and have not started modeling yet. Therefore, i can't attach the code. Please acknowledge it beforehand. I will ask the following questions. How to show previously-matched keywords as autocomplete below the search box? How to display the details page of a recently viewed post? Since I use the REST framework, I don't use Sessions in my Django web project, so I don't know how to store the keywords that the user has recently searched for, and how to save the most recent posts the user has seen. I need to expose the keywords that users have recently searched for in the search box, and list the posts that users have viewed recently. I wait for your advice. everybody have a good day! -
Forbidden (CSRF cookie not set.) when csrf is in header
The request header is as below. Accept:application/json, text/plain, */* Accept-Encoding:gzip, deflate, br Accept-Language:en-US,en;q=0.8 Connection:keep-alive Content-Length:129 Content-Type:text/plain Host:localhost:9000 Origin:http://localhost:8000 Referer:http://localhost:8000/ User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36 X-CSRFTOKEN:t5Nx0SW9haZTeOcErcBDtaq6psqBfeyuX4LRQ1WOOXq5g93tQkvcUZDGoWz8wSeD The X-CSRFTOKEN is there but Django still complain about CSRF cookie not set. What happen to Django? In settings.py, the naming are perfectly correct. CSRF_HEADER_NAME = "HTTP_X_CSRFTOKEN"