Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use en0 address as host in Django database setting
I am trying to use my localhost database inside docker Django container. I have allowed listen_address to all in postgresql.conf file. I have added host all all localhost,192.168.1.9 trust in pg_hba.conf file. 192.168.1.9 is my en0 address. Now i want to use 192.168.1.9 as my host in database setting in django. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'db_name', 'USER': 'db_user', 'PASSWORD': 'db_password', 'HOST': '192.168.1.9', 'PORT': '5432', } } I am trying this but i am not able to succeed. Am i doing something wrong? I want postgres to accept all connect so Django app container can connect to my local machine database. -
Why is the consumer run twice when two users share the same websocket connection?
It's one-to-one chat with message persistence. The issue is that when two users connect to the same chat, any message a user sends will be broadcast once but saved in the db twice. When only a single user is connected, however, it will work as normal--only save once. I'm wondering what might cause the consumer to run twice only when two users are connected to the same socket. Here is the relevant code: class ChatConsumer(AsyncJsonWebsocketConsumer): ... async def receive_json(self, content): """ Called when we get a text frame. Channels will JSON-decode the payload for us and pass it as the first argument. """ # Messages will have a "command" key we can switch on command = content.get("command", None) recipient = content.get("recipient", None) sender = self.scope["user"] try: if command == "join": # Make them join the room await self.join_room(content["room"]) previous_message_list = await get_saved_messages(recipient, sender) for msg in previous_message_list: await self.send_json({ "msg_type": MSG_TYPE_MESSAGE, "room": content["room"], "username": msg.sender.user.username, "message": msg.message, },) elif command == "leave": # Leave the room await self.leave_room(content["room"]) elif command == "send": await self.send_room( content["room"], content["message"], content["recipient"] ) except ClientError as e: # Catch any errors and send it back await self.send_json({"error": e.code}) ... async def send_room(self, room_id, message, recipient): … -
Django: queryable computed fields
Is there a "best" way of doing computed fields that can be queried? For example: from django.db import models class Person(models.Model): given_name = models.CharField(max_length=30) family_name = models.CharField(max_length=30) NAME_ORDER_CONVENTION_CHOICES = ( # "Eastern" name order: family name followed by given name ('E', 'Eastern'), # "Western" name order: given name followed by family name ('W', 'Western') ) name_order_convention = models.CharField( length=1, choices=NAME_ORDER_CONVENTION_CHOICES, ) @property def full_name(self): """ Return full name, calculated on the basis of given name, family name and name order convention. """ template = "{} {}" if self.name_order_convention == "W": return template.format(self.given_name, self.family_name) return template.format(self.family_name, self.given_name) This gives you the ability to get the full name for any Person, but if you want to do a database query based on full name, you would need to write a query with implicit knowledge of how this property is computed. This would seem to be something of a violation of DRY, in that there is no longer any central place where you can change where how the computed field is calculated - you have to change the full_name property, and anywhere that makes a query based on implicit knowledge of how full_name works. The main alternative I can think of is overriding … -
django_tables2 gives Tag {% querystring %} error although it is included in settings.py
I have this very simple django_tables2 setup that gives this error and I don't understand why (http://django-tables2.readthedocs.io/en/latest/pages/table-data.html#list-of-dicts): Error: Tag {% querystring %} requires django.template.context_processors.request to be in the template configuration in settings.TEMPLATES[]OPTIONS.context_processors) in order for the included template tags to function correctly. settings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(SETTINGS_PATH, 'templates') ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', # included 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', views.py: class RenderView(TemplateView): def __init__(self): super().__init__() self.template_name = "test.html" def get_context_data(self, **kwargs): context = super(RenderView, self).get_context_data(**kwargs) data = [ {'name': 'Bradley'}, {'name': 'Stevie'}, ] table = NameTable(data) context["table"] = table context["data"] = "data" # a lot of other data here return context class NameTable(tables.Table): name = tables.Column() test.html: {% load render_table from django_tables2 %} {% render_table table %} urls.py: urlpatterns = [ path('', RenderView.as_view(), name='test'), ] django 2.0.2, python 3.6 -
how to access to foreign attributes model in django views
This is my code: urls.py url(r'^blog/$', views.blog, name='blog'), models.py class Category(models.Model): name = models.CharField(max_length=100) slug = models.CharField(max_length=100) description = models.CharField(max_length=200) creation_date = models.DateTimeField(auto_now_add=True) class Post(models.Model): Status = ((1, "Publicado"), (2, "Borrador"), (3, "Eliminado")) status = models.IntegerField(choices=Status, default=3) title = models.CharField(max_length=100) slug = models.CharField(max_length=100, default='prueba') description = models.CharField(max_length=200) content = tinymce_models.HTMLField() category = models.ForeignKey(Category) creation_date = models.DateTimeField(auto_now_add=True) image = models.ImageField(upload_to="photos", default=1) autor = models.ForeignKey(User) views.py def blog(request): posts = Post.objects.filter(status=1).values().order_by("-creation_date") categories = Category.objects.order_by("name") context = { "posts":posts, "categories":categories } return render(request, "blog.html", context) blog.html {% for post in posts %} <a href="{% url 'detail_post' slug=post.slug %}">{{ post.title }}</a> <p>{{ post.description }}</p> <p>{{ post.category }}</p> <p>{{ post.autor }}</p> <p>{{ post.creation_date }}</p> {% endfor %} I can't access to the attributes author and category from a post. Please. I need help for how to do it. Thank you so much. -
Django OAuth Toolkit - Register a user
I've gone through the docs of Provider and Resource of Django OAuth Toolkit, but all I'm able to find is how to 'authenticate' a user, not how to register a user. I'm able to set up everything on my machine, but not sure how to register a user using username & password. I know I'm missing something very subtle. How do I exactly register a user and get an access token in return to talk to my resource servers. -
Views of the django
Good afternoon. In the site template there is a button for the user from the "Technical Support" group to take on the application for subsequent execution. When he clicks on "Run" the application takes the status "In the work", as it can be implemented. Many thanks to all those who respond! I apologize if this question sounded silly, I'm still a beginner) models.py class Application(models.Model): STATUS_CHOICES = ( ('In_the_work', 'В работе'), ('New', 'Новая'), ('Complited', 'Завершена') ) author = models.ForeignKey('auth.User', related_name = '+', verbose_name = 'Автор', null = True) title = models.CharField(max_length=50, verbose_name = 'Заголовок') text = models.TextField(verbose_name = 'Описание проблемы') room = models.CharField(max_length = 4, verbose_name = 'Кабинет') published_date = models.DateField(blank=True, null=True, default = datetime.datetime.now, verbose_name = 'Дата') status = models.CharField(max_length=15, choices=STATUS_CHOICES, default='New', verbose_name = 'Статус') owner = models.ForeignKey('auth.User', related_name = '+', null = True, blank = True, limit_choices_to={ 'groups__name': 'Техническая поддержка'}, verbose_name = 'Исполнитель') class Meta: permissions = ( ("can_add_change", "Добавлять и изменять"), ("can_close", "Закрывать"), ("can_assign", "Назначать"), ) verbose_name = 'Заявка' verbose_name_plural = 'Заявки' def publish(self): self.publish_date = datetime.datetime.now() self.save() def __str__(self): return self.title def save(self, *args, **kwargs): if self.status != 'Complited' and self.owner is not None: self.status = 'In_the_work' super(Application, self).save(*args, **kwargs) View in template {% if perms.helpdesk.can_close … -
Django filter across many to many field
This is a simplified version of my models: class User(models.Model): pass class Foo(models.Model): owners = models.ManyToManyField(User) bar = models.ForeignKey(Bar) class Bar(models.Mode) pass I have a user instance and I would like to compute a queryset for all Bar instances associated with that user. Going from user to Bar consists of getting all Foo objects that have user as owner and then getting all bar instances associated with each Foo. How can I express this most efficiently using django queries? -
Multi tenant with Multiple Databases using django
I have a django project using as database postgres that is already done but now I want to make it a saas with single database per tenant and I dont have any idea where I should start I've been looking for the answer on google but I found almost all answer for schema approch and that is not waht I'm looking for. Can anyone help with an article or a tutorial that I can follow to get it done. Thanks -
Open raster using rasterio and s3
I'm storing rasters in Amazon S3 bucket and would like to open specific object using installed rasterio library in my Django docker container. AWS_ACCESS_KEY_ID and AWS_ACCESS_KEY_ID are incluced in docker-compose.yml env variables. Inside docker container and trying: $ python manage.py shell $ import rasterio $ with rasterio.open(url_to_s3_object) as file: $ ....print(file) I'm receiving error: Traceback (most recent call last): File "rasterio/_base.pyx", line 72, in rasterio._base.DatasetReader.start (rasterio/_base.c:2847) File "rasterio/_base.pyx", line 74, in rasterio._base.DatasetReader.start (rasterio/_base.c:2799) File "rasterio/_err.pyx", line 196, in rasterio._err.CPLErrors.check (rasterio/_err.c:1773) rasterio._err.CPLE_OpenFailed: {URL TO S3 OBJECT} does not exist in the file system, and is not recognised as a supported dataset name. What is the solution for that? In local machine everything works fine. -
Send object to child template in {% include %} tag in Django
How can I send list or object to sub template while including template? {% include "subtpl.html" with parameter={"name":"Saifullah","address":"Lahore"} %} When I run the above code I get TemplateSyntaxError Could not parse the remainder: '{"name":"Saifullah","address":"Lahore"}' from '{"name":"Saifullah","address":"Lahore"}' -
Image not rendering on webpage in django website
So I am building a website with Django, and on the homepage I want to render an image that is always the same. Here is what I have tried. The picutres and html file are in the same directory. This is the html: <div class="ui segment"> <div class="ui horizontal divider"> View the results </div> <img src="3.png" alt="View Results"> </div> And this is a picture of my folder: The image isnt showing up at all, I just get that small icon that you get when the image doesnt load. Any help would be appreciated! -
Django Rest Framework - query params with special characters
my model is: class Skill(models.Model): skill = models.CharField() my viewset: class SkillViewset(viewsets.ModelViewSet): queryset = Skill.objects.all() serializer_class = SkillSerializer filter_backends = (filters.SearchFilter, filters.OrderingFilter ) search_fields = ('id', 'skill') ordering_fields = '__all__' def get_queryset(self): queryset = property_models.Skill.objects.all() skill = self.request.query_params.get('skill', None) if skill is not None: queryset = queryset.filter(skill__icontains=skill) return queryset One of my languages is "C++" This works: Skill.objects.filter(skill__icontains='C++') However calling my api does not work: /skills/?skill=c++ -
Error while make the password hash
Following is my model User. class User(models.Model): username = models.CharField(max_length=30, unique=True) password = models.CharField(max_length=30) pw = make_password(password, None, 'md5') role = models.ForeignKey(Roles, on_delete=models.CASCADE) def __str__(self): return self.username I'm getting this error TypeError: Can't convert 'CharField' object to str implicitly -
Django query, greater than and lower than are not working
I have the following table: class OverallAdvise(mixins.OrdMixin, mixins.EqMixin, models.Model): section = models.ForeignKey('quest.Section', on_delete=models.CASCADE, related_name='section_owner') range_start = models.IntegerField(blank=True, null=True) range_end = models.IntegerField(blank=True, null=True) get_advise = models.CharField(max_length=500) Then, in serializer I'm trying to select the get_advise based on a calculated score. My query is: get_overall_advise = OverallAdvise.objects.filter(section_id = section_id, range_start__gte = section_overall_score, range_end__lte = section_overall_score).values("get_advise") but it's not working. section_id=6 and section_overall_score=8 are given. This is an instance of my mysql table: Can you help me please? -
Django: Update a single field in existing model with forms.py
I need to allow the user to edit a field to customise the name of the field with a stylish modal window. I've been trying to go over tutorials for AJAX but it's going a bit over my head. My HTML: <div id="editCustomParam" class="modal fade bd-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg"> <form class="form-horizontal" id="chamber-form" action="" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="modal-content"> <div class="modal-header"> <h3>Edit Parameter Name</h3> </div> <div class="modal-body"> {{ custom_param_form|crispy }} </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button> <button type="button" class="btn btn-primary submit_property" id="property_submit">Submit</button> </div> </div> </form> </div> </div> The button and element to edit: <td><i id="edit_{{parameter.id}}" data-toggle="modal" data-target="#editCustomParam" class="far fa-edit" title="Edit Parameter Name"></i>&emsp;<span>{{parameter.parameter_name_userdef}}</span></td> The AJAX: $(document).ready(function() { $('.submit_parameter').click(function(el) { var parameter_name = $("#id_parameter_name_userdef").val(); var sensor_id = {{sensor.id}} $.post("{% url 'sensor' sensor.id %}", { csrfmiddlewaretoken: '{{csrf_token}}' }, function(data) { location.reload(); }).done(); }); }); The form: class CustomParameterForm(ModelForm): parameter_name_userdef = forms.CharField(max_length=100) class Meta: model = SensorParameter fields = ['parameter_name_userdef'] The view: class SensorInfoView(generic.DetailView): model = Sensor template_name = 'expert/sensor.html' def get(self, request, sensor_id): sensor = Sensor.objects.get(pk=sensor_id) chamber = Chamber.objects.get(sensor=sensor) sensor_parameters = SensorParameter.objects.filter(sensor=sensor) custom_param_form = CustomParameterForm() return render(request, self.template_name, {'sensor': sensor, 'chamber': chamber, 'custom_param_form': custom_param_form, 'sensor_parameters': sensor_parameters}) def post(self, request, sensor_id): instance = get_object_or_404(Sensor, id=id) form = … -
bootstrap tagsinput failed to load
I have a Django application which loads tags in an input field using jquery as shown in the code. On running the code I have observed that application cannot be able to locate bootstrap-tagsinput.css and bootstrap-tagsinput.js. Where should I put these files so that they can be detected. Error [28/Feb/2018 12:14:23] "GET /scripts/bootstrap-tagsinput.css HTTP/1.1" 404 2191 Not Found: /scripts/bootstrap-tagsinput.js [28/Feb/2018 12:14:23] "GET /scripts/bootstrap-tagsinput.js HTTP/1.1" 404 2188 Not Found: /scripts/bootstrap-tagsinput.js [28/Feb/2018 12:14:23] "GET /scripts/bootstrap-tagsinput.js HTTP/1.1" 404 2188 Project Directory Structure <project_name> |--<app_name> | |--templates | |--index.html |--<project_name> |--scripts | |--bootstrap-tagsinput.css | |--bootstrap-tagsinput.js |--manage.py Code <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.2/css/bootstrap.min.css"> <link rel="stylesheet" href="../scripts/bootstrap-tagsinput.css"> <title>Sample</title> </head> <body> <input type="text" id="tagbar" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../scripts/bootstrap-tagsinput.js"></script> <script type = "text/javascript" language = "javascript"> $(document).ready(function() { $('#tagbar').tagsinput('add', { "value": 1 ,"text": "Amsterdam" ,"continent": "Europe" }); $('#tagbar').tagsinput('add', { "value": 2 ,"text": "Washington" ,"continent": "America" }); $('#tagbar').tagsinput('add', { "value": 3 ,"text": "Sydney" ,"continent": "Australia" }); $('#tagbar').tagsinput('add', { "value": 4 ,"text": "Beijing" ,"continent": "Asia" }); $('#tagbar').tagsinput('add', { "value": 5 ,"text": "Cairo" ,"continent": "Africa" }); }); </script> </body> </html> -
Django RestFramework - Optional Nested serializer ID on POST, Detail on GET?
I've encountered the following problem. Lets say I have a simple Profile Serializer and that is used as a nested serializer within the DevelopmentPLanItemSerializer, like so: class SimpleProfileSerializer(serializers.ModelSerializer): profile_image = serializers.SerializerMethodField() class Meta: model = um.Profile fields = ('id', 'name', 'profile_image') def profile_image(self, obj): return obj.profile_image_url class DevelopmentPlanItemSerializer(serializers.ModelSerializer): id = serializers.ModelField( model_field=dp.DevelopmentPlanItem()._meta.get_field('id'), required=False, allow_null=True ) name = serializers.CharField(required=False, allow_null=True) profile = SimpleProfileSerializer(required=False, allow_null=True) class Meta: model = dp.DevelopmentPlanItem fields = ('id', 'title', 'name', 'profile') Now, I've market the 'profile' field with required=False, allow_null=True as this field is optional. However, when I save I still get an error because the fields within the SimpleProfileSerializer are not allowed to be empty. I could solve this by removing the nested serializer, so that I only POST / GET an Profile.id on the DevelopmentPlanItemSerialzer.profile field, but we really want the additional info from this field, not just the ID. Is there a way to accomplish this? Where we, for example, supply only a Profile.PK on POST and get the entire nested serialized info on a GET request? -
wsgi: No module named 'settings'
I have installed apache2 and wsgi on my Ubuntu16.4 I got this error; ImportError: No module named 'settings' In my Django project folder, there is the directory named 'settings' and inside 'settings' folder, several settings files like default.py, development.py,... exist. Inside wsgi_dev.py, the setting is done for wsgi. os.environ.setdefault("DJANGO_SETTINGS_MODULE",'settings.development') This settings folder is not recognized as module. I have __init__.py inside settings folder. -
Is it possible to implement with Django Restframework?
I'm making API Server with DRF(DB is MySQL). Now I made some system similar with facebook's like. First, below is my Database Structure. [user table] userkey(PK) username [article table] articleNo(PK) userkey(FK to user) content [like table] articleNo userkey(FK to user) When user click the "Like" buttons, articleNo and User's key will be inserted into like table. Currently, When I access to /article/, shows below result. { "articleNo": 1, "userkey": "22222", "content": "test1", "date": "2018-02-14T22:34:36.673805+09:00" }, { "articleNo": 2, "userkey": "11111", "content": "test2", "date": "2018-02-15T22:34:36.673805+09:00" }, ... ... If like table has two row like this, +-----------+---------+ | articleNo | userkey | +-----------+---------+ | 1 | 11111 | | 1 | 22222 | +-----------+---------+ It means that 11111 and 22222 user likes articleNo==1. So When user access to /article?userkey=11111, What I would like instead as output is something like: { "articleNo": 1, "userkey": "22222", "content": "test1", "isLiked": "true", // add this line "date": "2018-02-14T22:34:36.673805+09:00" }, { "articleNo": 2, "userkey": "11111", "content": "test2", "isLiked": "false", // add this line "date": "2018-02-15T22:34:36.673805+09:00" }, ... ... Is it possible to implement with DRF? Thanks. -
How to disallow method on Django model?
If I need disallow some methods on Django model on condition, then what exception to drop? Example: class Container(Certificate): def sign(self, csr): if self.authority: # some code else: raise SomeError() -
Wagtail ModelAdmin - multiselect filters
is there a way to make filters in Wagtail modeladmin index page multiselectable? Best Regards, Konrad -
Django user object can not display
The goal is to show a users images on their profile page. The current error message I am getting is "'Images' object is not iterable". views.py def view_profile(request, pk=None): if pk: user = User.objects.get(pk=pk) else: user = request.user args = {'user': user, 'images': Images.objects.get(pk=pk)} return render(request, 've/cp/profile.html', args) profile.html {% if images %} {% for img in images %} <img src="{{ img.image.url }}" class="float-left" style="max-width: 150px"> {% endif %} {% else %} models.py class Images(models.Model): image = models.ImageField(upload_to='profile_image', null=True, default='profile_image/none/no-img.png') user = models.ForeignKey(User, on_delete=models.CASCADE, null=False) -
request.session is not transferring full querydict to another view
I am submitting a form using 'post' and transferring its data to another view using request.POST but my querydict is incomplete when it arrives in the second view. view1 def question_filter(request): if request.method == 'POST': print('before validation', request.POST) request.session['question_data'] = request.POST return HttpResponseRedirect(reverse('qapp:question_preview')) view2 def question_preview(request): all_questions = Questions.objects.all() question_data = request.session.get('question_data') print(question_data) question_pk_list = question_data['question_pk'] preview_questions = all_questions.filter(id__in=question_pk_list) ... return render(request,'apps/qapp/question_preview.html', {somecontext}) Am I doing something wrong here ? -
ManyToManyField how i can store many data in one DB field -- Django
class Roles(models.Model): name = models.CharField(max_length=60, unique=True) def __str__(self): return self.name class Permission(models.Model): name = models.CharField(max_length=60, unique=True) create = models.BooleanField(max_length=5) read = models.BooleanField(max_length=5) update = models.BooleanField(max_length=5) delete = models.BooleanField(max_length=5) def __str__(self): return self.name class RolesHasPermission(models.Model): role_id = models.ForeignKey(Roles, on_delete=models.CASCADE) permission_id = models.ManyToManyField(Permission) in RoleHasPermission i need to store many permission_id in on role_id how can i do this i tried alot but i cant find the solution for this problem :(