Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Install django alongside PHP web with apache
I have successfully install Django with apache. Then, I tried to install adminer for mysql administration which uses php. I have created separated virtual host for both django and adminer. When I access adminer web, it display "DisallowedHost at /" error. I know that error is belong to django. Below is my config for both django and adminer. For django: WSGIScriptAlias / /home/bharata/pythonweb/myfirstdjango/myfirstdjango/wsgi.py WSGIPythonHome /home/bharata/virtualenv/ WSGIPythonPath /home/bharata/pythonweb/myfirstdjango/ <Directory /home/bharata/pythonweb/myfirstdjango/> Options Indexes FollowSymLinks AllowOverride None Require all granted </Directory> <Directory /home/bharata/pythonweb/myfirstdjango/myfirstdjango> Options Indexes FollowSymLinks AllowOverride None Require all granted <Files wsgi.py> Require all granted </Files> </Directory> For adminer: <Directory /home/bharata/website/adminer/> Options Indexes FollowSymLinks AllowOverride None Require all granted </Directory> I have set the config file in sites-available accordingly. For django: <VirtualHost *:80> ServerAdmin email.com ServerName python-web.local.com ServerAlias www.python-web.local.com DocumentRoot /home/bharata/pythonweb/myfirstdjango ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> For adminer: <VirtualHost *:80> ServerAdmin email.com ServerName adminer.local.com ServerAlias www.adminer.local.com DocumentRoot /home/bharata/website/adminer ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> I have set the value for both adminer.local.com and python-web.local.com in the etc/hosts to 127.0.1.1. It seems that apache redirect all request to be handled by wsgi because I set the WSGIScriptAlias to / How can I set apache to distinguish when to use the wsgi and … -
django inserting instead of updating
I've read many questions related to this issue but I haven't found the solution in any of them. In my app, the user logs in and may change some fields in HIS/HER profile. Basically, what I need is to update the user's profile instead of creating a new one. This is my view: @login_required def profile(request, user_id): try: user = User.objects.get(pk=user_id) profile = Profile.objects.get(pk=user_id) ProfileFormset = inlineformset_factory( User, Profile, fields=('nick_name', ), can_delete=False) except: return render_access_denied_message(request) if request.user.is_authenticated() and request.user.id == user.id: if request.method == 'POST': user_form = UserProfileForm(instance=user, data=request.POST) if user_form.is_valid(): profile_formset = ProfileFormset( request.POST, instance=profile) assert False, profile_formset.is_valid() if profile_formset.is_valid(): assert False, user_form # at this point both form are valid current_user = user_form.save() #saves a new user with empty username #assert False, current_user profile_formset.user_id = user_id profile_formset.save() return confirmation_page(request, user_id) return render_access_denied_message(request) else: user_form = UserProfileForm(instance=user) profile_formset = ProfileFormset(instance=user) return render(request, 'users/profile.html', { 'user_id': request.user.id, 'form': user_form, 'formset': profile_formset, }) else: render_access_denied_message(request) and my model is: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField( User, related_name='user', on_delete=models.CASCADE, primary_key=True) nick_name = models.CharField( 'Nick name', max_length=30, blank=True, default='') def __str__(self): return self.user.username def create_profile(sender, **kwargs): user = … -
django template - how to get a dictionary property without using a for loop
Doing this works {% for comment in comments %} {{ comment.user }} {% endfor %} However, I want to get all the comment.user values in the dictionary without using a for loop. Is this possible? I ask because I need to do this check {% if name in comment.user %} # check if name is in any one of the comments # do something {% endif %} -
Django {% if %} statement
I have a form that allows users to upload an image as well as an image url. Depending on which they use the image src on the page should be the uploaded image, or the image from the URL. Here's the form: 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}), } I have two issues to sort out. The first one is, on the page where the image needs to be displayed I have the following: <img class="img-fluid" {% if product.image.url %}src="{{ product.image.url }}" {% else %} src="{{ product.image_url }}" {% endif %} alt="" /> Only the "product.image.url" images show up. I think I'm confusing myself here so am asking for help. The second thing is only allowing users to upload and image OR use an image URL - that next on the list but, for now, I want to work out how to get this issue sorted out. -
Multi-level Categories in Wagtail
I always make sure I have tried every possible avenue before coming on here for advice. That said, here is what I am currently struggling with; creating multi-level/nested categories. As an aside, it will be nice if the wagtail core developers can implement an easy way for multi-level category creation, without us having to write some vanilla-django hack for it. I have been working on this application for a few weeks, everything runs smoothly, except now, there's a business decision for a nested category to be implemented. My initial M.O was to create a ServiceCategoryIndex Page, a ServiceCategoryPage then make the ServiceIndex Page a descendant or orderable to the ServiceCategoryIndex Page as ServiceCategoryPage, Which just doesn't seem right. After a couple of iteration, I went back to my default model, then tried the url of the category using views and url like vanilla-django, the problem with is, I am not able to query the foreign key with a through relationship on the template, so I still can't get the content of the service page as a list queryset rendered out. Here're my model codes below, any suggestion or work around on this will be absolutely helpful. P.S: I am almost … -
bokeh django plot embed: large amount of white space in generated div tag
I have a Bokeh chart embed working well in my Django project but I'm having problems with the embed that it creates. I'm importing both the script and div in my template as {{ div | safe }} and {{ script | safe }} but the div is creating a large white space after itself on my template. Any ideas? Here's an image -
Using user CSS sheet in a template
I'm using Django to display user uploaded static HTML and CSS files. The HTML isn't a problem, however I can't get Django to actually render using the uploaded CSS. Project structure is the following: my_project main_app display_app my_project media user whatever.html whatver.css My main url.py contains: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^html_uploads/', include('display_app.urls')), url(r'^', include('main_app.urls')),] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) display_app urls.py is: urlpatterns = [ url(r'^(?P<requested>(?:[\w]+\/?)+)$', views.readhtml, name='requested'),] The relevant part of the view is: def read_html(request, file_name): title = 'html_file_title' body = get_body(file_name) css_source = 'user/whatever.css' return render(request, "display_app/base.html", {'title': title, 'body': body, 'css_source': css_source, 'media_url': settings.MEDIA_URL,} ) The CSS simply contains: body { background-color: #FFCC66 } And the template looks like: <head> <title>{{ title }}</title> <link rel="stylesheet" href="{{ media_url }}{{ css_source }}" type="text/css" /> </head> <body> {% autoescape off %} {{ body }} {% endautoescape %} </body> With this, I get a 404 as Django fails to find /media/user/whatever.css. If I change the CSS location to: <link rel="stylesheet" href="/{{ media_url }}{{ css_source }}" type="text/css" /> The 404 warning disappears, the HTML still loads, however the CSS is silently ignored. The HTML is passed through several functions and heavily modified, therefore passing it as a string made sense, however the … -
Django user model extension in an ecommerce application
I have a django ecommerce project that works fine till I decided to improve it. I let users place order on certain services but every time they place an order they have to always input their details (name, emil, address etc) so I decided to upgrade the application to use user registration and extended the user registration so that a user can update their user account with email and address and phone number etc. The initial codes for placing an order is shown below Model class Order(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField() address = models.CharField(max_length=250) postal_code = models.CharField(max_length=20) city = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) paid = models.BooleanField(default=False) class OrderItem(models.Model): order = models.ForeignKey(Order, related_name='items') product = models.ForeignKey(Product,related_name='order_items') price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.PositiveIntegerField(default=1) view def order_create(request): cart = Cart(request) if request.method == 'POST': form = OrderCreateForm(request.POST) if form.is_valid(): order = form.save() for item in cart: OrderItem.objects.create(order=order, product=item['product'],price=item['price'], quantity=item['quantity']) cart.clear() return render(request,'order/created.html', {'order': order}) else: form = OrderCreateForm() return render(request, 'order/create.html',{'cart': cart, 'form': form}) I then created an account app and extended django user so that user can register address and mobile so that the user does not have to type it every time … -
ModelChoiceField gives “Select a valid choice” populating select with ajax call
I've tried all possible solutions on several threads and I'm still unable to fix the problem. I have the following code: models.py class CustomerVisit(models.Model): start_date = models.DateField() end_date = models.DateField() customer = models.ForeignKey(Customer) address = models.ForeignKey(Address) forms.py address = forms.ModelChoiceField(label='Address', queryset=Address.objects.none(), widget=forms.Select(attrs={'style': 'width: 100%;'})) customer = forms.ModelChoiceField(label='Customer', queryset=Customer.objects.all(), widget=forms.Select(attrs={'style': 'width: 100%;'})) views.py if request.method == "POST": # Cleaning fields post = request.POST.copy() post['address'] = Address.objects.get(id=post['address']) post['start_date'] = dateparser.parse(post['start_date']) post['end_date'] = dateparser.parse(post['end_date']) # Updating request.POST request.POST = post form = CustomerVisitForm(request.POST) if form.is_valid(): form.save(commit=True) return redirect("customervisit:calendar") My address select its being populated based on customer selection using ajax call using select2. After reading several threads I noticed that modelchoicefield expects a Address object so that's why I'm using the following code on my view before the form is being validated: post['address'] = Address.objects.get(id=post['address']) but I'm still getting the Select a valid choice. That choice is not one of the available choices. error I'm using queryset=Address.objects.none(), because I need an empty select -
Django - Modifying database record before displaying to user
I have a MultipleChoiceField forms field (associated with a models CharField) which shows up in the database like this. It seems to have been converted to a string in the database, because when I try to display it with a 'for property in property_type' statement in the HTML, it shows up like this. I want it to be displayed like this So I have to write some code to fix this issue. My pseudocode will look something like: for record in property_type: split record at comma for i in record: if record[i] is not a letter or number: remove record[i] Now my question is, where do I write this code? Do I write it in the views.py or in the HTML file? I tried doing it in views but I don't know how to select a single database record. I tried doing it in the HTML but I was limited by the template tags. Here is the shortened version of my code: models.py: property_type = models.CharField(max_length=50, help_text="You can select more than 1 option") forms.py: property_type = forms.MultipleChoiceField(widget=forms.SelectMultiple, choices=BuyerListing.PROPERTY_TYPE) HTML: {% for property in listing.property_type %} <p>Property type: {{ property }}</p> {% endfor %} -
Conditional in django model field declaration
I have a model called Image, which I use to store both paintings and photos. In this model, I have an Artist field, which stores the name of the creator. For reasons uninportant to the question, Artist can be blank if the Image instance is a photo, but it can not be blank if the Image instance is a painting. As such, I would want something like such: Class Image() isPainting = models.BooleanField(default=0) # set too 1 for paintings artist = models.CharField( max_length=127, if isPainting: blank=False else: blank=True ) Is such a conditional possible? -
How can I map objects in Django?
Let's assume that I have in my POST method three fields - field1, field2, field3 however in POST method field2 and field3 should have the same value during adding to the database. So there is no need to add for instance field2=2, field3=2 manually. I could add only field1=1, field2=2 and then field3=2 will be added to this body automatically and finally whole 3 fields will be added to the database. I wonder how it should be done in most optimal way? Should it be done in view? class UserObject(GenericAPIView): def post(self, request, user_id): serializer = ObjectSerializer(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) -
Sphinx doc generator throw warning missing app_label
I am trying to generate Sphinx documentation to my Django app. Sphinx 1.6.4 Django 1.11.5 I am using custom setting which are placed in setting folder and loading correct settings with OS ENV. When I try to generate documentation with make html, it throws back this warning: WARNING: /home/stanliek/Documents/dev/timak/backend/docs/modules/users.rst:6: (WARNING/2) autodoc: failed to import module 'users.models'; the following exception was raised: Traceback (most recent call last): File "/home/stanliek/Documents/dev/timak/backend/env/lib/python3.5/site-packages/sphinx/ext/autodoc.py", line 658, in import_object __import__(self.modname) File "/home/stanliek/Documents/dev/timak/backend/docs/../users/models.py", line 2, in <module> from django.contrib.auth.models import User File "/home/stanliek/Documents/dev/timak/backend/env/lib/python3.5/site-packages/django/contrib/auth/models.py", line 6, in <module> from django.contrib.contenttypes.models import ContentType File "/home/stanliek/Documents/dev/timak/backend/env/lib/python3.5/site-packages/django/contrib/contenttypes/models.py", line 139, in <module> class ContentType(models.Model): File "/home/stanliek/Documents/dev/timak/backend/env/lib/python3.5/site-packages/django/db/models/base.py", line 118, in __new__ "INSTALLED_APPS." % (module, name) RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. This warning causes that the users.models are not in the documentation. Before I run make html, I export OS ENV export DJANGO_SETTINGS_MODULE=settings.development and then run it. My settings settings.development includes base.py which contains this INSTALLED_APPS: INSTALLED_APPS = [ # Default Django Apps 'django.contrib.contenttypes', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', # Our Apps 'settings', 'backend', 'places', 'users', # Custom modules 'raven.contrib.django.raven_compat', 'corsheaders', 'allauth', 'allauth.account', 'rest_framework', 'rest_auth', 'rest_auth.registration', ] This looks like that contenttypes is … -
Django DeleteView select Database to use
I'll delete an object from my second unmanaged database (pgsql). view.py class DeleteDomain(DeleteView): model = Domains template_name = 'domain/delete_domain.html' @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(DeleteDomain, self).dispatch(*args, **kwargs) def get_object(self, *args, **kwargs): obj = super(DeleteDomain, self).get_object(*args, **kwargs) if obj.created_by != self.request.user: raise Http404 return obj def get_success_url(self): return reverse('overview') def get_context_data(self, **kwargs): context = super(DeleteDomain, self).get_context_data(**kwargs) context['nav_overview'] = True return context settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'pgsql': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': 'localhost', 'PORT': '5432', 'PASSWORD': 'xxxxx', 'USER': 'vmailuser', 'NAME': 'virtualmail', 'OPTIONS': { 'options': '-c search_path=public' }, } } models.py: # -*- coding: utf-8 -*- from django.db import models from django.utils.translation import ugettext_lazy as _ from django.core.validators import RegexValidator class Domains(models.Model): id = models.AutoField(primary_key=True, unique=True) domain = ( models.CharField(max_length=255, blank=False, null=True, validators=[RegexValidator( regex=r"([a-zA-Z0-9-_]+\.)+[a-zA-Z0-9-_] {2,}", message=_("Invalid domain name") )], help_text=_('Please enter the email Domain here') ) ) created_by = ( models.CharField(max_length=255) ) class Meta: managed = False db_table = 'domains' def __unicode__(self): return self.domain urls.py: # -- coding: utf-8 -- from django.conf.urls import url from .views import AddDomainView, DeleteDomain urlpatterns = [ url(r'add', AddDomainView.as_view(), name='add_domain'), url(r'(?P<pk>\d+)/delete/$', DeleteDomain.as_view(), name='delete_domain'), If I try to access https://localhost:8080/1/delete I get: Exception Value: no such table: domains And in my … -
Can't get value from form's input field in django-ajax
On my html file I dynamically add forms, but I can't extract the value of the input field with id='recipient'. When I print it, it returns an empty string! file.html <script> {% for article in article_list %} $('#somediv').append( "<div class='form-group'>"+ "<form action='' class='popup' id='send_form{{ article.pk }}' method='POST'>{% csrf_token %}"+ . "<input type='text' class='form-control' id='recipient' placeholder='Enter a username'>"+ "<input class='btn btn-primary' type='submit' value='Send'/>"+ "</form>"+ ) {% endfor %} $(document).on('submit','#send_form{{ article.pk }}', function(e) { e.preventDefault(); console.log('print input content: ', $("#recipient").val(),) $.ajax({ type: 'POST', url: '{% url "userprofile:send_form" %}', data: { recipient: $("#recipient").val(), journal: '{{ journal.pk }}', section: '{{ section.pk }}', article: '{{ article.pk }}', csrfmiddlewaretoken: '{{ csrf_token }}' }, success: function showAlertLike() { $("#success_send").show().delay(2000).fadeOut(); } }); }); </script> Views.py class SendView(generic.FormView): """ A view that creates a LikedArticles object when a user clicks on the like badge under each article displayed. """ def post(self, request): print('#####################################') if request.method == 'POST': sender = request.user recipient_name = request.POST.get('recipient') journal_pk = request.POST.get('journal') section_pk = request.POST.get('section') article_pk = request.POST.get('article') print('content: ', recipient_name, journal_pk, article_pk, sender) What is printed on my terminal: "##################################### ('content: ', u'', u'1', u'2249', SimpleLazyObject: function lambda> at 0x106c3ce60>>) -
Django sessions and number of users
i have a python chatbot chatting application on a Django website where each uses has it own session when he/ she starts chatting with the chat bot.Also i'm using Mysql DB as a back end my question is how many number of users or sessions can the application handles at the same time? -
Django deploy troubles
I use Ubuntu server 16.04, Nginx, Gunicorn and supervisor. I can't access my website on production. Here is my site.conf (supervisor) : [program:sitepro] command = /home/user/sitepro/bin/gunicorn sitepro.wsgi:application -w 4 -b www.mywebsite.fr:8002 --reload directory = /home/chuck/sitepro/site/ user = chuck stdout_logfile = /home/user/sitepro/site/logs/gunicorn/gunicorn_stdout.log stderr_logfile = /home/user/sitepro/site/logs/gunicorn/gunicorn_stderr.log redirect_stderr = True environment = PRODUCTION=1 My nginx conf file : server { listen 443 ssl; server_name mywebsite.fr; root /home/user/sitepro/site; access_log /home/user/sitepro/site/logs/nginx/access.log; error_log /home/user/sitepro/site/logs/nginx/error.log; location / { proxy_set_header X-Forward-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://127.0.0.1:8002; break; } } } And my settings.py [...] ALLOWED_HOSTS = [u'IPOFTHESERVER', u'www.mywebsite.fr'] [...] I get a "ERR_CONNECTION_REFUSED" on my domain name. If I execute the command on my user repository I get : ~/sitepro/site$ gunicorn sitepro.wsgi:application -w 4 -b www.mywebsite.fr:8002 --reload [2017-10-28 16:27:31 +0000] [17953] [INFO] Listening at: http://[myip] (17953) Invalid HTTP_HOST header: 'MYIP:8002'. You may need to add u'MYIP' to ALLOWED_HOSTS. I opened the 8002 port on ufw. It listen my IP so I think this is link to my trouble. Could you help please ? :) Thanks ! -
python, django : python-decouple occur not found error
I'm using django and need to decouple setting data from souce code. so tried python-decouple module. when using setting.ini file, I located it next to setting.py(same directory) when using setting.env, located setting.py's parent derictory. both occur error like this. SECREAT_KEY not found. Declare it as envvar or define a default value. setting.ini file [settings] SECRET_KEY=1234 setting.env file SECRET_KEY=1234 source code from decouple import config SECRET_KEY = config('SECRET_KEY') I already installed python-decouple pip install python-decouple please help me os = window -
DeleteView not deleting instance
My app has a combined update/delete page. When I click on the delete button for a specific instance, I'm taken to the success_url specified in the DeleteView function, but nothing happens to the instance I'm trying to delete. Is there some additional step I need to take to specify the desired object to delete, because I'm combining views into one template? Views: class RecipientUpdate(UpdateView): model = models.Recipient fields = ['first_name', 'last_name', 'birthday', 'notes'] template_name_suffix = '_update_form' def get_success_url(self): return reverse('shopping_list') class RecipientDelete(DeleteView): model = models.Recipient template_name = ('recipient_update_form') success_url = reverse_lazy('shopping_list') Urls: urlpatterns = [ url(r'^shoppinglist/', views.shopping_list, name='shopping_list'), url(r'^recipient_update/(?P<pk>\d+)/$', views.\ RecipientUpdate.as_view(), name='recipient_update_form'), ] Template: {% block content %} <h3>Edit or Delete Recipient info:</h3> <form action='' method="POST">{% csrf_token %} {{ form.as_p }} <input type="Submit" value="Update"> <br> <p>Or you can click here to delete this record altogether. Are you sure you want to delete "{{ object }}"?</p> <input type="Submit" value="Delete"> </form> {% endblock %} -
How to test django logout using client.post()?
I want to test if my user is logged out correctly. I can log in. I tried to logou the same way, but, the test fails. I can't figure out why. Why this test fails? def test_user_can_login_and_logout(self): response = self.client.post('/login/', {'username': 'login', 'password': 'pass'}) user = auth.get_user(self.client) self.assertEqual(user.is_authenticated(), True) # This works fine self.client.post('/logout/') self.assertEqual(user.is_authenticated(), False) # This fails. My urls.py from django.conf.urls import url from django.contrib.auth import views as auth_views urlpatterns = [ (...) url(r'^login/$', auth_views.login, {'template_name': 'home/login.html'}, name='login'), url(r'^logout/$', auth_views.logout, name='logout'), (...) ] In question I skipped the code responsible for creating test user in database. -
Django server response with 4xx response code sometimes
Background Information : I have developed server in django python and deployed on AWS Elastic Beanstalk by using ELB. Server content many API named like as /testapi, /xyz, etc. Problem Facing : Sometime it gave me 4xx or 200 when i called /testapi. Attaching logs of AWS EC2 instant which show some of request are failed with 4xx response code and some are ok i.e 200. Please guide me on the right path so I can solve it. ------------------Start Of Logs ------------------- 172.31.16.19 - - [28/Oct/2017:12:01:59 +0000] "POST /testapi/ HTTP/1.1" 404 218 "http://192.168.0.167/" "MozillaXYZ/1.0" 172.31.2.71 - - [28/Oct/2017:12:02:01 +0000] "POST /testapi/ HTTP/1.1" 404 218 "http://192.168.0.167/" "MozillaXYZ/1.0" 172.31.2.71 - - [28/Oct/2017:12:02:09 +0000] "POST /testapi/ HTTP/1.1" 404 218 "http://192.168.0.167/" "MozillaXYZ/1.0" 127.0.0.1 (-) - - [28/Oct/2017:12:02:22 +0000] "GET / HTTP/1.1" 200 54 "-" "Python-urllib/2.7" 172.31.2.71 (35.154.225.66) - - [28/Oct/2017:12:02:44 +0000] "PUT /xyz/ HTTP/1.1" 200 872 "http://192.168.0.167/" "MozillaXYZ/1.0" 172.31.16.19 (35.154.225.66) - - [28/Oct/2017:12:02:54 +0000] "PUT /xyz/ HTTP/1.1" 200 834 "http://192.168.0.167/" "MozillaXYZ/1.0" 172.31.2.71 (35.154.225.66) - - [28/Oct/2017:12:03:23 +0000] "POST /testapi/ HTTP/1.1" 200 866 "http://192.168.0.167/" "MozillaXYZ/1.0" 172.31.16.19 (35.154.225.66) - - [28/Oct/2017:12:03:25 +0000] "PUT /xyz/ HTTP/1.1" 200 857 "http://192.168.0.167/" "MozillaXYZ/1.0" ::1 (-) - - [28/Oct/2017:12:03:33 +0000] "OPTIONS * HTTP/1.0" 200 - "-" "Apache/2.4.25 (Amazon) mod_wsgi/3.5 Python/3.4.3 (internal … -
Django - data too large for session
I have a view in which I query the database then I give the queryset to session and use it in other views. It works fine most of the time but in vary rare cases when the queryset gets very large, it takes a long time and I get a timeout. What I would like to know is if I am doing the right thing? if not, what is the best practice for this case? what options do I have? -
Django Get name of current view as a string
Is it possible to get the name of Django view in string form? I have searched a lot but could not find the answer. -
django rest framework desing api
I have a model something like this: a "Post" has many "Comments" and the comments has a "Profile" and the profile has "Items", Post and Submissions are in a postgres datastore and profile and items are in elasticsearch datastore. in the /views.py file i have two apis something like this: from docs import ProfileDocType from models import Posts @api_view(['GET']) def posts_list(): "code" @api_view(['GET']) def profiles_list(): "code" if i want to use information from profiles in the posts_list api, ¿¿what is the better desing aproach ?? Accesing with the ProfileDocType ?? or using the profiles_list api in the code of post_lists api (it can be done in that way? thinkin in extensible code? -
retain all data when editing using a formset
Suppose I have a model FooBar containing two fields Foo and Bar. Then if I use a modelform to edit just the Foo field for existing records, I can retain the Bar data by using instance, i.e. foobar = FooBar.objects.get(...) foobar_form = FooBarForm(request.post, instance=foobar) What is the equivalent of this for formsets? So far I have tried Instance, which Django tells me doesn't exist for formsets, and initial, which I use to populate the formset in the GET request, foobar = FooBar.objects.filter(...) foobar_formset = FooBarFormSet(request.post, initial = foobar.values()) Excluding the initial argument makes has_changed() always return True, while including the initial argument makes has_changed() reflect the actual state of the form POST data. This suggests to me that the bar field data is picked up somewhere, yet when I iterate over foobar_formset and do for foobar_form in foobar_formset: foobar_form.save() I get an error from the debugger saying null value in column "Bar" violates not-null constraint. DETAIL: Failing row contains ('foo_value', null).