Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to set subdomains whit ip using nginx
Can subdomains be used with ip on Nginx for testing, like teste.x.x.x.x I did this but does not work. server_name teste.x.x.x.x teste2.x.x.x.x ; Thanks -
Custom validation in a CUSTOM Django admin
I've a custom django admin that extends a default change_form (I do it because a need some logic for uploading images), but I need a way to show the page again if no image was uploaded, and show the errors. Some code to illustrate: class MyModel(models.Model): ... main_photo = models.ForeignKey(Photo) photos = models.ManyToManyField(Photo, related_name='collage') I extend the change_form.html admin template for this model: myapp/templates/admin/mymodel/change_form.html {% extends "admin/change_form.html" %} {% block inline_field_sets %} {% for inline_admin_formset in inline_admin_formsets %} {% include inline_admin_formset.opts.template %} {% endfor %} <fieldset class="module"> <h2>Upload photos</h2> <h3>Main photo</h3> <input name="main_photo" type="file" /> <h3>Others</h3> <input name="photos" type="file" multiple /> </fieldset> {% endblock inline_field_sets %} Now I overwrite the save_model method from ModelAdmin in the admin.py @admin.register(MyModel) class MyModelAdmin(admin.ModelAdmin): ... exclude = ['main_photo', 'photos'] def save_model(self, request, obj, form, change): photos = request.FILES.getlist('photos') main_photo = request.FILES.get('main_photo', None) if not main_photo: pass # --> I NEED THE WAY TO NOTIFY THE USER THIS IMAGE MUST BE UPLOADED # raise ValidationError("msg") --> It's not an option because this doesnt show the form re-rendered with the error. # some internal bussiness logic here: folder_to_save = '{0}/{1}'.format(self.folder_to_save_img, obj.id) obj.main_photo = Photo.objects.create(folder=folder_to_save, original=main_photo) obj.save() if photos: for photo in photos: obj.photos.add(Photo.objects.create(folder=folder_to_save, original=photo)) -
Django with Docker - Server not starting
I have followed the steps in the official docker tutorial for getting up and running with django: https://docs.docker.com/compose/django/ It works fine until I have to run docker-compose up It doesn't directly give me an error, but it won't run the server either, stopping at this point: (Screenshot of the Docker Quickstart Terminal) I am on Windows and have therefore used docker-toolbox. Thanks for your suggestions! -
Running Wagtail site with Docker
I'm trying to convert an existing Wagtail site to run with Docker. I have created the image and then run the container, but I'm unable to connect in the browser window. Getting 0.0.0.0 didn’t send any data. ERR_EMPTY_RESPONSE. Dockerfile: FROM python:3.6 RUN mkdir /app WORKDIR /app COPY ./ /app RUN pip install --no-cache-dir -r /app/requirements/base.txt RUN mkdir -p -m 700 /app/static RUN mkdir -p -m 700 /app/media ENV DJANGO_SETTINGS_MODULE=mysite.settings.dev DJANGO_DEBUG=on ENV SECRET_KEY=notsosecretkey ENV DATABASE_URL=postgres://none ENV SENDGRID_KEY=sendgridkey EXPOSE 8080 RUN chmod +x /app/entrypoint.sh \ && chmod +x /app/start-app.sh RUN python manage.py collectstatic --noinput ENTRYPOINT ["/app/entrypoint.sh"] CMD ["/app/start-app.sh"] docker-compose.yml: version: '2' services: db: environment: POSTGRES_DB: app_db POSTGRES_USER: app_user POSTGRES_PASSWORD: changeme restart: always image: postgres:9.6 expose: - "5432" ports: - "5432:5432" app: container_name: mysite_dev build: context: . dockerfile: Dockerfile depends_on: - db links: - db:db volumes: - .:/app ports: - "8080:8080" environment: DATABASE_URL: postgres://app_user:changeme@db/app_db command: python manage.py runserver 0.0.0.0:8080 entrypoint.sh: #!/bin/sh set -e exec "$@" start-app.sh: #!/bin/sh python manage.py runserver 0.0.0.0:8080 I run docker run -p 8080:8080 app:latest and it works when I run docker ps showing that it's at 0.0.0.0:8080->8080/tcp, but when I go to 0.0.0.0:8080 in the browser window, I get the error. What am I missing? -
Is there any open-source free codes of a Django Python database app with a CRUD and search functionality? [on hold]
Is there any open-source free codes and tutorials of a Django Python database app with a CRUD and search functionality? Need to develop a bioinformatics-oriented application with an extended search and data view functionality. And I am thinking what technology would be more appropriate: Django Python or YII PHP. Thx. -
Trouble using an Oracle View in Models.py
My group and I are attempting to rewrite our website. We are keeping an Oracle database back-end, and rewriting the front-end with Python Django. No problem connecting to Oracle, or accessing the datatables. Now I'm trying to add an Oracle view to the models.py, and I can't get it to work. I googled this question with many results, so I know it is possible and apparently common, but I can't get it to work. All I've done so far is add the class to models.py. We are using PhCharm as our IDE. When I try to access the data using the Python Console, I can import the class, but when I try to load the QuerySet I get the error "Unable to get repr for " in the result window. Does anyone see something I'm missing from my model? Here is the model: class LawBillRoleActionInfoView(LawBaseClass): combo_id = models.AutoField(primary_key=True) rltp_role_cd = models.CharField(max_length=2, blank=True) bill_dft_no = models.CharField(max_length=6, blank=True) session_id = models.IntegerField(blank=True, null=True) ebrl_appl_seq = models.IntegerField(blank=True, null=True) enty_id_seq = models.IntegerField(blank=True, null=True) lst_nm = models.CharField(max_length=100, blank=True) fst_nm = models.CharField(max_length=40, blank=True) mi = models.CharField(max_length=1, blank=True) entity = models.CharField(max_length=145, blank=True, null=True) prtydist = models.CharField(max_length=11, blank=True, null=True) blac_appl_seq = models.IntegerField(blank=None, null=True) role_descr = models.CharField(max_length=80, blank=True) shr_ttl = … -
Why can't I display my background image in django template?
I have an app by the name 'main' having static folder and template folder. My static folder goes like static/main/background/city.png I am trying to set background image of my html file but it does not load. Can you tell me what is it that I'am doing wrong? <style> body{ background-image:url("{static 'main/background/city.png'}"); } </style> -
Django: Modify model field value when form is submitted
I have a model field for each use that keeps track of their score on my website. Every time a user does some I want to add or subtract from their score. In this particular case, I would like to change the users score when they publish a post on my site. I am able to access the user's score, but not modify it. Here is what I have so far: def createPost(request): user = UserProfile.objects.get(user=request.user) current_score = user.user_score if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): ... user.user_score = current_score - 1 ... else: form = PostForm() return render(request,'feed/userpost_form.html',{'form':form}) I am not getting any errors and publishing the post works fine, just not modifying the user's score. Also, I am using Django 1.11 -
Between Django and WAMP which would be better for using their sql for my Android studio project?
I want to use the database and communicate between both using REST API. -
Rest framework: different serializer for input and output data on post/put operations
Lets say I have these models: class Download(MPTTTimeStampedModel): endpoint = models.ForeignKey(EndPoint, related_name="downloads",) class EndPoint(TimeStampedModel): name = models.CharField(max_length=100, verbose_name=_(u"Nombre")) url = models.CharField(max_length=2000, verbose_name=_(u"Url")) These serializers: class DownloadSerializer(serializers.ModelSerializer): class Meta: model = Download fields = ('id', 'endpoint') def create(self, validated_data): ... def update(self, validated_data): ... class EndPointSerializer(serializers.ModelSerializer): class Meta: model = EndPoint fields = ('id', 'name', 'url') def create(self, validated_data): ... def update(self, validated_data): ... And this generic api view: class DownloadList(generics.ListCreateAPIView): queryset = Download.objects.all() serializer_class = DownloadSerializer This will allow me to create a download by sending a json representation looking like this: { 'id': null, 'endpoint': 19 } And upon creation, the web service will send me back the data with the id from the database. Now, I actually want the web service to send me back not just the endpoint id but a complete representation of the object, Something like this: { 'id': null, 'endpoint': { 'id': 19, 'name': 'my endpoint', 'url': 'http://www.my-endpoint.com/' } } I would manage this with this serializer: class DownloadDetailedSerializer(DownloadSerializer): endpoint = EndPointSerializer(many = False, read_only=False) And now the actual question: how do i tell my generic view to use this last serializer for the returned data while keeping the original DownloadSerializer for the input? -
Django and Postgress Heroku deployment error
I have the following error in Heroku: at=error code=H10 desc="App crashed" method=GET path="/" host=psc-test.herokuapp.com request_id=c16bb8e0-a1e6-4905-ae79-56d105d71ef7 fwd="92.86.38.87" dyno= connect= service= status=503 bytes= protocol=https and I have no idea why -
How to pass an InMemoryUploadedFile as parameter to a celery task with json set as serializer?
I've just changed my celery settings to use json as serializer, I have to change some of my tasks with objects like querysets as parameters. I have one particular task with an InMemoryUploadedFile as parameter that can no longer be used with json as serializer. Do you have any advice since the file has no path please? The only thing I can think of would be to temporarily save the file, then pass the path as parameter, then reopen the file, and finally delete it. Thanks guys! -
Django debug toolbar 404
I am trying to get django-debug-toolbar working. I have followed the installation steps and I get the sidebar including stats (e.g. SQL 1 query in 2.75ms, Static Files 19 Files used, 30 receivers of 12 signals) which seem to be legitimate and indicate that its working. However, when I click for more info on a given tab, I get a 404 in browser, and this sort of thing in the console: "GET /__debug__/render_panel/?store_id=ac74875cfe864b2dab4c6d17c1d1ed5d&panel_id=RequestPanel HTTP/1.1" 404 1791" Other pages on site do work. I have tried various configurations in urls.py. Here is what I currently have: from __future__ import absolute_import, unicode_literals from django.conf import settings from django.conf.urls import include, url from django.contrib import admin from wagtail.wagtailadmin import urls as wagtailadmin_urls from wagtail.wagtailcore import urls as wagtail_urls from wagtail.wagtaildocs import urls as wagtaildocs_urls from search import views as search_views urlpatterns = [ url(r'^django-admin/', include(admin.site.urls)), url(r'^admin/', include(wagtailadmin_urls)), url(r'^documents/', include(wagtaildocs_urls)), url(r'^search/$', search_views.search, name='search'), # For anything not caught by a more specific rule above, hand over to # Wagtail's page serving mechanism. This should be the last pattern in # the list: url(r'', include(wagtail_urls)), # Alternatively, if you want Wagtail pages to be served from a subpath # of your site, rather than the … -
Django: Extent with snippets or better solution
I have the following template: {% extends "account/base.html" %} {% load i18n %} {% load account %} {% load crispy_forms_tags %} {% block head_title %}{% trans "Password Reset" %}{% endblock %} {% block content %} <div class="container"> <div class="row justify-content-center"> <div class="col-8"> <h1>Reset your password</h1> {% if user.is_authenticated %} {% include "account/snippets/already_logged_in.html" %} {% endif %} <p>{% trans "Forgotten your password? Enter your e-mail address below, and we'll send you an e-mail allowing you to reset it." %}</p> <form method="POST" action="{% url 'account_reset_password' %}" class="password_reset"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-primary">Reset My Password</button> </form> <p><em>{% blocktrans %}Please contact us if you have any trouble resetting your password.{% endblocktrans %}</em></p> </div> </div> </div> {% endblock %} account/base.html contains this here: {% extends "base.html" %} base.html then contains tags etc. I am currently struggling with finding the best solution while considering DRY. In my template I have written: <div class="container"> <div class="row justify-content-center"> <div class="col-8"> [more text] </div> </div> </div> I have several of these templates and in each of them I am currently writing the same ... I am now wondering is the right solution to include these opening / closing div-tags in two files and then … -
Pre-populate HTML form table from database using Django
I have a class-based view (IndexView at views.py) that shows a table with all the data stored in the database. This view is rendered in index.html using a def get_queryset(self) to obtain all the data. No issues yet. The difficult part for me is trying to do it using a form, to be able to modify and save the amount column. I have no issues with the POST part, where I use AJAX to save the new values. Where I'm having issues is getting the initial values from the database to populate a Django Form (forms.py) I tried using initial argument in the definition of the form fields (at forms.py), even overriding __init__ at the form definition, but I don't know how to get "one value". I mean, the closer I've been in my tests was populating a MultipleChoiceField with: forms.ModelMultipleChoiceField(queryset=Item.objects.order_by('code__name')) (achieving a multiple choice field of Item object (1), Item object (2), etc.) But how do you populate a single IntegerField or CharField with the content of the database to show a form-based table field in the template? I'm trying first with a single item (to try to understand how to reference one item/value to populate them using the … -
Unable to import view .. Python Django
i donot why app registery error is showing when i try run the url.py in music folder i see this error also view not getting imported when i try running the website urls, i get this above errors, i tried searching for solution in this website.. couldn't get the proper ans please help to resolve this soon team. -
Python // coming from SQL server table with /
I have a field in my SQL server table that is a varchar that is coming into my model defined as field= models.CharField(db_column = 'tablename', max_length = 30) When I look at the POST coming through my field is displayed as AAA//AAA#### when it's stored in the database as AAA/AAA####. Later in my view I try to call the field, but it's attempting to divide giving the following error: ValueError: invalid literal for int() with base 10: 'AAA\\AAA####' How can I get this field to display as AAA/AAA#### in my post? owner = request.POST.get('usercheck') -
Arrayfield in Django
my code: pagerange_str_array = ArrayField(models.CharField(max_length=10, blank=True, default=list())) docs example: https://docs.djangoproject.com/en/2.0/ref/contrib/postgres/fields/ board = ArrayField( ArrayField( models.CharField(max_length=10, blank=True), size=8, ), size=8, ) docs - size: This is an optional argument. error message: DETAIL: Array value must start with "{" or dimension information. But none of these work: default={}, '{}',or {''} They all get the same error message. docs: If you give the field a default, ensure it’s a callable such as list (for an empty default) or a callable that returns a list (such as a function) But none of these work either: default=list, list(). null=True (my original code) also does not work. All these examples give the same error. I have seen non-Django solutions on the web, but what is an example of code that works in Django?! Thanks. -
How do I render my django login form with bootstrap?
I am struggling to understand how handling forms manually works... It's a bit of a headache because there are no relevant examples, or they are outdated. I just have the basic login form with username and password. I would like to display the errors under each field if possible. Thank you. <form method="post"> {% csrf_token %} {{ form.username }}<br> {{ form.password }}<br> {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endfor %} {% for error in form.non_field_errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endif %} <button type="submit" class="btn btn-primary">Submit</button> </form> Right now, the above snippet display errors in such way that my whole form gets moved to the left inside the html page. -
Django docs -- CBVs: Why not just define a get() method that takes an argument from a URL?
Noob here going through the Django docs, trying to get a grip on how it all fits together. In this section of their document on generic class-based views, they demonstrate the hard-coding of filter parameters for a particular publisher (in this example) into ListView's queryset attribute and suggest that doing so will become problematic once you need separate ListViews for every publisher. That makes sense to me. In the next section they suggest overriding ListView's get_queryset() method this way: class PublisherBookList(ListView): template_name = 'books/books_by_publisher.html' def get_queryset(self): self.publisher = get_object_or_404(Publisher, name=self.kwargs['publisher']) return Book.objects.filter(publisher=self.publisher) My question is, why not just declare a get() method in ListView and allow get() to take in publisher from the URL? What am I missing here? -
class based view passing parameters
I have just started using Class-based views and I am trying to pass the parameters to class-based view as: return HttpResponseRedirect(reverse('myView'), kwargs={'method': 'learning'}) My view is: class MyView(View): form_class = MyForm initial = {'key': 'value'} template_name = 'algoRunning.html' def dispatch(self, request, *args, **kwargs): print (kwargs['method']) data = self.readFile('myFile.txt') context = {'result': data} return render(request, self.template_name, context) def readFile(self, filePath): # read data return data my url pattern looks like: urlpatterns = [... url(r'^learning/(?P<method>[a-z]+)/$', my_views.MyView.as_view(), name='myView'), ..] But, it gives me following error Reverse for 'myView' with no arguments not found. 1 pattern(s) tried: ['learning/(?P<method>[a-z]+)/$'] What am I doing wrong?? -
AssertionError: `base_name` argument not specified
i'm trying to add a parameter of a model to a URL pattern, as such: http://111.111.11.111:8080/resultados/image.jpg where nome_ficheiro = image.jpg (nome_ficheiro is a model parameter, see below) But i'm getting the following error: File "/usr/local/lib/python2.7/dist-packages/rest_framework/routers.py", line 139, in get_default_base_name assert queryset is not None, '`base_name` argument not specified, and could ' \ AssertionError: `base_name` argument not specified, and could not automatically determine the name from the viewset, as it does not have a `.queryset` attribute. The URL pattern: router = routers.DefaultRouter() urlpatterns = [url(r'^', include(router.urls))] router.register(r'resultados/(?P<nome_ficheiro>.+)/$',resultUploadView.as_view({'get': 'get_queryset'})) The view: class resultUploadView(generics.ListAPIView): serializer_class = resultSerializer queryset = labelResult.objects.all() def get_queryset(self): nome = self.kwargs['nome_ficheiro'] return labelResult.objects.filter(nome_ficheiro=user) The model: class labelResult(models.Model): nome_ficheiro = models.CharField(max_length=120) especie = models.CharField(max_length=120) zona = models.CharField(max_length=120) data = models.CharField(max_length=120) USING: Python 2.7.12 and DRF 3.6.3 -
Django ChoiceField generated from a function
I want a generic list of choices in my form. In the devices.py def get_devices(): api_url = api_url_base response = requests.get(api_url,headers=headers) if response.status_code == 200: return json.loads(response.content.decode('utf-8')) else: return None ####################################### devices_infos = get_devices() if devices_infos is not None: print('Voici les devices: ') for each in devices_infos['data']: device_name = (each['name']) for k in range(len(devices_infos['data'])): mes_choix = ("(%s, ('%s'))," % (k,device_name )) else: print("[!] Request failed") It returns me my 2 devices like that (0, ('Erics phone')), (1, ('mySensor001')), In forms.py from django import forms from alertes.devices import * class NameForm(forms.Form): nom_alerte = forms.CharField(label='Nom Alerte', max_length=100) devices = forms.ChoiceField(label='Liste devices', choices=mes_choix, required=False) user_mail = forms.EmailField(label = 'Email a envoyer', max_length=100) Here, i would have in the devices label, a list of choice like Erics phone mySensor001 But i got the need more than 1 value to unpack error -
Parent Keys in Django Template URL lookup
In Django, I am trying to make an app with a tree hierarchy of models, i.e: My Models in models.py: class Book(models.Model): name = models.CharField("Book Name", max_length = 80) class Chapter(models.Model): name = models.CharField("Book Name", max_length = 80) book = models.ForeignKey('Book', on_delete = models.CASCADE) My URL patterns in urls.py: urlpatterns = [ path('books/', views.BookListView.as_view(), name='book_list'), path('books/<int:book>/', views.BookDetailView.as_view(), name='book_detail'), path('books/<int:book>/chapters/', views.ChapterListView.as_view(), name='chapter_list'), path('books/<int:book>/chapters/<int:chapter>/', views.ChapterDetailView.as_view(), name='chapter_detail'), path('books/<int:book>/chapters/create/', views.ChapterCreateView.as_view(), name='chapter_create'), My Views in views.py: class BookListView(generic.ListView): model = 'Book' class BookDetailView(generic.DetailView): model = 'Book' pw_url_kwarg = 'book' class ChapterListView(generic.ListView): model = 'Chapter' def get_queryset(self): return Chapter.objects.filter(book = self.kwargs['book']) class ChapterDetailView(generic.DetailView): model = 'Chapter' pw_url_kwarg = 'chapter' class ChapterCreateView(generic.CreateView): model = 'Chapter' fields = ['name', 'book'] def get_initial(self): initial = super().get_initial().copy() initial['book'] = self.kwargs.['book'] return initial; In my HTML-Template used for the list of chapters, I want to have a link to create a new chapter. Currently, that template looks as follows: Template chapter_list.html: <ul> {% for chapter in chapter_list %} <li>{{ chapter.name }}</li> {% endfor %} </ul> <a href="{% url 'chapter_create' 42 %}">Add new chapter</a> Obviously, I don't want to add all new chapters to the book with ID 42, rather I would like to use the book ID from the chapter list, … -
Heroku run migrate gives server error
I pushed my application to Heroku, assign the dyno, and create the database. Now if I run: heroku run python manage.py migrate I receive the error: 'Is the server running on host 'localhost' and accepting TCP/IP connections on port 5432? but I don't want to run on my server but one the Heroku server