Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Django pass an url to template for reusable code
My question is if it's possible to pass a named url from the view to the template for reusing template code, something like this, but it's passed as raw string. class PersonCreateView(CreateView): ... def get_context_data(self, **kwargs): context = super(PersonCreateView, self).get_context_data(**kwargs) context['myurl'] = "{% url 'people:person-index' %}" return context And in the template: <a class="btn btn-default pull-right" href="{{ myurl }}" role="button"> Thanks! -
Django : change allauth singup template
I want to change the template of socialaccount/singup template in a project that i am working on django 1.11.0, here's the template : {% extends "socialaccount/base.html" %} {% load i18n %} {% block head_title %}{% trans "Signup" %}{% endblock %} {% block content %} <h1>{% trans "Sign Up" %}</h1> <p>{% blocktrans with provider_name=account.get_provider.name site_name=site.name %}You are about to use your {{provider_name}} account to login to {{site_name}}. As a final step, please complete the following form:{% endblocktrans %}</p> <form class="signup" id="signup_form" method="post" action="{% url 'socialaccount_signup' %}"> {% csrf_token %} {{ form.as_p }} {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} <button type="submit">{% trans "Sign Up" %} &raquo;</button> </form> {% endblock %} How can I replace it with my own template in my project ? -
Django: Exclude Extra Users
Here's my Query, users = User.objects.all() # contains all users extra_users = Models.objects.filter(user=request.user) # contains few users related to request.user Hoe can I exclude extra_users from users? -
DJango Querysets Filter
clients = Client.objects.filter(user_id=request.user) quotes = Quote.objects.filter(customer_act_id=clients) I have the above code and I am trying to display the users clients and quotes to the user. The clients display fine but the quotes only show the quotes for the FIRST client and not all of them. Any help is appreciated. Relationships: User has_many clients(user_id FK) has_many quotes(client_id FK) -
Anaconda virtual environment django in windows
I created a virtual environment using anaconda in windows, and there are a lot of stuff installed within the virtual environment, when I tried to add my project to the github, it listed all the files within the directory to be committed and showed the follow warnings: LF will be replaced by CRLF. how can I properly set up a virtual envs by using Anaconda3 to start my django project, many thanks. -
Django insert script
I would like to have one time insert script in django to the database configured in the settings. This script could be rerun and would only insert once i was going to have something like my_list =[{key:value},{key:value}] with transaction.atomic(): for item in my_list: my_model = a_model(my_key=item['key']) my_model.save() But I don't know how to get it running -
using __import__ on a module in a different directory python. django
I am attempting to import a model from another app in django. The following attempts fail fails: from venueadmin.models import VenuePermissions fails how: Python is not able to located VenuePermissions, i guess circular reference? from django.apps import apps suitscity = apps.get_model('suitsandtablesadmin', 'City') fails how: raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. so then I tried importing using __import__ suitscity = __import__('suitsandtablesadmin.models') suitscity = getattr(suitscity, 'City') and suitscity = __import__('suitsandtablesadmin/models') suitscity = getattr(suitscity, 'City') all of which did not work because City is in a different directory suitsandtablesadmin how can I make any one of these work -
Displaying models' instances in Django admin index page
I'm trying to modify admin page in Django. I want my admin index page to display the names of my models as well as those models' instances just like in the change list page. How can I do that without modifying Django core files?