Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What are processes?
I am a french Django programmer and I wanted to see what options I had to host my servers. When I went to Django Europe's pricing, there was a limit of processes you can do per month. What are these? Is 50 a lot? Is it a scam? Please help me or tell me a french definition because I don't understand what they mean by process. 10GB SSD Starter Plan €5/month 10GB SSD Storage 0.5GB RAM 50 Processes 1 SSH User -
Django Nginx is not serving wagtail admin css/js files
I set up my django wagtail on a ubuntu server with a domain using NGINX and Gunicorn. My CSS and JS files located in the static folder in my directory are being served correctly, but I can't figure out why the Wagtail Admin CSS/JS files are not being served. I'm assuming it has something to do with the fact that the Wagtail admin files are not located in my static folder with my CSS/JS files. I ran CollectStatic and set Debug=False. Google chrome is reporting a 404 files not found on the admin CSS/JS Part of NGINX File server { listen 443 default_server; listen [::]:443 default_server; root /home/projects/stemletics/stemletics/mysite/mysite; index index.html index.htm; # Make site accessible from http://localhost/ server_name domain.com www.domain.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/projects/stemletics/stemletics/mysite/mysite; } location / { include proxy_params; proxy_pass http://unix:/home/projects/stemletics/stemletics/mysite/mysite.sock; } -
Django2.1- error- everything was working fine but it started giving {% ur 'name' %}l error
enter image description here everything was working fine but it started giving {% ur 'name' %}l error, when i delete this works fine!Using to django-2.1, jinja2, python-3.6 -
Error saving custom model admin on Django
At first I'd would say this is my first time here and I also want for my English. I hope explain myself. Well, I'm developing a web with Django 2.0 and I have a curious (and annoying) problem wich didn't exist at development environment. I'm on myweb.com/admin, saving data and it has a ImageField and when I'm saving Django tells me: Page not found (404) Request Method: POST Request URL: http://www.myweb.com/admin/about/about/add/ Raised by: django.contrib.admin.options.add_view Using the URLconf defined in myweb.urls, Django tried these URL patterns, in this order: busqueda/ contacto/ sobre-mi/ admin/ [name='home'] <slug:categoria>/ [name='category'] <slug:category>/<slug:slug>/ [name='post'] ^media\/(?P<path>.*)$ The current path, about/about/add/, didn't match any of these. I've mentioned about ImageField because I had no problems with two models without this Field. This is myproject/urls.py: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('busqueda/', include('search.urls')), path('contacto/', include('contact.urls')), path('sobre-mi/', include('about.urls')), path('admin/', admin.site.urls), path('', include('post.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) And about/urls.py: from django.urls import path from .views import AboutView app_name = 'about' urlpatterns = [ path('', AboutView.as_view(), name='about-me'), ] Thanks mates. I suppose it's an stupid question, but I'm not able to resolve it myself. -
Cloned Django app on Ubuntu with Nginx and uwsgi
So recently I just cloned my instance in order to add it to a load balancer. Everything is set up fine but I can't help thinking that I am missing something. It has been a while and my friend set up my first server. Is there somewhere that I must add the new Public Ip of my Clone server? Perhaps the Allowed Host in settings.py? Heres exactly what I have done: Clone the server Git pull Add to loadbalancer Am I missing a step somewhere that I add the new IP? Sometimes I get a Django Invalid External IP message. Im guessing it's when clone server tries to make requests. -
Where can I download demo project for django (for html template)
I just started to develop with django, I'm searching one demo project that I can modify for my purpose (registration, login, profile). It's a simple project. But I'm googling for a nice template and not only white background with black text. Does it exist one site where can I browse from many theme/app for django? Thanks -
DateFromToRangeFilter don't filter anything
I have a very simple example using DateFromToRangeFilter in python but nothing happens when i try to filter, simple don't work. This is my model: class Caixa(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) data = models.DateField('Data') total = models.DecimalField('Total', decimal_places=2, max_digits=10, null=True) unidade = models.ForeignKey(Unidade, on_delete=models.CASCADE) def __str__(self): return "Caixa " + self.unidade.nome This is my filter: class CaixaFilter(django_filters.FilterSet): data = django_filters.DateFromToRangeFilter() class Meta: model = Caixa fields = ['data'] This is my view: def caixa_list(request): id_unidade = request.session['id_unidade'] unidade = Unidade.objects.filter(id=id_unidade).get() caixas_filter = CaixaFilter(request.GET, queryset=Caixa.objects.filter(unidade=unidade).order_by('data')) context = { 'unidade': unidade, 'filter': caixas_filter } return render(request, 'caixas.html', context=context) so, in my HTML i have the following: <form method="get"> <div class="row"> <div class="col s12"> {% render_field filter.form.data class="datepicker" %} </div> </div> <button type="submit" class="btn btn-primary"> <span class="glyphicon glyphicon-search"></span> Buscar </button> </form> {% for caixa in filter.qs %} <tr> <td>{{ caixa.data }}</td> <td>{{ caixa.total }}</td> <td><a class="btn-floating btn-xs waves-effect waves-light green"><i class="material-icons">forward</i></a> </td> </tr> {% endfor %} So, as i said when i clicked in "Search" button nothing happens, my filter don't work. I noted that my date format is : "13, Aug, 2018", so if i change to "2018-08-13" it works, but i want to use this format in HTML and convert … -
How to add multiple form field types of choices for a question in django?
I'm creating a "Polls" like application. In this application there will be questions and every question will have single or multiple answers choices. The answer choice can be Text, Image, or Video. I have made one model called Question and different models for different choice types: class Question(models.Model): question_text = models.TextField() category = models.ForeignKey(QuestionCategory) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class ChoiceText(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice = models.CharField(max_length=255) class ChoiceImage(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice = models.ImageField() Is this a good way to design the models, or is there a better way to solve this problem ? It doesn't look so intuitive in the admin side too, any suggestions on the admin side ? I looked at https://docs.djangoproject.com/en/2.1/intro/tutorial07/ but I'm still confused about combining the different choices into a better user-friendly way. -
model.objects.raw(SELECT * FROM table) convert result to u'%s'
When I use Model.objects.filter() I just specify in my model def __unicode__(self): return u'%s' % (self.field) But how can I get the same result using model.objects.raw(SELECT * FROM table)? -
Unable to load Django YAML fixture file
I have a Django project that contains a "list" application. I'm trying to load some user data into the auth_user table using a YAML fixture file. Each time I run the command, it doesn't display any errors but it also says "Installed 0 objects". Here's the file: - model: list.auth_user pk: 1 fields: is_superuser: false username: user1 is_staff: false is_active: true date_joined: 2018-07-06 pk: 2 fields: is_superuser: false username: user2 is_staff: false is_active: true date_joined: 2018-07-06 The file is located in ~/project/list/fixtures/testusers.yml and I'm running this command: python manage.py loaddata testusers I've tried it by giving model the arguments "list.auth_user" and "auth_user" but neither works. The Django fixture doc doesn't say that any file extension is required when specifying the fixture file. What am I doing wrong? -
DRF - Sending extra data to browsable api
Sorry for my poor language usage. I am using drf for my web api. It has special renderers. I can use django views, or drf pure APIView. I can use TemplateHTMLRenderer which is good but all of them make drf not necessary. Because i want to use drf browsable api features. Using post, put, delete forms. Using json and html in api, less and clean code. But the problem is, i cant customize browsable api, i cant send extra content or context. For example; i am using serializer for my Post model but also i need another query serializer too. Which they are not related actualy. Too much talk. My question is; i want to customize browsable api with his features and with more extra data. But i could not see any documant for it. Thanks. -
Integrating MS Power BI w/ Python / Django
I am writing a Django multi-tenant web application which is supposed to use Power BI Embedded as a reporting frontend (basically to render data from the local DB). For this, I am using the 'App Owns Data' scenario and created an application in Azure which I can authenticate against Active Directory to retrieve an access token. However, all the code samples I found are 1) not in Python or 2) they don't work. I am wondering if anyone successfully used ADAL or the Azure libraries to connect and then the Power BI libraries to render a report? Thanks! -
ProgrammingError at /admin/login/ permission denied for relation django_session
I have django rest fromework running on Heroku with Postgres When I try to Login from admin panel with superuser I got this error: ProgrammingError at /admin/login/ permission denied for relation django_session Request Method: POST Request URL: https://myappckrths.herokuapp.com/admin/login/?next=/admin/ Django Version: 1.11.10 Exception Type: ProgrammingError Exception Value: permission denied for relation django_session Exception Location: /app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py in execute, line 64 Python Executable: /app/.heroku/python/bin/python Python Version: 3.6.5 Python Path: ['/app', '/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python36.zip', '/app/.heroku/python/lib/python3.6', '/app/.heroku/python/lib/python3.6/lib-dynload', '/app/.heroku/python/lib/python3.6/site-packages'] Server time: Thu, 13 Sep 2018 21:51:17 +0000 -
How do you add title and meta description on a DjangoCMS template?
i'm working with djangoCMS and i have created all the templates and they are working fine, now my issue is on the djangoCMS page creation fields i fill a couple of fields, the page name, slug, menu title and page title. How do i add and display meta descriptions on my pages? -
Urls Unable To Be Found After Moving Django App To Another Machine
So I've built a Django app on my local machine that works perfectly. Using Bitvise, I've copied the files over to a server, and tried to run the server from there. Everything appears to run fine, I can access the admin page, however, I cannot get to the home page. When I attempt to visit any of the urls I've added, in the listed urls attempted, the only one listed is "^admin". The following is my urls.py for the main app: from django.conf.urls import url, include from django.urls import path from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), path('home/', include('Home.urls', namespace='Home')), path('billing/', include('billing.urls', namespace='billing')), path('createquote/', include('createquote.urls', namespace='createquote')), path('accounts/', include('django.contrib.auth.urls')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root = settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) The following are the installed apps on my settings.py: INSTALLED_APPS = [ 'Home', 'billing', 'createquote', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] And my ROOT_URLCONF: ROOT_URLCONF = 'LNQuoteTool.urls' Is there anything that appears blatantly wrong? How might I solve this? -
Django - Validate password with AUTH_PASSWORD_VALIDATORS
I have a custom User model that only contains two mandatory fields: email and password. I also have a custom UserCreationForm that prompts users for their email and one password. Unfortunately, the form doesn't validate the password, aside from min_length. How do I enable the password validators in settings.AUTH_PASSWORD_VALIDATORS? The object is a list of distc, not Validators, so I'm not sure how to use them. class UserCreationForm(forms.ModelForm): password1 = forms.CharField( widget=forms.PasswordInput(attrs=form_attrs.password), min_length=8, strip=True, ) class Meta: model = User fields = ('email',) widgets = { 'email': forms.EmailInput(attrs=form_attrs.email), } def save(self, commit=True): user = super().save(commit=False) user.set_password(self.cleaned_data.get('password1')) if commit: user.save() return user -
Filter django-geojson to return data based on slug
I am trying to add a postgis geometry as a Geojson to a django template. At the moment I am using django-geojson. I want there to be a page for each one of my Countries model slugs. On that page I want to return (or have available) the geojson from the PostGis geometry. With my URL.py as seen below it loads all of the database entries as geojson on every page. I want it to just load the geojson for the relevant page. from django.conf.urls import url from django.contrib import admin from Countries_App import views from Countries_App.models import Countries from djgeojson.views import GeoJSONLayerView urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^country/(?P<country_slug>[\w\-]+)/$',GeoJSONLayerView.as_view(model=Countries), name='data'), -
Break point not getting hit
I have a class called ProviderConfig that inherits from ConfigurationModel (class ProviderConfig(ConfigurationModel). The ConfigurationModel is defined into a module called config_models.models (from config_models.models import ConfigurationModel) The ConfigurationModel is defined as an 'Abstract base class': class ConfigurationModel(models.Model): class Meta(object): abstract = True ... enabled = models.BooleanField(default=False, verbose_name=_("Enabled")) ... The config_models exists as dependency 'loaded' with pip into a venv. Now, whenever I try to debug my code with pudb and I try to put a breakpoint into the class ConfigurationModel, this breakpoint never gets hit... Furthermore, stepping into the code calling does not load any code but simply returns the result... The breakpoint is added by loading the module config_model.models (by typing m) in pudb and adding the breakpoint. How comes the breakpoint never gets hit? Could it be: The debugger does not stop because the code references a module that is a dependency (installed via pip)? The ConfigurationModel class is an abstract class? pudb does not display the correct site-packages/config_models/models.py(hence the fact that I never hit the breakpoint)? How can I ultimately debug how the enabled gets calculated? and to which field in the DB is relates to? -
Django Query ForeignKeys to return a list "grouped by"
Something is tricking my mind here. My mission is to get a list of Categories vs Brands, querying over Products models. Say we got something like this: class Category(models.Model): name = models.CharField(max_length=100) #examples: TVs, Monitors, HomeTheaters, Fridges class Brand(models.Model): name = models.CharField(max_length=100) #examples: Sony, LG, Apple class Product(models.Model): name = models.CharField(db_index=True, max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) What I am looking for is a query that could return me something like this: {TVs: [Sony, LG, Apple], Monitors:[Sony, Apple] } Of course it could return a queryset that I could transform into a dict later. Since I couldn't get this done in a clean way, I did this: categories = Category.objects.all() products = Product.objects.select_related('category', 'brand').all() categories_brands = {} for category in categories: categories_brands[category.name] = [] for product in products: if product.brand.name not in categories_brands[product.category.name]: category_brands[product.category.name].append(product.brand.name) It does work. But feels silly iterating like that. I tried "annotate" and "regroup" solutions in templatetags, but I couldn't make it work. In addition to this question... would you have one Model class for all the products or best would be have Fridge class, TV's class and so on. I am using tags to add content like volume of a fridge and … -
it does not save updated value to database table ajax
===html=== one project has many expenses, and my dropdown display all expenses of that project. It will also allow user to select different value from dropdown list and then hit update button. it does not give any error however it does not save selected value from dropdown list to database. any help will be deeply appreciated. <select id="select_dropdown"> {% if project.id and emp.id %} {% for expense in emp.expense_set.all %} {% if expense.city %} <option value="{{expense.id}}" selected="selected">{{expense.expense_type}}</option> {% else %} <option value="{{expense.id}}">{{expense.expense_type}}</option> {% endif %} {% endfor %} {% endif %} </select> ====js======= $("#save_change").click(function(e) { e.preventDefault(); console.log("update fucntion is working!"); var value = $("#select_dropdown").find(":selected").val(); var text = $("#select_dropdown option:selected").text(); var project_id = $("#project_id").val(); var emp_id = $("#emp_id").val(); console.log(emp_id); $.ajax({ url: "{% url 'update_form' %}", //url: "/ajax/update_form/", method: "POST", data: { "value": value, "text": text, "project_id": project_id, "emp_id": emp_id, csrfmiddlewaretoken: '{{ csrf_token }}', }, dataType: "json", success: function(data){ console.log("success"); console.log(data); }, error: function(error_data){ console.log("error") console.log(error_data) } }); return false; ===views.py=== @csrf_exempt def update_form(request): if request.method == "POST" and request.is_ajax(): expense_id = request.POST.get('value') expense_type = request.POST.get('text') project_id = request.POST.get('project_id') emp_id = request.POST.get('emp_id') project_id = request.POST.get('project_id') for exp in expense: exp.expense_type = expense_type exp.save() data = serializers.serialize("json", expense) return HttpResponse(data, content_type="application/json") -
Python Django url reverse in unittest returns a 404
url: path('some/path_to/<int:special_id>/', some_views.someAPI.as_view(), name="someAPI") Normally when accessing the API with https://some_domain/some/path_to/1, I can get the data with special_id=1. No issue here. However, when I run a test which contains the reverse() function, the special_id doesn't seem to be loaded. I'm doing url = reverse('someAPI', kwargs={'special_id': 1}) request = self.factory.get(url) force_authenticate(request, user=self.user) response = someAPI.as_view()(request, special_id=1) it gave me a 404: Not found when I expect a 200 I checked the path, and it seems to be correct. I'm wondering why I'm receiving a 404. This is running through django unittest. -
Django - WSGIRequest' object has no attribute 'Get'
So I have 2 scenerios in which one works and one doesnt. I set up a select box in the html template with some hard coded options which you can see in Scenrio2. Im curious to know why Scenario2 works with no problems and Scenario1 throws this error. I have also attached the stack trace below. Scenario1(Doesnt Work): current_status = 'All' status_list = [] all_status = RequisitionStatus.objects.all() for status in all_status: status_list.append(status.status) if request.Get.get('Filter') in status_list: user_req_lines_incomplete = RequisitionLine.objects.filter(Q(parent_req__username=request.user) & Q(status__status=request.Get.get('Filter'))) current_status = request.Get.get('Filter') else: user_req_lines_incomplete = RequisitionLine.objects.filter(parent_req__username=request.user).exclude(status__status='Completed') Scenario 2(works): if request.GET.get('Filter') == 'Created': user_req_lines_incomplete = RequisitionLine.objects.filter(Q(parent_req__username=request.user) & Q(status__status='Created')) current_status = 'Created' elif request.GET.get('Filter') == 'For Assistance': user_req_lines_incomplete = RequisitionLine.objects.filter(Q(parent_req__username=request.user) & Q(status__status='For Assistance')) current_status = 'For Assistance' elif request.GET.get('Filter') == 'Assistance Complete': user_req_lines_incomplete = RequisitionLine.objects.filter(Q(parent_req__username=request.user) & Q(status__status='Assistance Complete')) current_status = 'Assistance Complete' elif request.GET.get('Filter') == 'Assistance Rejected': user_req_lines_incomplete = RequisitionLine.objects.filter(Q(parent_req__username=request.user) & Q(status__status='Assistance Rejected')) current_status = 'Assistance Rejected' else: user_req_lines_incomplete = RequisitionLine.objects.filter(parent_req__username=request.user).exclude(status__status='Completed') StackTrace: Traceback: File "C:\Users\Kevin.Pardo\Documents\Python\venv\env\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\Kevin.Pardo\Documents\Python\venv\env\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "C:\Users\Kevin.Pardo\Documents\Python\venv\env\lib\site-packages\django\core\handlers\base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Kevin.Pardo\Documents\Python\venv\env\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view 21. return view_func(request, *args, **kwargs) File "C:\Users\Kevin.Pardo\Documents\Python\django\lambda\req\views.py" in pending_action 241. if request.Get.get('Filter') in status_list: Exception Type: … -
How to create a submenu in django with(parent and children)?
I try to create menu with submenu hierarchy. My models.py class Category(MPTTModel): name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', on_delete=models.CASCADE,db_index=True) slug = models.SlugField() class MPTTMeta: order_insertion_by = ['name'] class Meta: unique_together = (('parent', 'slug',)) verbose_name_plural = 'categories' def get_slug_list(self): try: ancestors = self.get_ancestors(include_self=True) except: ancestors = [] else: ancestors = [ i.slug for i in ancestors] slugs = [] for i in range(len(ancestors)): slugs.append('/'.join(ancestors[:i+1])) return slugs def __str__(self): return self.name In my ListView I have such query Category.objects.all() And now I want to display all of my parent object on the main page of index.html and in submenu consequently children for each specific parent. How can I do it? -
Present ManyToMany in Django's Admin as horizontal-filter using related_name
I have the following: class User(models.Model) blablabla class Product(models.Model) authorized_users = models.ManyToManyField( User, related_name='shared_products', ) I already configured the admin of Product to show authorized_users as an horizontal filter, in order to select all the users that can edit a product. class ProductAdmin(admin.ModelAdmin): filter_horizontal = ( 'authorized_users', ) admin.site.register(Product, ProductAdmin) The problem is that I want to do the same in the admin of User, meaning that I want to have an horizontal filter for shared_products, in order to select the products that this user is able to edit. I have tried the following which clearly doesn't work: class UserAdmin(admin.ModelAdmin): filter_horizontal = ( 'authorized_users', ) admin.site.register(User, UserAdmin) Other answers I have found recomend the usage of Inlines but as I have seen they are used to edit the model instance on the other end, which is not I what I want to do. Does someone have an idea of how to achieve this? -
Not able to find the query portion in looped back request by HttpResponseRedirect | Session is not saving the key/value
I am trying to redirect to another API for some random token generation and that will ultimately loop back to my current URL again, but when the redirected URL is actually looped back to the function I am not able to find the QUERY_STRING in request.META. In the intermediate state I am able to see the query portion. The intermediate state is (I found by giving print statement) as below: https://mysite.domain.com/api/home/?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6qh In views.py: def home(self, request): print("\nMeta: ", request.META) # Prints -> # Meta: {'HTTP_ACCEPT': 'application/json, text/plain, */*', 'HTTP_CONNECTION': 'keep-alive', 'REMOTE_ADDR': 'xx.xx.xx.xxx', 'HTTP_ORIGIN': 'https://mysite.domain.com', 'CONTENT_LENGTH': '', 'QUERY_STRING': '', 'wsgi.multithread': False, 'uwsgi.node': b'ip-xx-xx-xx-xx.aws.test.domain.com', 'wsgi.input': <uwsgi._Input object at 0x7f965c42b3a8>, 'CONTENT_TYPE': '', 'wsgi.multiprocess': False, 'REQUEST_METHOD': 'GET', 'SCRIPT_NAME': '', 'REMOTE_PORT': '62724', 'REQUEST_SCHEME': 'https', 'SERVER_PROTOCOL': 'HTTP/1.1', 'SERVER_NAME': 'mysite.domain.com', 'HTTP_ACCEPT_ENCODING': 'gzip, deflate, br', 'HTTP_USER_AGENT': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.81 Safari/537.36', 'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.9', 'wsgi.errors': <_io.TextIOWrapper name=2 mode='w' encoding='ANSI_X3.4-1968'>, 'REQUEST_URI': '/dboardrpt/', 'HTTP_HOST': 'mysite.domain.com', 'DOCUMENT_ROOT': '/etc/nginx/html', 'wsgi.file_wrapper': <built-in function uwsgi_sendfile>, 'HTTP_REFERER': 'https://mysite.domain.com/api/home', 'wsgi.version': (1, 0), 'wsgi.url_scheme': 'https', 'HTTPS': 'on', 'uwsgi.version': b'2.0.14', 'SERVER_PORT': '443', 'wsgi.run_once': False, 'PATH_INFO': '/home/'} # Where the `QUERY_STRING` is blank, and that why the below if statement is failing. if (request.GET.get('token')): ... # Business logic follows.... ... else: URL = …