Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In Django, why do view functions require a request parameter?
Example from Django documentation: def index(request): return HttpResponse('<h1>hellworld!</h1>') def detail(request, question_id): return HttpResponse("Question: %s" % question_id) Since the request argument is never used, why should I include it in each function signature? -
Adding Filer to Django CMS toolbar?
On the Django CMS demo they have something called a "Media Library" which takes you right to the Django Filer. How do I put this on the tool bar? I can go to it easily through the admin but not get an option for the toolbar. -
django fat models: should they make rest requests?
Some time ago a colleague of mine wrote a method on a model that updated its data over a REST api. At that time, I thought that this kind of thing should be done by a controller (or view in Django's lingo), which should make the request and tell model to update itself, and so I asked her to rewrite that. However, reading more on Django and its "Fat models" approach, I now come to think that it is the model that should do the request after all. It is a payment system, and the model in question is a Transaction. The REST api that needs to be called is a backend of that payment system that has certain statuses that affect the status of the transaction, and the REST api call is made to check the status of the remote system and to set the status of the Transaction in the local application. What would you do? Where would you put the API call: the model or a view? -
'Image' object has no attribute '_committed' django - python
I'm cropping with an imge cropper. I use a form to handle the crop process. The below snippet is that for: class EditHeaderForm(forms.Form): x = forms.FloatField() y = forms.FloatField() width = forms.FloatField() height = forms.FloatField() file = forms.ImageField() def clean_file(self): file = self.cleaned_data.get('file', False) if file: filetype = magic.from_buffer(file.read()) if file._size > 3 * 1024 * 1024: raise ValidationError("The image shouldn't more than 3 MBs") x = self.cleaned_data.get('x') y = self.cleaned_data.get('y') w = self.cleaned_data.get('width') h = self.cleaned_data.get('height') image = Image.open(file) cropped_image = image.crop((x, y, w + x, h + y)) resized_image = cropped_image.resize((200, 200), Image.ANTIALIAS) return resized_image and this is the model that I want to save image to it: class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile', on_delete=models.CASCADE) name = models.CharField(max_length=30) header = models.ImageField(upload_to=userHeaderNameToSave, blank=True, null=True) and at last, the below snippet is my view: def change_header(request): form = EditHeaderForm(request.POST, request.FILES) if form.is_valid(): profile = get_object_or_404(Profile, pk=request.user.profile.pk) profile.header = form.cleaned_data['file'] profile.save() return JsonResponse({'success': True}) else: return JsonResponse({'success': False, 'errors': form.errors}) When I try to upload and crop the image, it shows me this error: 'Image' object has no attribute '_committed'. the cropper crops image properly, but when the profile tries to save, it shows the error. How can I solve the … -
Get information from a model using unrelated field
I have these two models: class A(models.Model): name=models.CharField(max_length=10) class D(models.Model): code=models.IntegerField() the code field can have a number that exists in model A but it cant be related due to other factors. But what I want know is to list items from A whose value is the same with code items=D.objects.values('code__name') would work but since they are not related nor can be related, how can I handle that? -
Django optional parameter is not readed from url
I was reading the thread Django optional url parameters And following the steps to generate a URL with a single optional parameter. Well, my URL should be: /client/ /client/?clientname=John And I have defined two urlpatterns url(r'^$', views.index, name='index'), url(r'^/(?P<clientname>\d+)/',views.index), Well, at this point both of them render the page. But, in my view: def index(request, clientname='noparameter'): print("The searched name is: " + str(clientname)) The searched name is always noparameter Am I doing something wrong? -
Django port not open in container when starting Django Docker container via shell script
I'm trying to containerize my Django application, and everything is working fine, except in the situation where I try to run the container from a shell script. In this case, the Django server is running, but the port is not open inside the container. Here's the command I'm running to start the container: docker run -d -p 8000:8000 --net=mynet --name myapp -v $PWD:/myapp myimage ./ss ss is a shell script that launches my Django app. It contains: python3 manage.py runserver 0:8000 When I run the Docker RUN command from the command line, everything works fine; the port is mapped correctly, I can browse to my app from a browser in my host and it loads correctly, etc. However, if I copy the above run command in a shell script (start_container.sh for example), the container launches just fine, the ports are mapped correctly, but when I try to open the app in my browser, I get a connection reset error. If open a shell to the container by running docker exec -i -t myapp /bin/bash I can get into the container. I check running processes with ps -eaf I do see the python process running my Django app. However, if I … -
Django- copy filefield url
I want to copy FileFieldURL from one model to another model.not file or image.just URL only how can I do that? for eg: Sender to receiver. sender uploaded some file for receiver and receiver receives that file. models.py sender: class DB1(models.Model): user = models.ForeignKey(User) attachments = models.FileField(upload_to= 'attachments/',blank=True,null= True) Receiver: class DB2(models.Model): user = models.ForeignKey(User) copy_url= ??? -
Django - Multiple post_save signals after create despite dispatch_uid
I'm having trouble preventing a post_save signal from firing multiple times after the creation of an object. My signal is defined as follows: @receiver(post_save, sender=Order, dispatch_uid='post_save_order') def post_save_order(sender, **kwargs): instance = kwargs.get('instance') if instance.type == 'buy': delta = instance.quantity else: delta = instance.quantity * -1 Balance.update(instance.user, instance.quote_currency, delta) the signal is imported in orders/apps.py class OrdersConfig(AppConfig): name = 'orders' def ready(self): super(OrdersConfig, self).ready() import orders.signals When printing passed kwargs to the signal after 1 Order.create: {'instance': object, 'signal': signal, 'using': 'default', 'update_fields': None, 'raw': False, 'created': True} {'instance': object, 'signal': signal, 'using': 'default', 'update_fields': None, 'raw': False, 'created': False} {'instance': object, 'signal': signal, 'using': 'default', 'update_fields': None, 'raw': False, 'created': False} {'instance': object, 'signal': signal, 'using': 'default', 'update_fields': None, 'raw': False, 'created': False} so apparently on a single creation, there is 1 post_save signal fired with args created: True and three with created: False. I don't think that the problem is that the signal may be imported multiple times, because I provided a dispatch_uid and a post_delete signal that is defined in the same file is not fired multiple times on a single deletion. Can anyone enlighten me why this is happening? Thanks -
Turning off access logging for static GET requests in nginx
I see a lot of GET requests in my nginx access logs that relate to static assets. Is there a way to turn off nginx access logging for assets (e.g. in /static/)? I've already done the following, but it hasn't solved the problem: location ~* \.(?:ico|css|js|gif|jpe?g|png)$ { root /home/myuser/myproject/myapp; access_log off; expires 30d; add_header Pragma public; add_header Cache-Control "public, must-revalidate, proxy-revalidate"; } In case relevant, I'm using nginx as a reverse proxy with gunicorn (Django). -
DJANGO static images dont show me in template
I try to use static images in my template using DJANGO framework and that images don't view in my page. I follow complete the manuals. any idea ? here the code : html : {% load staticfiles %} div class="portfolio-item"> <a href="#"><img class="img-portfolio img-responsive" src="{% static portfolio2.jpg %}"></a> </div> settings.py : STATIC_URL = '/static/' STATICFILES_DIRS=( os.path.join(BASE_DIR, 'static','static_dirs'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'static','static_root') MEDIA_ROOT = os.path.join(BASE_DIR, 'static','media') MEDIA_URL = ('/media/') urls.py + urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) -
Django / combinig DetailView FormMixin and Function based views
I try to make a reddit clone with django. The problem is I can't combine DetailView and a function based view. I can create a post and comments to specific posts but couldn't make nested comments. I created the logic but couldn't render it. How should I render nested comments ? I can't get the data wit get_context_data views.py class EntryDetail(DetailView, FormMixin): template_name = 'post_detail.html' model = Post form_class = CommentForm def get_success_url(self): return reverse_lazy('post-detail', kwargs={'pk': self.object.pk}) def get_context_data(self, **kwargs): context = super(EntryDetail, self).get_context_data(**kwargs) context['post_object'] = Post.objects.filter(pk=self.kwargs.get('pk')) context['comments'] = Post.objects.get(pk=self.kwargs.get('pk'))\ .comments\ .all() return context def post(self, request, *args, **kwargs): form = self.get_form() p_object = Post.objects.get(pk=self.kwargs.get('pk')) if form.is_valid(): form.save(post=p_object.id) return redirect(reverse_lazy( 'post-detail', kwargs={'pk': p_object.pk})) def add_sub_comment(request, comment_id): comment = Comment.objects.get(pk=comment_id) if request.POST: form = SubCommentForm(request.POST) if form.is_valid(): form.save(comment_object=comment.id) return redirect('index') sub_comments = Comment.objects.filter(object_id=comment.id) ctx = {'sub_comments': sub_comments} return render(request, 'post_detail.html', ctx) urls.py urlpatterns = [ url(r'^$', EntryView.as_view(), name='index'), url(r'^new_post/$', EntryCreate.as_view(), name='new-post'), url(r'^post_detail/(?P<pk>\d+)/$', EntryDetail.as_view(), name='post-detail'), url(r'^sub_comments/(?P<comment_id>\d+)/$', views.add_sub_comment, name='sub-comment'), ] post_detail.html {% for comment in comments %} <div class="comment-per-style"> {{ comment.entry_comment }} {% for subcomment in sub_comments %} <ul> <li>{{ subcomment.entry_comment }}</li> </ul> {% endfor %} </div> <form action="{% url 'sub-comment' comment.id %}" method="post"> {% csrf_token %} <input id="entry_comment" type="text" name="entry_comment" maxlength="100" required … -
Testing views in Django, need a hand
I'm trying to understand how django works,but I have a question in views. With the code below def post_list(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'blog/post_list.html', {'posts': posts}) I understand the dictionaries but I do not know why {'posts': posts} is a dictionary with the same word and the value does not have quotation marks. When I use dictionaries I use something like: hello = {'my_key': 'this is text', 'my_key2': 2017 } {'posts': posts}, in this example post is shown twice and the second, I mean the value does not have quotation marks. can anyone explain me please? -
Reverse for viewname with arguments '(1,)' not found
Attempting to start the server and getting following exception (starting server leads to polls/index.html page): django.urls.exceptions.NoReverseMatch: Reverse for 'detail' with arguments '(1,)' not found. 1 pattern(s) tried: ['$(?P[0-9]+)'] If I remove the following line fron index.html, the error is removed. But I don't get what the issue is. Even the ide prompts the current data. Found similar questions where the issue was with incorrect number of arguments which isn't the case with this. Please help. Error line: {% url 'polls:detail' q.id %} index.html {% for q in latest_question_list %} <li><a href="{% url 'polls:detail' q.id %}">{{ q.question_text }}</a></li> {% endfor %} urls.py app_name = 'polls' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P<question_id>[0-9]+)', views.detail, name='detail'), ] views.py def index(request): latest_question_list = Question.objects.order_by('pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context) def detail(request, question_id): return HttpResponse(question_id) -
Is there a way to add a ForeignKey to the Site model in Django Sites Framework?
This answer shows the inverse of what I'm looking for because it allows one Site to have many Asset objects: from django.contrib.sites.models import Site class Asset(models.Model): site = Models.ForeignKey(Site) Is there a way to add the ForeignKey field to the Site model, such that one Asset can have many Site objects? Something like this (non-working) code: from django.contrib.sites.models import Site class UpdatedSite(Site): asset = models.ForeignKey(Asset) I understand that I could use a ManyToManyField but in my case one Site object will never have multiple Asset objects. -
Why is gunicorn displaying an extra process?
I have a gunicorn web server on my django app in my docker container and my gunicorn config is: bind = '0.0.0.0:8001' loglevel = 'debug' errorlog = '-' accesslog = '-' preload = True reload = True workers = 2 My gunicorn command is: gunicorn -c gunicorn_conf.py project.wsgi:application I am expecting it to only show 2 processes when I hit ps aux in the container or docker top but it turns out that it has three like the one below USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND root 1 0.0 0.1 21756 2600 ? Ss 21:48 0:00 /bin/bash /usr/src/app/entrypoint.sh root 6 0.0 1.0 97424 21860 ? S 21:48 0:01 /usr/local/bin/python /usr/local/bin/gunicorn -c gunicorn_conf.py project.wsgi:application root 11 2.7 3.2 310404 65560 ? Sl 21:48 1:20 /usr/local/bin/python /usr/local/bin/gunicorn -c gunicorn_conf.py project.wsgi:application root 12 2.7 3.2 310408 65572 ? Sl 21:48 1:20 /usr/local/bin/python /usr/local/bin/gunicorn -c gunicorn_conf.py project.wsgi:application -
Django: Prevent Data Repetition
This is how my model looks like, class Question(models.Model): .... & another one class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) .... I'm trying the filter out those questions which have answer, I tried the simplest way, i.e. result = Question.objects.order_by('-answer')[:10] As it should it's repeating the question in results if they have more than 1 answer which I don't want. I tried distinct() but it's not working. I just want a question to appear once even if it has multiple answers. How can I prevent the repetition of Questions in results if they have multiple answers? What is the best way of doing it? Please helpme. Thank You :) -
Django join multiple tables
I have the following three models. (I have removed unnecessary fields for clarity) class Product(models.Model): product_id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) class MRFDetails(models.Model): mrf_no = models.AutoField(primary_key=True) customer_id = models.ForeignKey(CustomerDetails) product_id = models.ForeignKey(Product) machine_no = models.CharField(max_length=255) class MRFStatus(models.Model): mrf_no = models.ForeignKey(MRFDetails) worker_id = models.CharField(max_length=255) I want to get the result as it's expected to be given from the following SQL query. Simply to get name form product table for the values I get from MRFStatus. SELECT `SandD_mrfstatus`.`mrf_no_id`, `SandD_mrfdetails`.`mrf_no`, `SandD_mrfdetails`.`product_id_id`, `SandD_product`.`product_id`, `SandD_product`.`name`, `SandD_product`.`end_product_name` FROM `SandD_mrfstatus` INNER JOIN `SandD_mrfdetails` ON ( `SandD_mrfstatus`.`mrf_no_id` = `SandD_mrfdetails`.`mrf_no` ) INNER JOIN `SandD_product` ON ( `SandD_mrfdetails`.`product_id_id` = `SandD_product`.`product_id` ) WHERE `SandD_mrfstatus`.`status` = 0 ORDER BY `SandD_mrfstatus`.`status` ASC, `SandD_mrfstatus`.`modified_datetime` DESC This is what I have tried gg = MRFStatus.objects.all().filter(Q(status__contains=0)).order_by('status','-modified_datetime').select_related() How can I get the values that are there in MRFDetails and Product. print gg.values() gives the values related to MRFStatus table only. -
how to pass language between templates in django admin
I 'm overriding django-admin templates to add a language choice links. I added this: {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <a href="/{{ language.code }}{{ request.get_full_path|slice:'3:' }}" class="{% if language.code == LANGUAGE_CODE %}selected{% endif %}" lang="{{ language.code }}"> {{ language.name_local }} </a> {% endfor %} in both base_site.html and login.html. They work fine The problem is that I always get the default language in the dashboard. For example: If I choose Frensh in the login page, the login page gets translated into frensh but after I login, I find the dashboard and other pages in the default language. How can I fix this, in order to display the dashboard in the language chosen from the login page -
Django - JSON file to DTL and JavaScript
I am trying to read a JSON file and pass its content to my template like this: with open('Directory_To_Json', "r") as data: content = json.load(data) return render(request, 'Displayer/index.html', {'Content': content}) It works, but I also want to be able to work with the same JSON inside of my javascript. I tried it like this: var jsonData = JSON.parse("{{Content}}"); But there is an error at the second position, although the JSON itself is valid. (I tried adding the "safe" modifier as well) I guess it's because I pass it the json.load output, which is formated to work with Python. But how can I pass it the raw json file content? Thanks in Advance -
Python can't read the environment variable with Supervisor
when I run sudo -E supervisor reread/reload I have the command defined in the [program:site] section to launch the gunicorn.conf.py /etc/supervisor/conf.d/weather.conf [program:site] directory=/home/nhcc/campus-weather-station/weather_station command=/home/nhcc/venv/weather_station/bin/gunicorn -c /home/nhcc/campus-weather-station/weather_station/gunicorn.conf.py -p gunicorn.pod weather_station.wsgi gunicorn.conf.py # -*- coding: utf-8 -*- # /usr/bin/python3 import os bind = "{}:8080".format(os.environ['DJANGO_WEATHER_STATION_HOST']) worders = (os.sysconf('SC_NPROCESSORS_ONLN') * 2) + 1 loglevel = 'error' command = "WTR_VENV/gunicorn" pythonpath = "$PROJECT/weather_station" it will showed up the error . I set DJANGO_WEATHER_STATION_HOST in the /etc/profile.d/project.sh project.sh export DJANGO_WEATHER_STATION_HOST=the_host_ip After reloading it but in vain. I also set in the ~/.profile But still got the error. -
GeoDjango Distance object to serializer
I want to get the distance as a return values how can I convert the Distance object to decimal value. My query query = Model.objects.filter(location__distance_lte=(search_location, D(m=distance)) ).annotate(distance=Distance('location', search_location) ).order_by('distance') Serializes class ModelSerializer(serializers.ModelSerializer): distance = serializers.FloatField() class Meta: model = Model fields = ('id', 'name', 'image', 'distance',) I am getting an error float() argument must be a string or a number, not 'Distance' How can I do it. ? -
How To retrieve ArrayField data in django query?
I have a model with an ArrayField as: class Item: static_data = ArrayField( models.CharField(max_length=120), blank=True ) Now I want to retrieve only the First Element of the Array in a select query using django model. Is it possible to do so? If its possible how do I achieve it. -
All creation date of all users which are customers
In a web application, it is possible to create User and CustomerProfile. A user could be an employee and a customer. I could find the creation date with >> cust = CustomerProfile.objects.get(pk=100) >> cust.user.date_joined >> datetime.datetime(2017, 7, 28, 14, 43, 51, 925548) I know I can find all users with User.objects.all(). How could I find all users which are not employees? Be aware that User is the parent class of CustomerProfile. -
Django 1.11 - templates folder in project directory
I'm struggling to get the following working: I would like to have a 'general' templates folder for non-app-specific html in the directory of my project, akin to the static folder for non-app-specific static files. My current structure looks like this: |- my_app/ |- dashboard/ |- static |- dashboard/ |- css/ |- ... |- templates |- dashboard |- index.html |- ... |- urls.py |- views.py |- landing/ |- static |- landing/ |- css/ |- ... |- templates |- landing |- index.html |- ... |- urls.py |- views.py |- my_app/ |- static/ |- my_app/ <-- no problem loading these |- css/ |- ... |- templates |- my_app <-- unable to load these |- boilerplate.html |- settings.py |- ... |- manage.py My current convention is that if the html or static files are in an app directory, they are specific to that app, if they are in the project (here my_app) directory, they are applicable across the whole project. My problem now is that when I try to load boilerplate.html (a snippet) into dashboard/index.html by stating {% include "my_app/boilerplate.html" %} in dashboard/index.html, it complains with: TemplateDoesNotExist at /dashboard My settings.py file, or at least the part I believe to be relevant is the …