Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Changing name of Foreign Key items at admin page in Django
I have created two Django models, were a field from one model is a Foreign key to another (as per below). class Units(models.Model): name = models.CharField(max_length=10, primary_key=True) symbol = models.CharField(max_length=5) class Targets(models.Model): name = models.CharField(max_length=100) unit = models.ForeignKey(MicroNutrientUnits) ... These models are then registered to the admin site via admin.site.register. When adding an item to table Target unit correctly reflects items from table Units, however are represented in a dropdown with the name Units objects for each entry. How can I set the name in the admin dropdown to Units.name in the admin config page? -
How can I set required field only for specified function in Django GenericAPIView?
Let's assume that I have such a GenericAPIView: class UserObject(GenericAPIView): serializer_class = ObjectSerializer def post(self, request, user_id): serializer = ObjectPostSerializer(data=request.data) if serializer.is_valid(): serializer.save(user_id=user_id) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def get(self, request, user_id): try: object = Object.objects.filter(user=user_id) except Object.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) serializer = ObjectSerializer(object, many=True) return Response(serializer.data) In ObjectSerializer I have: def __init__(self, *args, **kwargs): super(ObjectSerializer, self).__init__(*args, **kwargs) for key in self.fields: self.fields['field'].required = True I would like to only for POST method set self.fields['field'].required = False Any ideas how can I do that? I tried in ObjectPostSerializer: def __init__(self, *args, **kwargs): super(ObjectSerializer, self).__init__(*args, **kwargs) for key in self.fields: self.fields['field'].required = False My model looks in this way: class Object(models.Model): name = models.CharField(max_length=200) user = models.ForeignKey('auth.User') field = models.FloatField() field2 = models.FloatField(null=True, blank=True) But this line serializer_class = ObjectSerializer is crucial and only settings from this serializer are visible for instance in Swagger. I try in this way: def __init__(self, *args, **kwargs): super(ObjectSerializer, self).__init__(*args, **kwargs) for key in self.fields: self.fields['field'].required = not bool(kwargs.get("is_post")) Then def post(self, request, user_id): serializer = ObjectPostSerializer(data=request.data, is_post=True) #rest of code But I get __init__() got an unexpected keyword argument 'is_post' Any ideas how can I solve it? Maybe it should be done in another, more … -
Why after deploying django docker container, emails getting sending failed?
I was working on django and everthing was working fine on my local machine as well as on heroku. But than i deodorize my django project and it was working fine locally till now. now i have depolyed this container on my dedicated server and than i came to know that my emails was failing after deployment. Can anybody have idea why my dedicated server is not sending mails? I am sending mails using smtp protocol. Any help or suggestion will be highly appreciated. Thanks. -
cascade select with parent, child and sub child drop down boxes
I am creating a form using django 1.8. in this form I am using cascade select on three fields type, subtype and category. Type is the parent of subtype. subtype is the parent of category. When I change the value in the type drop-down box the subtype drop down box is disabled but the category drop down box is still active. I am wondering how to disable the category drop down box as well. The category drop down box is disabled when the subtype drop down box is changed by the user. cascade select CascadeSelect({ use_ajax: true, url: "{{ request.get_full_path }}", // The url for the ajax function parent: "id_project_type", // Name of the parent field in forms.py child: "id_sub_type", // Name of the child field in forms.py selected_child: "{{ selected_sub_type }}", // Sent from views.py empty_label_init: "Select a type first", empty_label_selected: "--- Please select ---", disable_child: true }); CascadeSelect({ use_ajax: true, url: "{{ request.get_full_path }}", // The url for the ajax function parent: "id_sub_type", // Name of the parent field in forms.py child: "id_category", // Name of the child field in forms.py selected_child: "{{ selected_sub_type }}", // Sent from views.py empty_label_init: "Select a type first", empty_label_selected: "--- Please select … -
Deleting item using Ajax request with DELETE , using JQuery
I am trying to delete a post when clicking the (x) icon using Ajax request here is my html code relating to this part : My html blog.js delete.php I copied the JS and php parts from google , I've never written an Ajax request before so I cannot figure out where I did wrong, please help -
How can I authenticate user both in websockets and REST using Django and Angular 4?
I would like to authenticate user both in websockets and REST using Django and Angular 4. I have created registration based on REST API. User after creating an account and log in can send messages to backend using websockets. My question is how can I find out that the authenticated user by REST API (I use Tokens) is the same user who sends messages? I don't think that sending Token in every websocket message would be a good solution. consumers.py: def msg_consumer(message): text = message.content.get('text') Message.objects.create( message=text, ) Group("chat").send({'text': text}) channel_session_user_from_http def ws_connect(message): # Accept the connection message.reply_channel.send({"accept": True}) # Add to the chat group Group("chat").add(message.reply_channel) message.reply_channel.send({ "text": json.dumps({ 'message': 'Welcome' }) }) @channel_session_user def ws_receive(message): message.reply_channel.send({"accept": True}) print("Backend received message: " + message.content['text']) Message.objects.create( message = message.content['text'], ) Channel("chat").send({ "text": json.dumps({ 'message': 'Next message' }) }) @channel_session_user def ws_disconnect(message): Group("chat").discard(message.reply_channel) -
NoReverseMatch for detail with arguments '('',)' not found
So i have a blog app that show the blog posts and a post_detail page, yesterday i added the next post button with the post.get_next_by_created_at() every thing is working but if i viewed the last post django raise an error because there is no post after this post. The error: Post matching query does not exist. i tried this code: def post_detail(request, pk): post = Post.objects.get(id=pk) try: next = post.get_next_by_created_at(series=post.series) except: next = 1 return render(request, 'blog/read_post.html', {'Post': post, 'next': next}) this code worked with previous posts but Django raise an error: Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) with last post again so what to do to avoid this error, thanks in advance -
Implement 2 ways sign up with custom user model
I follows https://github.com/jcugat/django-custom-user to create my own custom user model. My code in model.py is shown below. # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from custom_user.models import AbstractEmailUser class MyCustomEmailUser(AbstractEmailUser): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) contact_number = models.CharField(max_length=20) REQUIRED_FIELDS = ['contact_number', 'first_name', 'last_name'] # Create your models here. Then, I wish to implement signup view using https://django-registration.readthedocs.io/en/2.3/hmac.html#behavior-and-configuration so I can enable email activation feature. However, I am not using form by Django. The form will be sent with ReactJS front end therefore I only need to create view that accepting POST request. How should I implements django-registration with custom user? I am stucked after following the documentation on writing code on urls.py from django.conf.urls import include, url urlpatterns = [ # Other URL patterns ... url(r'^accounts/', include('registration.backends.hmac.urls')), # More URL patterns ... ] -
Django 1.11 - static file not found
I'm working on a Django project (Django 1.11), and I'm trying to use static file. This is my project structure: |project_name |---- app_name |-------- src |------------ static |---------------- css |-------------------- bootstrap |------------------------ bootstrap.min.css |-------- templates |------------ base.html |------------ first_template.html |-------- views |------------ first_view.py |---- project_name |-------- settings.py In settings.py file, I have django.contrib.staticfiles in INSTALLED_APPS and I set STATIC_URL variable as follow: STATIC_URL = '/src/static/' Then, I'd like use static files in base template, and this is what I've done: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %}{% endblock %}</title> <link href="{% static "css/bootstrap/bootstrap.min.css" %}" rel="stylesheet"> </head> <body> {% block content %}{% endblock content %} </body> </html> When I load first_template.html, and so also the base.html file, the bootstrap.min.css file is not found (404). I know that is a trivial question, but i really don't understand what i'm missing. I have checked a lot of similar SO questions without success, also because most of them refer to old django versions Thank you in advance -
How can i use angular4 just for showing some data in a Django template
I want to implement simple angular4 component rendering (lets say list of use activity component) in django template. I know it is possible in angular1, with few lines of code (ng-controller and etc). React supports the same with just few lines of code ReactDOM.render.But not sure if its possible with angular4. I realised there is something called https://angular.io/api/core/Renderer2 , is this something close to ReactDOM.render(not sure). So my questions are Is it possible to use angular4 for my usecase or angular4 has grown so much from angular1 that it cannot support this usecase. How to implement a angular component(Example: UserActivityComponent) in the django template. Even if I manage to do it, angular uses typescript, whats the best way to translate it to js for deployments If its not possible whats the best solution. We use lot of angular4 in our products, so just trying to avoiding add new stack(React) into the team. Just exploring if there is a way or we have to go to React. -
Get Context from mail outbox body when sending email with Django EmailMessage
Let say I created a Mailer class from django.core import mail from django.core.mail import EmailMessage from django.template.loader import get_template class Mailer: def __init__(self, from_email=None): self.connection = mail.get_connection() self.from_email = from_email` def send_messages(self, subject, template, context, to_emails): messages = self._generate_messages( subject, template, context, to_emails) self._send_mail(messages) def _send_mail(self, mail_messages): self.connection.open() self.connection.send_messages(mail_messages) self.connection.close() def _generate_messages(self, subject, template, context, to_emails): messages = [] message_template = get_template(template) for recipient in to_emails: message_content = message_template.render(context) message = EmailMessage(subject, message_content, to=[ recipient], from_email=self.from_email) message_content.content_subtype = 'html' messages.append(message) return messages And I sent it like this: email = Mailer() email.send_messages(subject='Account verification', template='emails/account_verification.html', context={'user': user}, to_emails=[user.email]) We could access mail body with: `mail.outbox[0].body can we access context object like the one in HttpResponse? Perhaps for unittest. -
Got AttributeError when attempting to get a value for field in Django - ForeignKey Relationship
Please check me this error with serializers. I have a model Avatar: class Avatar(models.Model): user = models.ForeignKey(User, related_name='avatar_user', null=True) photoset = models.ForeignKey(PhotoSet, null=True, blank=True) primary = models.BooleanField(default=True) date_uploaded = models.DateTimeField(default=datetime.datetime.now) image = models.ImageField(max_length=1024, upload_to=avatar_file_path) I created a serializer User with avatar class BasicAvatarSerializer(ModelSerializer): class Meta: model = Avatar fields = [ 'user', 'photoset', 'image', ] class UserBasicSerializer(ModelSerializer): avatar_set = BasicAvatarSerializer() class Meta: model = User fields = [ 'username', 'avatar_set', 'first_name', 'last_name', ] But it get error: enter image description here -
Django: using CreateView to create object for a related model too
I have 2 models: class Store(models.Model): owner = models.ForeignKey(User, null=False, verbose_name='User') name = models.CharField(max_length=200, null=False, verbose_name='Store name') address_line_1 = models.CharField(max_length=200, null=False, verbose_name='Address line 1') address_line_2 = models.CharField(max_length=200, null=False, verbose_name='Address line 2') city = models.CharField(max_length=200, null=False, verbose_name='City') state = models.CharField(max_length=200, null=False, verbose_name='State') zip_code = models.CharField(max_length=200, null=False, verbose_name='Zip/Pin Code') country = models.CharField(max_length=200, null=False, verbose_name='Country') phone = models.CharField(max_length=12, verbose_name='Phone') email = models.EmailField(verbose_name='Email') website = models.URLField(verbose_name='Website') archive = models.BooleanField(default=False, verbose_name='Archive') class StoreSetting(models.Model): store = models.OneToOneField( Store, on_delete=models.CASCADE, null=False, unique=True, verbose_name='Store' ) currency = models.CharField(max_length=200, default="$", null=False, choices=CURRENCY, verbose_name='Currency') separator = models.CharField(max_length=1, default=",", null=False, choices=DECIMAL_SEP, verbose_name='Decimal seperator') date_format = models.CharField(max_length=1, default="DD/MM/YYYY", choices=DATE_REP, null=False, verbose_name='Date format') I am using CreateView to add data to both Store and StoreSettings. But I want to create a default StoreSettings as for a store as soon as the Store is created and then later just access StoreSetting for a particular store using UpdateView. How to achieve this in Store's CreateView? -
Add functionality to third party app
I have a third party app in my proyect and I want to add one model class and some nctionality in the admin page. In particular, I started using django-push-notifications to send push notifications to users. The problems are: Admin app doesn't come with a button to send notifications. The models and the views doesn't contemplate the option to send push notifications using the admin page. I solved the first problem overriding the app_index.html template of the app. No problem here. The problem is when I try to add functionality to that button. I need that when the button is pressed, it shows a modal like this one where I can enter things that are not in the original model. For example, it would be useful to have a model class "Notification" with fields like title, body, image, icon, a dropdown list of topics, etc. Then, when I press the button "SEND PUSH" in the admin page, a pop up is displayed with a form to enter those fields. And finally, when I want to send the notifications, a view (I guess...) receive these values and send the notifications (in this way or this way). Any suggestions? -
previous object values persist while creating new model object in a loop
Here is the model: class ModelA(models.Model): field1 = models.CharField(max_length=100) field2 = models.CharField(max_length=100) def save(self, *args, **kwargs): # Below print should be None # But it shows the value of the previously created object, why ? print self.field2 self.field2 = self.field1 + " world" super(ModelA, self).save(*args, **kwargs) Here is the view: def view1(request): for x in range(1, 3): a = ModelA.objects.create(field1="hello%s" % x) Expected output: None None None Achieved output: None hello1 world hello2 world So, as per the given output, can you tell me why its using previous objects values while creating a new object ? -
Daphne Django file upload size limitations
I am using Daphne for both socket and http connections. I am running 4 worker containers and running everything locally right now in a docker container. My daphne server fails if I try to upload a file that is 400MB. It works fine for small files upto 15MB. My docker container quits with error code 137. I dont get any error in daphne logs. The daphne container just dies but the worker containers keep on running. Does anyone know if there is a way to increase upload limits on daphne or I am missing something else? I start the daphne server by daphne -b 0.0.0.0 -p 8001 project.asgi:channel_layer --access-log=${LOGS}/daphne.access.log -
How to custom related result Django Rest Framework
I implement django rest framework and received bellow results: { "count": 3, "next": null, "previous": null, "results": [ { "id": 2, "created_at": "2017-10-16T09:55:07.663791Z", "modified_at": "2017-10-16T09:55:07.663846Z", "visible": true, "name": "Viewer", "permissions": [ 2, 3 ] }, ... ] } So I want field permissions would be: "permissions": [ "name permission 1", "name permission 2" ] What should I do? -
Installed djangorestframework but imports on error
I just installed djangorestframework on an existing app. I followed the first page of django rest framework tutorial, added my rest_framework to my INSTALLED_APPS, followed the tutorial and did from rest_framework import routers, serializers, viewsets but I get an error on this line "...\docutils\core.py", line 246 print ('\n::: Runtime settings:', file=self._stderr) SyntaxError: invalid syntax invalid syntax at =. I tried a different tutorial and it appears that any from rest_framework i just can't import it and gives me the same error. I am using python 2.7.8 and django 1.10.5, and just freshly installed the djangorestframework. I don't know where to go from here. I've searched and seemed the result is pretty limited. Any kind suggestions/directions? -
Django avoid user back to form click navigator back button
What is the best way in Django to avoid user back to form by clicking navigator back button? The login page or any other form. There are somo post addresing the subject but they are of php. Thanks! -
Creating a cas server gateway in django
What would be the proper way to create a gateway (similar to how django-cas does with it's decorator). Since login is shared across all domains this gateway should be processed on every request which would indicate a middleware to me. But, the gateway is checking for the cas server ticket in the session and if it exists (and the user is not authenticated) then authenticating them. Why I'm doing this: Say I log into my domain (say 1) through the cas server then domain (say 2) only picks this up as being authenticated after visiting the cas servers login route. I want to bypass this step since a user isn't going to visit the cas login url this way and I don't want them to actually have to login if login isn't required. Wasn't sure if middleware was the way to go with this. I can decorate all of my views of course but looking for DRY. -
Django One-to-One field is not saving (violates not-null constraint)
I am trying to save a form that has a one-to-one field. However it keep getting an error null value in column "account_id" violates not-null constraint. Not sure why I couldn't save the new account object in the one-to-one field. Model class Account(models.Model): name = models.CharField(max_length=30) class Bank(models.Model): account = models.OneToOneField(Account, on_delete=models.CASCADE, primary_key=True) bank_name = models.CharField(max_length=30) View def add_bank_view(request): if request.method == 'POST': form = BankForm(request.POST) if form.is_valid(): account = Account.objects.create(name='xxx') bankform = form.save(commit=False) bankform.account = account bankform.save() return HttpResponseRedirect('/add_banks/') else: form = BankForm() return render(request, 'bank/add_bank.html', {'form': form}) Form class BankForm(forms.ModelForm): class Meta: model = Bank fields = ['bank_name'] -
How to get the count of each value from different fields using Django Queries?
I have a Django model with many fields. Let's say the model is like this: class Foo(models.Model): name = models.CharField(max_length=50) type = models.CharField(max_length=100, blank=True) foo_value = models.CharField(max_length=14, blank=True) # ... and many many other fields Now I need to run a query to get me all the data from all fields. This would be Foo.objects.all(), right? Now I need for each name (which means I will group by name) to do some things. First, the problem is if I want to group by name I would do this: Foo.objects.values('name'), right? But this gets me the 'name' field value only for all records. I need all the other fields but grouped by name. The second more important thing is, I need to get the count of each distinct value in the 'type' field as well as the sum of the 'foo_value' field associated with each 'type'. I need all this to be one record per 'name' in the returned result. The issue is, if I tried this: Foo.objects.values('name').annotate(c=Count('type'), s=Sum('foo_value')), it will get me a record for each ('name', 'type') pair. What I need is that if I have data like this: name type foo_value x t1 5.5 x t1 10.0 x t2 20.0 y t2 15.23 y t1 17.0 I need the result … -
Django: dynamic pagination and variable paginate_by
After searching solution for my puzzle I decided to ask one more question on this board. So. The conditions: - class ListView has paginate_by = 12 - in html-template there is dropdown list with several options to change my paginate_by with POST request - works fine at first, changesnumber of objects on page and number of pages of course - to show links for pagination I prefer to use recipe from https://www.tummy.com/articles/django-pagination/ - had to make come corrections, but shows links to different pages in proper The problem: - after changing paginat_by of class ListView, with dropdown list, I move to next page, and paginate_by returns to first value = 12, and of course return to previous number of objects on page and number of pages of course ... by the way - at first dropdown list show selected number 12, as should, but after changing value it selects the first value, even if i choose the last one and number of pages is changed according to last value My questions: - Is attribute paginate_by returning back to first (12) value every every time the template page is rendered? is there any way to keep it for little longer? - … -
Django Rest - Adding query parameter data in viewset
In the documentation for dynamic extension of DRF they describe the possibility to to add query parameters through the viewset.(instructions) These added query parameters act as if they were being passed in the url request, thereby triggering dynamic actions available through the extension. But I can't get this to work. It seems impossible to make the serializer or router to recognize the alteration of the request instance. Any suggestions as to where to learn more about how this works, or alternative ways to do it would be greatly appreciated. class EventViewSet(DynamicModelViewSet): # … def list(self, request, *args, **kwargs): # sideload location by default request.query_params.add('include[]', 'location.') # filter for status=current by default status = request.query_params.get('filter{status}') if not status: request.query_params.add('filter{status}','current') return super(EventViewSet, self).list(request, *args, **kwargs) -
django datetimefield: __str__ give different time from admin display
i am trying to setup the str() to display a datetimefield in admin site. but it give me a different time in different pages. the code is like: class Order(models.Model): order_date = models.DateTimeField(auto_now_add = True,null=True) def __str__(self): return self.product.name + \ " ordered on " + \ str(self.order_date.strftime("%Y%m%d-%H:%M:%S")); it give a time like 20171027-22:28:40 in the list of My_model. However, "Oct. 27, 2017, 3:28 p.m." is displayed if i click into the entry as the pictures. enter image description here enter image description here