Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use the `path` function instead of the `url` function
I am learning how to use django-rest-framework to build my front-end separation project. I follow the django official documentation using the path function instead of the url function for development. But when I added django-rest-framework, I found that django-rest-framework is still using the url function. In order to maintain code consistency, I wrote the following code: In 'quickstart/urls.py'('quickstart' is my app name) from django.urls import path, include from rest_framework import routers from quickstart import views router = routers.DefaultRouter() router.register('users', views.UserViewSet) router.register('groups', views.GroupViewSet) app_name = 'quickstart' urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls')), ] In 'tutorial/urls.py'('tutorial' is project name) from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('quickstart/', include('quickstart.urls')), ] However, there was a problem with the program. When I visited 127.0.0.1/quickstart/users, I got the following error: Internal Server Error: /quickstart/users/ Traceback (most recent call last): File "C:\dev\tomorrow-headline\venv\lib\site-packages\rest_framework\relations.py", line 376, in to_representation url = self.get_url(value, self.view_name, request, format) File "C:\dev\tomorrow-headline\venv\lib\site-packages\rest_framework\relations.py", line 314, in get_url return self.reverse(view_name, kwargs=kwargs, request=request, format=format) File "C:\dev\tomorrow-headline\venv\lib\site-packages\rest_framework\reverse.py", line 50, in reverse url = _reverse(viewname, args, kwargs, request, format, **extra) File "C:\dev\tomorrow-headline\venv\lib\site-packages\rest_framework\reverse.py", line 63, in _reverse url = django_reverse(viewname, args=args, kwargs=kwargs, **extra) File "C:\dev\tomorrow-headline\venv\lib\site-packages\django\urls\base.py", line 90, in reverse return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, … -
Internal Server Error, The server encountered an internal error or misconfiguration and was unable to complete your request
I've just finished switching(or trying to) from SQlite toPostgresql for my Django 1.11, on my Centos 7 server. I'm getting the "The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator, root@localhost..." I have checked the Apache Error log but I can't seem to make out what the error logs are trying to tell me. Here's is the latest from the error log after shutting down and starting apache: [Fri Aug 17 03:43:48.612578 2018] [mpm_prefork:notice] [pid 8653] AH00170: caught SIGWINCH, shutting down gracefully [Fri Aug 17 03:44:12.483952 2018] [core:notice] [pid 16472] SELinux policy enabled; httpd running as context system_u:system_r:httpd_t:s0 [Fri Aug 17 03:44:12.484791 2018] [suexec:notice] [pid 16472] AH01232: suEXEC mechanism enabled (wrapper: /usr/sbin/suexec) [Fri Aug 17 03:44:12.498213 2018] [auth_digest:notice] [pid 16472] AH01757: generating secret for digest authentication ... [Fri Aug 17 03:44:12.498876 2018] [lbmethod_heartbeat:notice] [pid 16472] AH02282: No slotmem from mod_heartmonitor [Fri Aug 17 03:44:12.501950 2018] [mpm_prefork:notice] [pid 16472] AH00163: Apache/2.4.6 (CentOS) mod_wsgi/3.4 Python/2.7.5 configured -- resuming normal operations [Fri Aug 17 03:44:12.501972 2018] [core:notice] [pid 16472] AH00094: Command line: '/usr/sbin/httpd -D FOREGROUND' [Fri Aug 17 03:44:16.287806 2018] [:error] [pid 16473] [remote 192.168.140.179:0] mod_wsgi (pid=16473): Target WSGI script '/home/kad/stargate/stargate/wsgi.py' cannot … -
CookieCutter Django; AttributeError: '_Environ' object has no attribute 'Path'
I'm trying to use CookieCutter Django and there are some errors on settings file. I'm trying to run server on local anyway but there are some errors. First I saw this error so I changed it to from os import environ ModuleNotFoundError: No module named 'environ' and then there is still an error. ROOT_DIR = environ.Path(file) - 3 # (project/config/settings/base.py - 3 = project/) AttributeError: '_Environ' object has no attribute 'Path' Are these errors only happened to me? Seems like other people don't change these parts. How can I fix this? -
Which method of creating a custom user that uses email instead of username is best in django?
Here are two examples of how to define a Custom User in django. http://musings.tinbrain.net/blog/2018/aug/14/django-registration-redux/ https://www.fomfus.com/articles/how-to-use-email-as-username-for-django-authentication-removing-the-username the first method uses AbstractBaseUser and a PermissionsMixin the second uses AbstractUser Both seem to achieve the same result, which method is better and why ? -
Django - Failed to import a models file from another app
I'm trying to import a model into some app from another app, but it throws an error. Project direcotires from django.db import models from ..book.models import Book class Cart: books = models.ManyToManyField(Book) Error: ValueError: attempted relative import beyond top-level package But if I do: from django.db import models from book.models import Book class Cart: books = models.ManyToManyField(Book) PyCharm will be complaining. It says "Unsolved reference book". -
Django datetimeinput widget - validate as datetime, but convert to unix time before saving
I have a django form that looks like this: class AnnouncementCreationForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['publish_datetime'].widget = forms.DateTimeInput() self.fields['publish_datetime'].widget.attrs.update({'placeholder': 'YYYY-MM-DD HH:MM:SS'}) self.fields['publish_datetime'].required=False self.fields['document'].required=False class Meta: model = CompanyAnnouncement exclude = ['company'] Where the model looks like this: class CompanyAnnouncement(models.Model): class Meta: ordering = ['publish_datetime'] verbose_name = 'Company Announcement' verbose_name_plural = 'Company Announcements' company = models.ForeignKey(Company, on_delete=models.CASCADE) publish_datetime = models.DecimalField(decimal_places=6, max_digits=18, help_text='Leave blank to publish immediately') title = models.CharField(max_length=100) document = models.FileField(upload_to='company_announcements', help_text='', null=True, blank=True) I have overridden the fault input widget for the publish_datetime to use a DateTimeInput, in spite of the value being a decimal. This is because I want the users to input a datetime, and then convert it to unix time before saving it in the db. This is done in the view: class AccouncementCreateView(LoginRequiredMixin, CreateView): form_class = AnnouncementCreationForm template_name = 'create_announcement.html' redirect_unauthenticated_users = True success_url = '/users/my_companies' def form_valid(self, form): form.instance.company = Company.objects.filter(crn=self.kwargs['company_spec_url'])[0] print(type(form.instance.publish_datetime)) # Returns 'datetime.datetime' if form.instance.publish_datetime: form.instance.publish_datetime = form.instance.publish_datetime.timestamp() else: form.instance.publish_datetime = dt.now().timestamp() form.save() return super().form_valid(form) The latter half of the if statement (i.e. the input field is blank) works, and it successfully stores the current unix time in the db, but the first half does not work. The form complains, … -
django-rest-auth reset password email contains 'example.com ' domain instead of site_domain
I'm using django-rest-auth in my project and want to customize the email template used when resetting a password> if I send a POST request at /rest-auth/password/reset/ with user email the request works but the email I receive is: email: from webmaster@localhost via ... ... http://example.com/reset/ZGJjNjU2MjAtZjdjNy00MDdjLTkyZDctZDAwZGM2M2IzMmU4/4ys-09e6403c9784bea04986/ ... basically I want the domain example to be the domain of the project as well as the sender email to be a custom email. I saw that I could create a /templates/registration/password_reset_email.html file and makes changes there. line of html I need to change is: {{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %} Is there a way to pass the project domain without hard coding it? How can I change the sender's email address to a custom one? -
How to show all images of category in foreign key by loop in django template?
I'm making a django practice by myself and this time about CV (Resume) Website, In the Portfolio section it shows the (title, client and description) of the project, down bellow, a gallery (using bootstrap carrousel) of all images from that project. I've tryed some filters in views.py but i can't get the separated images for each one. Also looking for filtering in template but neither too. So the output would be something like this: PORTFOLIO SECTION name: Practice Project 1 client: Peter Parker (ALL IMAGES IN CARROUSEL OF THIS PROJECT) name: Practice Project 2 client: Barack Obama (ALL IMAGES IN CARROUSEL OF THIS PROJECT) I need to show all images related with its project CODE: models.py: from django.db import models from django.contrib.auth.models import User from ckeditor.fields import RichTextField # Create your models here. class Project(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE) name = models.CharField(verbose_name='Nombre del proyecto', max_length=200) client = models.CharField(verbose_name='Nombre del cliente', max_length=200) description = RichTextField(verbose_name='Descripción') start = models.DateField(verbose_name='Fecha de Inicio', null=True, blank=True) ending = models.DateField(verbose_name='Fecha de Finalización', null=True, blank=True) order = models.SmallIntegerField(verbose_name="Orden", default=0) created = models.DateTimeField(verbose_name='Fecha de creación', auto_now_add=True) updated = models.DateTimeField(verbose_name='Fecha de modificación', auto_now=True) class Meta: verbose_name = 'Proyecto' verbose_name_plural = 'Proyectos' ordering = ['-start', 'order'] def __str__(self): … -
Django WSGI Configaration error
I'm stuck on deploying Django with WSGI and not able to get it to work. It's a new test app so I just ran django-admin startproject testing I created a virtual conda environment in the same directory. This is my wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testing.settings") application = get_wsgi_application() This is in my 000-default.conf <Directory /home/kiran_baktha/OverreadTool/testing/testing> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess testing python-path=/home/kiran_baktha/OverreadTool/testing/lib/python3.6/site-packages python-home=/home/kiran_baktha/OverreadTool/testing WSGIProcessGroup testing WSGIScriptAlias / /home/kiran_baktha/OverreadTool/testing/testing/wsgi.py I get the error "No module named testing" (testing is my app name). After reading a stack overflow answer, I added site packages path in DaemonProcess python-path is to avoid the "No module named Django" error which was getting thrown when the python-path is also the same as python-home because my environment is located there. Thanks for the help. -
how to use arabic_reshaper with data models?
i have project with Arabic data on Django system, i need make PDF file . i found arabic_reshaper it is work with me on single field from data , but on Models fields i don't know how i do that . in views.py : orders = CustomerOrder.objects.all() context = { 'orders' : orders , } in orders.html : {% for order in orders %} <tr> <th scope="row">{{ forloop.counter }}</th> {% for field, value in order.fields.items %} <td>{{ value }}</td> {% endfor %} </tr> {% endfor %} -
How do I get django template to recognize manytomanyfield comparison?
In my project, I am currently trying to access a manytomany field and compare it to another. I have several cases where I am doing something similar and it is working . The difference in this case is that I am trying to essentially say if one of the values in this many to many field equals a value in this other manytomanyfield, then do something.... Here is my code... Book(models.Model): author = models.ManyToManyField(Name) publisher = models.ManyToManyField(Name) In my Django template I am trying to do something like... {% If author_set.all in form.initial.publisher_set.all %} {{ author.name }} {% endif %} The example above is a simplified version of what I'm trying to do....I'm essentially trying to compare the manytomany fields and if any of the values match, perform an action. I've been at this most of today and have tried several combinations. If I do something like {% if user in form.initial.publisher.all %} This works fine. I'm struggling to try and figure out how I can compare manytomanyfields. I suspect the user query works fine because it's not a manytomanyfield. I'm thinking my format is off. I have tried to use the _set to both publisher and author as well … -
404 error in django static files
I am new in django. I was trying to add some bootstraps in my demo project. But i am just getting 404 not found error. I have searched a lot in the web for answers which didn't help me slving my silly problem. -
python3 django manage.py migrate error _gorg
I am trying to debug an error with python3. Below are versions of modules and the error when I try to run python3 manage.py migrate Python 3.6.5 python-ta 1.2.0 Below the error we are getting. Any advice or help on this appreciated. Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/pcrs/.virtualenvs/pcrsenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/home/pcrs/.virtualenvs/pcrsenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 337, in execute django.setup() File "/home/pcrs/.virtualenvs/pcrsenv/lib/python3.6/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/pcrs/.virtualenvs/pcrsenv/lib/python3.6/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/home/pcrs/.virtualenvs/pcrsenv/lib/python3.6/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/home/pcrs/.virtualenvs/pcrsenv/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/pcrs/pcrs/pcrs/problems_python/models.py", line 15, in <module> import python_ta File "/home/pcrs/.virtualenvs/pcrsenv/lib/python3.6/site-packages/python_ta/__init__.py", line 30, in <module> from .patches import patch_all File "/home/pcrs/.virtualenvs/pcrsenv/lib/python3.6/site-packages/python_ta/patches/__init__.py", line 4, in <module> from .type import patch_type_inference_transform File "/home/pcrs/.virtualenvs/pcrsenv/lib/python3.6/site-packages/python_ta/patches/type.py", line 4, in <module> from ..transforms.type_inference_visitor import TypeInferer File "/home/pcrs/.virtualenvs/pcrsenv/lib/python3.6/site-packages/python_ta/transforms/type_inference_visitor.py", line 5, in <module> from typing import CallableMeta, TupleMeta, Union, _gorg, _geqv, _ForwardRef ImportError: cannot import name … -
Django REST API is not returning all objects
I have a model of an "Instrument" which includes a field "active". When I go to the rest api it seems that all of the Instruments are listed, but there is one I have found that never appears. This is true even though it meets the criteria. This is how the Instrument view set is defined: class InstrumentViewSet(viewsets.ModelViewSet): serializer_class = serializers.InstrumentSerializer queryset = models.Instrument.objects.filter(active=True) lookup_field = ('slug') permissions = (permissions.IsAuthenticated) def get_queryset(self): plant = self.request.query_params.get('plant', None) location = self.request.query_params.get('location', None) name = self.request.query_params.get('name', None) issue = str2bool(self.request.query_params.get('issue', False)) attn = str2bool(self.request.query_params.get('attn', False)) pastdue = str2bool(self.request.query_params.get('pastdue', False)) active_issues = str2bool(self.request.query_params.get('active_issues', False)) active_pastdue = str2bool(self.request.query_params.get('active_pastdue', False)) active_due = str2bool(self.request.query_params.get('active_due', False)) since = self.request.query_params.get('since', None) if active_issues: return queries.get_active_issues(self.request.user, None, None) elif active_pastdue: return queries.get_past_due(self.request.user, None, None) elif active_due: return queries.get_due(self.request.user, None, None) queryset = models.Instrument.objects.filter(location__plant__in=self.request.user.plants.all()) if plant is not None: queryset = queryset.filter(location__plant__pk=plant) if location is not None: queryset = queryset.filter(location__pk=location) if name is not None: queryset = queryset.filter(Q(name__contains=name)|Q(location__name__contains=name)) if issue: queryset = queryset.filter(active_issue=issue) if attn: queryset = queryset.filter(attention=attn) if pastdue: queryset = queryset.filter(past_due=pastdue) if since is not None: last_time = datetime.strptime(since, '%Y-%m-%d %H:%M:%S') queryset = queryset.filter(date_edited__gte=last_time) return queryset It should return all instruments where active=true which the one I am referring … -
How to serve static content with Nginx and Django Gunicorn when using Traefik
I have a web application (Django based) that is utilising multiple containers: Web Application (Django + Gunicorn) Traefik (acting as the reverse proxy and SSL termination) Database which is used with the Web application Redis which is used with the Web application According to some of the documentation I have read, I should be serving my static content using something like NGINX. But I don't have any idea on how I would do that. Would I install NGINX on my Web Application container or as a seperate NGINX container. How do I pass the request from Traefik? As far as I am aware you cannot server static content with Traefik. This is what my docker-compose.yml looks like: traefik: image: traefik ports: - 80:80 - 8080:8080 - 443:443 volumes: - /var/run/docker.sock:/var/run/docker.sock:ro - ./traefik/traefik.toml:/etc/traefik/traefik.toml:ro - ./traefik/acme:/etc/traefik/acme web: build: . restart: always depends_on: - db - redis - traefik command: python3 /var/www/html/applications/py-saleor/manage.py makemigrations --noinput command: python3 /var/www/html/applications/py-saleor/manage.py migrate --noinput command: python3 /var/www/html/applications/py-saleor/manage.py collectstatic --noinput command: bash -c "cd /var/www/html/applications/py-saleor/ && gunicorn saleor.wsgi -w 2 -b 0.0.0.0:8000" volumes: - .:/app ports: - 127.0.0.1:8000:8000 labels: - "traefik.enable=true" - "traefik.backend=web" - "traefik.frontend.rule=${TRAEFIK_FRONTEND_RULE}" environment: - SECRET_KEY=changemeinprod redis: image: redis db: image: postgres:latest restart: always environment: POSTGRES_USER: saleoradmin … -
Django: PicklingError using Huey
In my Django project I am using the nice task queue called Huey with redis as backend. Unfortunately, I get a very strange error message when I run a view that uses a Huey task and I do not get what's wrong. I hope someone can help me debug it. Django Version: 2.1 Exception Type: PicklingError Exception Value: Can't pickle <function paginator_number at 0x7f7dc83fed90>: it's not the same object as django.contrib.admin.templatetags.admin_list.paginator_number Exception Location: /home/user/.local/share/virtualenvs/django-1XPpM6qc/lib/python3.7/site-packages/huey/registry.py in get_message_for_task, line 67 Python Version: 3.7.0 Here the code/task that is executed. In the view the task is called: def form_valid(self, form): recipients = self.get_recipient_list(self.kwargs['pk']) bus = Bus.objects.get(pk=self.kwargs['pk']) send_mail_to_all_passengers(form=form, request=self.request, bus=bus, recipients=recipients) And here the Huey task itself: from django.conf import settings from django.contrib.sites.shortcuts import get_current_site from django.core import mail from django.core.mail import EmailMessage from django.template.loader import render_to_string from django.urls import reverse from huey.contrib.djhuey import task @task() def send_mail_to_all_passengers(form, request, bus, recipients): url_bus = request.build_absolute_uri(reverse('bus:bus-detail', args=(bus.pk,))) subject = form.cleaned_data['betreff'] current_site = get_current_site(request) message = render_to_string('bus/organisator_email.txt', { 'domain': current_site.domain, 'bus': bus, 'protocol': 'https' if request.is_secure() else 'http', 'url_bus': url_bus, 'message': form.cleaned_data['nachricht'] }) reply_to_mail = form.cleaned_data['email'] mails = [] for recipient in recipients: mails.append( EmailMessage(subject, message, settings.DEFAULT_FROM_EMAIL, (recipient,), reply_to=[reply_to_mail]) ) connection = mail.get_connection() connection.send_messages(mails) -
Adding a interactive choropleth in leaflet with django
I have a leaflet map in a template with a django backend. I have a State model as follows: class State(models.Model): name = models.CharField(max_length=100) done = models.IntegerField() left = models.IntegerField() What I would like to do is implement something like this leaflet demo to my application. 1) How do I get the states outlines (or city) to show up? As in, where do I get the data 2) How do I attach my state info (done and left) to the individual states. I'm confused how to bring in the shapefile and then tell django to join it with the states -
How to add a time stamp for all the fields in a model django
I'm looking to add a new table that records all the user activity in my models. I was able to add a time stamp for general edits, but is there any practical way of adding a new table with the time stamp and the changed field? This would be useful to have as a ledger for all the user activity. -
What is the right way of containing data in django?
I'm rebuilding school project from html page to django app. In old project I had some articles and two tests. For articles I created django model with text field and pasted in it article's content with HTML due to it have some decorations as a <"code> <"/code> tags. How should I contain tests if first is build with HTML forms and second with <"canvas>? Should I use text field again? Data is too complex. For the first test it goes as a forms with individual texts and inputs and checked by javascript. For second it is initializing js functions. How they are look like: First test with forms Second test with canvas Where can I read about it more? P.S. Sorry for bad english -
How to implement Notification view in django correctly?
I have implemented Django notification in my index view. But I have more view like create a view, update view delete view etc. When the user first login to my application, I show the number of notification and links but when the user switches to another view then number of notification changes to zero. Is there any way to retain all the notification in every view of Django. This is my views.py file from django.shortcuts import render, redirect, render_to_response from django.http import HttpResponse, HttpResponseRedirect from django.views.generic.edit import FormMixin from .models import Report_item, ClaimForm, UserNotification from django.views import generic from django.db.models import Q from django.contrib.auth import login, authenticate from django.shortcuts import render, redirect from django.utils import timezone from django.views.generic import View, UpdateView, DeleteView from .forms import SignUpForm, LoginForm from django.contrib.auth import logout from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend from django.core.urlresolvers import reverse_lazy from django.db.models import Q def IndexView(request): if request.user.is_anonymous: print("Hello") query_list = Report_item.objects.all() query = request.GET.get('q') if query: query_list = query_list.filter(Q(title__icontains=query) | Q(item_type__icontains=query) | Q(city__icontains=query) | Q(Description__icontains=query)).distinct() context = { "object_list": query_list, } return render(request, "feed/index.html", context) else: query_list = Report_item.objects.all() query = request.GET.get('q') if query: query_list = query_list.filter(Q(title__icontains=query) | Q(item_type__icontains=query) | Q(city__icontains=query) | Q(location__icontains=query) | Q(Description__icontains=query)).distinct() n … -
Google OAuth2 not issuing a refresh token even with access_type='offline'?
This question is similar to Not receiving Google OAuth refresh token, but I have already specified access_type='offline' as suggested in the comments to the accepted solution. I'm writing a Django app to send calendar invites using the Google API which is basically an adaptation of the Flask example given at https://developers.google.com/api-client-library/python/auth/web-app, in which I've created a model GoogleCredentials to store credentials persistently in a database instead of in the session. Here are the views: import logging from django.conf import settings from django.shortcuts import redirect from django.http import JsonResponse from django.urls import reverse from django.contrib.auth.decorators import login_required import google.oauth2.credentials import google_auth_oauthlib.flow import googleapiclient.discovery from lucy_web.models import GoogleCredentials logger = logging.getLogger(__name__) # Client configuration for an OAuth 2.0 web server application # (cf. https://developers.google.com/identity/protocols/OAuth2WebServer) # This is constructed from environment variables rather than from a # client_secret.json file, since the Aptible deployment process would # require us to check that into version control, which is not in accordance # with the 12-factor principles. # The client_secret.json containing this information can be downloaded from # https://console.cloud.google.com/apis/credentials?organizationId=22827866999&project=cleo-212520 CLIENT_CONFIG = {'web': { 'client_id': settings.GOOGLE_CLIENT_ID, 'project_id': settings.GOOGLE_PROJECT_ID, 'auth_uri': 'https://accounts.google.com/o/oauth2/auth', 'token_uri': 'https://www.googleapis.com/oauth2/v3/token', 'auth_provider_x509_cert_url': 'https://www.googleapis.com/oauth2/v1/certs', 'client_secret': settings.GOOGLE_CLIENT_SECRET, 'redirect_uris': settings.GOOGLE_REDIRECT_URIS, 'javascript_origins': settings.GOOGLE_JAVASCRIPT_ORIGINS}} # This scope will allow the application … -
How can I organize a list of fields based on another field?
I am trying to show a list of items organized by their category, with their respective category name directly above it in bold. For example: Category 1 List item 1 List item 2 Category 2 List item 3 However, here is what the code currently does: Category 1 List item 1 List item 2 List item 3 Category 2 List item 1 List item 2 List item 3 The two model classes involved taken from /models.py: class Model(models.Model): model_number = models.CharField('Model Number', max_length = 50) manufacturer = models.ForeignKey('Manufacturer', on_delete = models.SET_NULL, null = True) category = models.ForeignKey('Category', on_delete = models.SET_NULL, null = True) description = models.TextField(max_length = 1000, help_text = "Enter brief description of product", null = True) #TextField for longer descriptions def __str__(self): return f'{self.model_number}..........{self.description}' def get_absolute_url(self): #Returns the url to access a particular location instance return reverse('model-detail', args=[str(self.id)]) class Category(models.Model): category = models.CharField('Equipment Type', max_length = 50, help_text = "Enter general category of equipment") class Meta: verbose_name_plural = "categories" #default would have shown as "Categorys" on admin page def __str__(self): return self.category /model_list.html {% extends "base_generic.html" %} {% block content %} <div style="margin-left:20px; margin-top:20px"> <h1>Model list</h1> </div> {% if model_list %} {% for category in model_list %} <li><strong>{{ … -
Django: How to properly create an html with input
I have a Django project, in my views.py, I have the following code: def my_fun(request): : html = ('<H2>Input:%s </H2>'.format(input_text), '<H2> Results:%s</H2>'.format(results)) return HttpResponse(html) But the output looks like: How do I properly format my results and make it display on the html? Thanks! -
i am trying to use Amazon S3 to upload file from django i am getting an error expected string or bytes-like object
i wanted to upload my images and file in Amazon S3 but with below code i am getting error which says expected string or bytes-like object. as i have never used Amazon S3 for uploading file i dont know what to do. view.py if request.method=='POST': if request.POST['title'] and request.POST['body'] and request.POST['url'] and request.FILES['icon'] and request.FILES['image']: product = Product() #making object of model Product icon = request.FILES['icon'] image = request.FILES['image'] product.icon = "http://productpanditfiles.s3.amazonaws.com/{}".format(icon) iconstr = "http://productpanditfiles.s3.amazonaws.com/{}".format(icon) print(type(iconstr)) product.image = "http://productpanditfiles.s3.amazonaws.com/{}".format(image) imagestr="http://productpanditfiles.s3.amazonaws.com/{}".format(image) if icon and image: conn = S3Connection(settings.ACCESS_KEY, settings.PASS_KEY) bucket = conn.create_bucket("productpanditfiles") mime = mimetypes.guess_type(iconstr) mime1 = mimetypes.guess_type(imagestr) k = Key(bucket) k.Key = iconstr k.set_metadata("Content-Type",mime) #k.set_contents_from_string(iconstr) k.set_contents_from_file(StringIO(iconstr)) k.set_acl("public-read") k1 = Key(bucket) k1.Key = imagestr k1.set_metadata("Content-Type",mime1) #k1.set_contents_from_string(imagestr) k.set_contents_from_file(StringIO(imagestr)) k1.set_acl("public-read") product.pub_date = timezone.datetime.now() product.hunter = request.user product.save() return redirect('/products/' + str(product.id)) home.html {% extends 'base.html' %} {% block content %} {% if error %} {{error}} {% endif %} <br> <br> <div class="container"> <div class="jumbotron"> <h2>Create Product</h2> <form action="{% url 'create' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <label for="title">Title:</label> <input type="text" class="form-control" id="email" placeholder="please enter title" name="title" required> </div> <div class="form-group"> <label for="body">Description:</label> <textarea rows="4" cols="50" placeholder="Description" name="body" class="form-control" required> </textarea> </div> <div class="form-group"> <label for="url">URL:</label> <input type="text" class="form-control" id="url" placeholder="please enter … -
Can't seem to link CSS to HTML in Django?
This is my html file: {% load static %} <html> <head> <title>Abhya Tripathi|Developer</title> <link rel="stylesheet" href="{% static 'css/blog.css' %}"> </head> <body> <nav> <ul id='navbar'> <li><a href="#welcome-section">About</a></li> <li><a href="#projects">Work</a></li> <li><a href="#contact">Contact</a></li> </ul> </nav> <div id="welcome-section" class="intro"> <h1>Hey i'am Mimic.</h1> <p>a web developer</p> </div> <div id="projects" class="work"> <h2 class="work-header">These are some of my projects..</h2> <a href="https://codepen.io/FreeCodeCamp/pen/NNvBQW" target="_blank" class="project project-tile"> <img class="project-pic" src="https://cloud.githubusercontent.com/assets/15967809/17642794/d084d718-6171-11e6-83fa-ede5d0a67ad2.png" alt="project"> <div class="project-title">Tribute Page</div> </a> <a href="https://codepen.io/FreeCodeCamp/pen/ONjoLe" target="_blank" class="project project-tile"> <img class="project-pic" src="https://cloud.githubusercontent.com/assets/15967809/17642771/7cd6a0c4-6171-11e6-87fb-915f6084d104.png" alt="project"> <div class="project-title">Random Quote Machine</div> </a> <a href="https://codepen.io/FreeCodeCamp/pen/PNKdjo" target="_blank" class="project project-tile"> <img class="project-pic" src="https://cloud.githubusercontent.com/assets/15967809/17642772/7d02406c-6171-11e6-8c79-40a2933163dc.png" alt="project"> <div class="project-title">JavaScript Calculator</div> </a> <a href="https://codepen.io/FreeCodeCamp/pen/mVEJag" target="_blank" class="project project-tile"> <img class="project-pic" src="https://cloud.githubusercontent.com/assets/15967809/17642773/7d08cb94-6171-11e6-8c45-22e7cf64683e.png" alt="project"> <div class="project-title">Map Data Across the Globe</div> </a> <a href="https://codepen.io/FreeCodeCamp/pen/wGqEga" target="_blank" class="project project-tile"> <img class="project-pic" src="https://cloud.githubusercontent.com/assets/15967809/17642774/7d091806-6171-11e6-8d47-ecf2f2833fe2.png" alt="project"> <div class="project-title">Wikipedia Viewer</div> </a> <a href="https://codepen.io/FreeCodeCamp/pen/KzXQgy" target="_blank" class="project project-tile"> <img class="project-pic" src="https://cloud.githubusercontent.com/assets/15967809/17642775/7d354304-6171-11e6-8b56-66eee4681d88.png" alt="project"> <div class="project-title">Tic Tac Toe Game</div> </a> <a href="https://codepen.io/FreeCodeCamp/" class="show-all" target="_blank">Show all</a> </div> <div id="contact" class="contact"> <div class="header"> <h1>Let's work together...</h1> <p>How do you take your coffee?</p> </div> <a href="https://facebook.com/freecodecamp" target="_blank" class="contact-details">Facebook</a> <a id='profile-link' href="https://github.com/freecodecamp" target="_blank" class="contact-details">GitHub</a> <a href="https://twitter.com/freecodecamp" target="_blank" class="contact-details">Twitter</a> <a href="mailto:example@example.com" class="contact-details">Send a mail</a> <a href="tel:555-555-5555" class="contact-details">Call me</a> </div> <footer>**This is just a fake portfolio.. All the projects and contact details given are not real.. <p>&copy; Created for <a …