Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Javascript and python real-time audio stream
i want to record audio in the client's browser and send it in real-time to server to process the audio stream in python. I found webRTC which is usefull for real-time but i can't find any example. What's the best solution ? Thank you! -
Django receive multiple files upload
<input type='file' name="images[]" /> files = request.FILES['images'] print(files[0].name) I have trouble to get multiple files upload in Django 3.0 Can anyone tell me why I got MultiValueDictKeyError -
Communicate with other Django Servers using Docker
I'm new to Docker and want to build a Django webapp. The app shall run on multiple computers with a central server, which basically run all the same image. The main point is that there will be computing tasks which I want to distribute over the servers. So now I wonder how I would communicate via Django between the different Servers. I know about basic Distributed styles and Architecture protocols, but how do I expose the local network to the docker image network layer, so that I can communicate on custom ports and IPs in my network? I read about Docker Swarm, but how to forward the Addresses to each Django Server? What is a best/recommended/efficient way to distribute tasks between my Django Apps with Docker? -
Django cannot create or render comments
Hi have this structure to handle users posts and comments my post model is from django.db import models from django.contrib.auth.models import User class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=0) profile = models.ForeignKey('users.Profiles', on_delete=models.CASCADE, null=True, default=1, blank=True) title = models.CharField(max_length=100, blank=True, null=True) desc = models.CharField(max_length=1000, blank=True, null=True) photo = models.ImageField(upload_to='posts/photos') created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) def __str__(self): return '{} by {}'.format(self.title ,self.user) and my comment model from django.db import models from posts.models import Post as Post from django.contrib.auth.models import User class Comment(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE, null=True, default=1, blank=True) name = models.CharField(max_length=20,blank=True, null=True) email = models.EmailField(max_length=20,blank=True, null=True) body = models.TextField(max_length=200,blank=True, null=True) created = models.DateTimeField(auto_now_add=True,blank=True, null=True) updated = models.DateTimeField(auto_now=True,blank=True, null=True) active = models.BooleanField(default=True,blank=True, null=True) class Meta: ordering = ('created',) def __str__(self): return 'Comment by {} on {}'.format(self.name, self.post) im able to create post on admin from posts.models import Post as Post from django.contrib import admin from comments.models import Comment @admin.register(Comment) class CommentAdmin(admin.ModelAdmin): list_display = ('name', 'email', 'post', 'created', 'active') list_filter = ('active', 'created', 'updated') search_fields = ('name', 'email', 'body') can create my post and persist on db now i have this function to persist the comment on front from django.shortcuts import render from .models import Post, Comment from .forms import EmailPostForm, CommentForm … -
Handling Django File from Model
I've created a basic model in Django and want to do some processing on a file in the background before sending to the template. At the moment I'm getting errors about a FileDescriptor object, which I cannot seem to find methods or attributes for, I was expecting something I can get a url or file contents from: class Projects(models.Model): image = models.ImageField(upload_to='uploads/') title = models.CharField(max_length = 200) desc = models.TextField() date_posted = models.DateTimeField() notebook = models.FileField(upload_to='notebooks/') I'd like to perform some processing on the file object in a generic view, but I don't really understand what is getting passed through. How can I just get the file url, or access to the actual contents of the file? Seem unable to get .url or .file attributes as I expect from FileField. class ProjectListView(ListView): model = Projects template_name = 'project_list.html' context_object_name = 'projects' def get_context_data(self, **kwargs): j = Projects.notebook.url context = super().get_context_data(**kwargs) ## insert functions to process object j ## context['notebook'] = j return context Thanks! -
How to add programmatically an image file to FileField from mezzanine.core.fields
I used Mezzanine==4.3.1 with django . I had a model when I used the feld FileField in order to get their facilities in the admin view, adn get a good user expieriece uploading photos from django.db import models from mezzanine.core.fields import FileField from mezzanine.utils.models import upload_to, AdminThumbMixin from django.contrib.auth.models import User # Create your models here. class Person(models.Model): full_name = models.CharField(max_length=256, null=True, blank=True) passport = models.CharField(max_length=128, null=True, blank=True) birth_day = models.CharField(max_length=128, null=True, blank=True) #models.DateField(null=True, blank=True) address = models.TextField(null=True, blank=True) gender = models.CharField(max_length=128, choices=(('F', 'Female'), ('M', 'Male'), ('U', 'Ungendered'))) city = models.CharField(max_length=128, null=True, blank=True) country = models.ForeignKey(Country, null=True, on_delete=models.CASCADE) image = FileField("Image", upload_to=upload_to("api.models.image", "models"), format="Image", max_length=255, null=True, blank=True) But I would like to create a command to upload quickly a bunch of data of person from a csv and also upload the corresponding photos. I copied the photos to settings.MEDIA_ROOT in folder of photos uploaded. And I would like programmatically add the corresponding photo for each person. I try to test with python manage.py shell >>> from apps.api.models import Person >>> from django.conf import settings >>> from os.path import isfile, join >>> p1 = Person.objects.filter(first_name="Amanda Vega") >>> p1[0].image.save('amanda1', open(join(settings.MEDIA_ROOT,'uploads/image/estudio_50_photos_mod/1/profesional/_Y2B1035.JPG')).read()) Traceback (most recent call last): File "<console>", line 1, in <module> File … -
How not to deploy under git control db.sqlite3 file
In my django project, db.sqlite3 is under git control(I chose to do so). However when deploying the project to AWS server(using elastic beanstalk), I would like not to deploy db.sqlite3 file. Database setting is configured inside settings module so even db.sqlite3 file is deployed to the server, the project won't reference db.sqlite3 file. I will probably work fine but I do not want to deploy something unnecessary(db.sqlite3) to be deployed to the server. How can I not to deploy db.sqlite3 under git control? -
how to use verbose name in foreign key django admin?
how to use verbose_name in foreign key django admin?? class ParentsProfile(models.Model): Fathers_Firstname = models.CharField(verbose_name="Firstname", max_length=500,null=True,blank=True) Fathers_Middle_Initial = models.CharField(verbose_name="Middle Initial", max_length=500,null=True,blank=True, help_text="Father") Fathers_Lastname = models.CharField(verbose_name="Lastname", max_length=500,null=True,blank=True) Educational_AttainmentID_Father = models.ForeignKey(EducationalAttainment,on_delete=models.CASCADE,null=True,blank=True) I've already try to use Educational_AttainmentID_Father = models.ForeignKey("EducationalAttainment",EducationalAttainment,on_delete=models.CASCADE,null=True,blank=True) but it doesn't work -
Having trouble restricting editing to the owner of the profile in Django while using a custom user model
I am new to development and Django. This is my first project from scratch. I am also new on here, so if I don't ask a question correctly, please give me some feedback rather than downvoting. So, I decided to go with a custom user model so I could customize the registration page and require users to submit a photo during registration. I am not sure if I needed to go through all this just for that, and I am finding out that it's more difficult to manage a custom user class. Right now, I am attempting to only allow the current logged in user to be able to edit their own info, not anyone else's. I totally know how to do this through the normal User model, but I can't figure out how to do this through the custom user model path. The only way I know how to do this is to create a separate model that has a foreign key to my Profile model, 'owner', and compare the two ID's when the current user try's to edit someone else's profile. I looked around a couple different related questions, and I couldn't come up with a solution either. … -
List of contacts per User when extending AbstractUser
I want to create a custom user model with some extra fields, among which a contact list of other users. I would like to extend AbstractUser instead of creating a new model with a one-to-one link to User. from django.contrib.auth import get_user_model from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): a_custom_field = models.IntegerField(default=0) # per-user contact list contacts = models.ManyToManyField(get_user_model()) This code doesn't work. Throwing this error during makemigrations. django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'users.CustomUser' that has not been installed The error totally makes sense, but what's the right way to achieve this? -
Django access media/uploaded images from template
This is Post model class Post(models.Model): objects = models.Manager() # The default manager. published = PublishedManager() # Our custom manager. STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') thumbnail = models.ImageField(name="photo", upload_to='thumbnails/', null=True, default='default.png') class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) This is my view for it class PostListView(ListView): queryset = Post.published.all() context_object_name = 'posts' paginate_by = 3 template_name = 'blog/post/list.html' def get_context_data(self, **kwargs): obj = Settings.objects.get(pk=1) context = super().get_context_data(**kwargs) context["blog_name"] = getattr(obj, "blog_name") context["footer"] = getattr(obj, "footer") context["description"] = getattr(obj, "description") context["keywords"] = getattr(obj, "keywords") return context I already tested uploading images and such and they work fine and I can even load them by manually specifying the path (ie: /uploads/thumbnails/XXXXX.jpg) However I need to access them via my template with something like {{post.thumbnail.url}} -
File Structure Issue When Deplying Django React App to Heroku
I have a Django React project that I created from a tutorial. I have played around with the Procfile and wsgi file quite a bit, but cannot seem to get the files correctly written to navigate my project structure. I can run my project locally with two terminal tabs. One is python manage.py runserver in lead_manager/leadmanagerproject The other tab is npm run dev in lead_manager/leadmanagerproject/frontend I haven't even gotten to the React side of things, just trying to get the Django part of the project working and I can't seem to get the Procfile and wsgi file done correctly. Any help/advice is greatly appreciated! Let me know what other information might help - I am new to Stack Overflow. Project Structure lead_manager | .gitignore | .babelrc | db.sqlite3 | requirements.txt | runtime.txt | package-lock.json | package.json | Pipfile | Pipfile.lock | Procfile | webpack.config.js | \---staticfiles | \---leadmanagerproject | db.sqlite3 | manage.py | +---accounts | | admin.py | | apps.py | | api.py | | models.py | | serializers.py | | tests.py | | urls.py | | views.py | | __init__.py | | | +---migrations +---frontend | | admin.py | | apps.py | | models.py | | tests.py | | … -
Sending a Python Dictionary Through a Single POST method in Django REST Framework
I have been attempting to implement this method several ways in which seems like it should be pretty straightforward. I have a web scraper that scrapes stock data and stores it into a Python dictionary in a python script. This then makes a post request to my Django API which is handled under my views using GenericAPIView. This post request sends a QueryDict and I am able to post a single instance but not multiple at once. Yes, I have said many=True on my serializer and attempted to override these methods. Each solution I have made is inefficient and I am frustrated not finding a clear and simple solution. This is my first time working with the Django Rest Framework so bear with me and thanks for your help in advance! CryptoView.py (Mostly followed a tutorial on Medium.com to improve my method) class CryptoView(ListCreateAPIView): queryset = Crypto.objects.all() serializer_class = CryptoSerializer def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) class SingleCryptoView(RetrieveUpdateDestroyAPIView): queryset = Crypto.objects.all() serializer_class = CryptoSerializer Cryptotest.py crypto = { "id": [], "name": [], "price": [], "change": [], "percentChange": [] } # For Loop - Yahoo Finance requires us to … -
Why does OneToOne relationship cause long load - very slow Django?
I've added a OneToOneField to my models.py. Once I do this my detail view takes almost a minute to load when before it took less than a second. See below list for reference method flowchart of what Django docs says happens in a DetailView. Whatever is happening its happening after render_to_response (last one) and get_success_url (not listed). I added a print('HELLO') to both. I see render_to_response's HELLO immediately. Chrome spins/loads for a minute or two. And then I see get_success_url's HELLO. What happens between render_to_response and get_success_url? Method Flowchart setup() dispatch() http_method_not_allowed() get_template_names() get_slug_field() get_queryset() get_object() get_context_object_name() get_context_data() get() render_to_response() -
Why does the 'setAttribute' function not work in javascript?
I am working on a django project and have a simple javascript inline code and want to disable a button and enable another one when some condition meets. I tried three method to do that but when condition meets and i expect to run code, no one work for me and nothing happend. here is this part of my code: {% else %} <script > document.getElementById('prevBtn').removeAttribute('disabled'); document.getElementsByTagName('button')[0].disabled='disabled'; document.getElementById("nextBtn").setAttribute('disabled','disabled'); </script> <h2 > finished <h3> THANK YOU FOR YOUR TIME <br> BYE! </h3> </h2> {% endif %} <br> <div><br> <button type="submit" id="nextBtn" name="nextBtn">next </button> <br><br> <button type="button" id="prevBtn" name="prevBtn" disabled>previous</button> </div> Before i submit this question i read some similar questions and all suggest above approachs as answer. i'm confused what is wrong with my code. thank in advance for any help. -
Django Serializer relation problem : Got KeyError when attempting to get a value for field
I have a two model which one of them includes relation to the other like this: class RapicModel(models.Model): app = models.ForeignKey(RapicApp, on_delete=models.CASCADE, blank=True, related_name = "app") name = models.CharField(max_length=20, blank=False, default='undefined') class Field(models.Model): model = models.ForeignKey(RapicModel, on_delete=models.CASCADE, blank = True, related_name='rapicfields') fieldtype = models.ForeignKey(FieldType, on_delete=models.CASCADE, blank=False) name = models.CharField(max_length=20, blank=False, default='undefined') max_length = models.IntegerField(blank=False, default=30) blank = models.BooleanField(blank=False, default=False) default = models.CharField(max_length=200, blank=True, default='undefined') And these are the serializers: class RapicModelSerializer(serializers.ModelSerializer): rapicfields = FieldSerializer(many=True) class Meta: model = RapicModel fields = ('id','app', 'name', 'rapicfields') def create(self, validated_data): field_list = validated_data.pop('rapicfields') rapicmodel = RapicModel.objects.create(**validated_data) for single_field in field_list: Field.objects.create(model=rapicmodel, **single_field) return rapicmodel class FieldSerializer(serializers.ModelSerializer): class Meta: model = Field fields = ('id','model', 'fieldtype', 'name', 'max_length', 'blank', 'default') When I try to post a new rapicmodel with some fields in it with this JSON: { "app": 7, "name": "myfirstmodel", "rapicfields": [ { "fieldtype": 1, "name": "myfirstfield" }, { "fieldtype": 1, "name": "mysecondfield" } ] } I am getting this response: KeyError at /rapicmodel/ "Got KeyError when attempting to get a value for field `rapicfields` on serializer `RapicModelSerializer`.\nThe serializer field might be named incorrectly and not match any attribute or key on the `dict` instance.\nOriginal exception text was: 'rapicfields'." I really don't understand … -
Hide button when item is in the cart
I have got a product page where I have a button to add item to the cart and to remove it. <a href="{{ object.get_add_to_cart_url }}" class="btn btn-primary btn-md my-0 p" style="margin: 0;"> Add to cart <i class="fas fa-shopping-cart ml-1"></i> </a> <a href="{{ object.get_remove_from_cart_url }}" class="btn btn-danger btn-md my-0 p"> Remove from cart </a> I want to hide the remove button, until the item is in the cart, what if statement would have to be use to achieve that? Here's my function to add item to the cart: @login_required def add_to_cart(request, slug): item = get_object_or_404(Item, slug=slug) order_item, created = OrderItem.objects.get_or_create( item=item, user=request.user, ordered=False ) order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] # check if the order item is in the order if order.items.filter(item__slug=item.slug).exists(): order_item.quantity += 1 order_item.save() messages.info(request, "This item quantity was updated.") return redirect("core:order-summary") else: order.items.add(order_item) messages.info(request, "This item was added to your cart.") return redirect("core:order-summary") else: ordered_date = timezone.now() order = Order.objects.create( user=request.user, ordered_date=ordered_date) order.items.add(order_item) messages.info(request, "This item was added to your cart.") return redirect("core:order-summary") -
Deserializing model with multiple parent models throws "...object has no attribute..." error
First of all sorry for the long post. I'm just trying to really break down the issue. I'm using the django-moderation and django-comments-xtd packages to implement moderation for comments. I use the following model on top: class VotableComment(XtdComment): vote_score = models.IntegerField(db_index=True, default=0) (...) The XtdComment itself inherits from the Comment model from the django-comments package. Behind the hood all this works through OneToOneFields i.e.: migrations.CreateModel( name='XtdComment', fields=[ ('comment_ptr', models.OneToOneField(auto_created=True, primary_key=True, parent_link=True, serialize=False, to='django_comments.Comment', on_delete=models.CASCADE)), (...) migrations.CreateModel( name='VotableComment', fields=[ ('xtdcomment_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='django_comments_xtd.XtdComment')), (...) This means that a VotableComment object should have both comment_ptr and xtdcomment_ptr as attributes. The error comes when django-moderation tries to set the changed_object attribute (which refers to the VotableComment object) of its ModeratedObject model which is a SerializedObjectField field. Then I get: The underlying issue happens when deserializing and trying to set the values of the VotableComment object's fields obtaining the value from its parent models. In particular the comment_ptr field: As you can see there is a problem when trying to set comment_ptr with value <Comment: :...> on the VotableComment model because later on related_descriptors.py is first trying to resolve all the inherited_pk_fields. There are two of them which come from the … -
Docker-compose Django Supervisord Configuration
I would like to run some programs when my django application running. That's why I choose supervisord. I configured my docker-compose and Dockerfile like : Dockerfile: FROM python:3.6 ENV PYTHONUNBUFFERED 1 # some of project settings here ADD supervisord.conf /etc/supervisord.conf ADD supervisor-worker.conf /etc/supervisor/conf.d/ CMD ["/usr/local/bin/supervisord", "-c", "/etc/supervisord.conf"] docker-compose: api: build: . command: bash -c "python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" restart: unless-stopped container_name: project volumes: - .:/project ports: - "8000:8000" network_mode: "host" supervisord.conf [supervisord] nodaemon=true [include] files = /etc/supervisor/conf.d/*.conf [supervisorctl] [inet_http_server] port=*:9001 username=root password=root So my problem is when I up the docker-compose project and other dependencies (postgresql, redis) works fine but supervisord didn't work. When I run "supervisord" command inside container it's working. But in startup, It don't work. -
create() takes 1 positional argument but 2 were given
I'm using Django and allauth trying to get a signup page working but for some reason it does not work. Whenever I have entered all the sign up data that's required and press Create an account it gives me this error; TypeError at /accounts/signup/ create() takes 1 positional argument but 2 were given This is my signup script; {% extends "account/base.html" %} {% load i18n %} {% load crispy_forms_tags %} {% block head_title %}{% trans "Signup" %}{% endblock %} {% block content %} <main> <div class="container"> <section class="mb-4"> <div class="row wow fadeIn"> <div class='col-6 offset-3'> <h1>{% trans "Sign Up" %}</h1> <p>{% blocktrans %}Already have an account? Then please <a href="{{ login_url }}">sign in</a>.{% endblocktrans %}</p> <form class="signup" id="signup_form" method="post" action="{% url 'account_signup' %}"> {% csrf_token %} {{ form|crispy }} {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} <button class='btn btn-primary' type="submit">{% trans "Sign Up" %} &raquo;</button> </form> </div> </div> </section> </div> </main> {% endblock %} -
How to fix NoReverseMatch? Reverse for 'porumbei' not found. 'porumbei' is not a valid view function or pattern name
I'm trying to edit some objects in django but when I'm accessing the view for editing it says that reverse not found. I've read almost all articles about noreversematch but none answered to my question. I'm new to django and maybe that could be the reason. Can anyone help me to fix that? Thanks! My code bellow. My view: @login_required(login_url='/auth/login/') def editareporumbei(request, pk): """ Pagina editare informatii porumbel """ global semi_frati sts = StatusPorumbei.objects.all() porumbel = get_object_or_404(Porumbei, pk=pk) if porumbel.crescator != request.user: raise PermissionDenied() descendenti = Perechi.objects.filter(Q(mascul=porumbel) | Q(femela=porumbel)) if porumbel.tata and porumbel.mama: frati = Porumbei.objects.filter(Q(Q(tata=porumbel.tata)) & Q(Q(mama=porumbel.mama))).exclude(serie_inel=porumbel) rude_tata = Porumbei.objects.filter(Q(Q(tata=porumbel.tata)) & ~Q(Q(mama=porumbel.mama))) rude_mama = Porumbei.objects.filter(~Q(Q(tata=porumbel.tata)) & Q(Q(mama=porumbel.mama))) vitregi = rude_tata | rude_mama semi_frati = vitregi.distinct() else: frati = None semi_frati = None try: rating_porumbel = Rating.objects.get(porumbel=porumbel) except Rating.DoesNotExist: rating_porumbel = None if request.method == "POST": form = AdaugaPorumbel(request.POST, request.FILES, instance=porumbel) if form.is_valid(): obj = form.save(commit=False) obj.crescator = request.user obj.save() return redirect('/porumbei/vizualizare') else: form = AdaugaPorumbel(instance=porumbel) context = { 'form': form, 'porumbel': porumbel, 'descendenti': descendenti, 'rating_porumbel': rating_porumbel, 'sts': sts, 'frati': frati, 'semi_frati': semi_frati, } template = loader.get_template("editare-porumbei.html") return HttpResponse(template.render(context, request)) My urls: urlpatterns = [ path('porumbei/vizualizare/', porumbei.views.viewpigeons, name='allpigeons'), path('porumbei/adaugare/', porumbei.views.porumbelnou, name="porumbelnou"), path('porumbei/editare/<int:pk>/', porumbei.views.editareporumbei, name='editareporumbei'), ] Template: <a href="{% url 'editareporumbei' … -
List objects of logged current user
I would like to ask how I could list all objects of logged current user via class based view in django. I have two apps in the project. One is called users and the other one is badminton. users/models.py from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) badminton/models.py from django.db import models from users import models as users_models class Player(models.Model): name = models.OneToOneField(users_models.Profile ,null=True, on_delete=models.CASCADE) matches_played = models.IntegerField(default=0, blank=True, null=True) class Match(models.Model): player_home = models.OneToOneField(Player, null=True, on_delete= models.SET_NULL, related_name='player_home') player_away = models.OneToOneField(Player, null=True, on_delete= models.SET_NULL, related_name='player_away') How I can access all matches of logged user via queryset? Thank you for your help! -
Cannot find template url in django
I have this project structure, foo_project - templates - base.html - photo_list.html - photo_create.html - foo_project - __init__.py - asgi.py - settings.py - urls.py - wsgi.py - apps - photo - __init__.py - admin.py - apps.py - models.py - tests.py - urls.py - views.py In apps.photo.views.py, from django.shortcuts import render from django.views.generic.list import ListView from django.views.generic.edit import UpdateView, CreateView, DeleteView from django.views.generic.detail import DetailView from .models import Photo class PhotoList(ListView): model = Photo template_name_suffix = '_list' class PhotoCreate(CreateView): model = Photo field = ['title', 'body', 'created', 'image'] template_name_suffix = '_create' success_url = '/ in foo_project/settings.py from os.path import abspath, dirname, join BASE_DIR = dirname(dirname(abspath(__file__))) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.template.context_processors.media', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] In foo_project/urls.py, from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static urlpatterns = [ path('', include('apps.photo.urls')), ] photo.urls, from django.conf import settings from django.conf.urls.static import static from django.urls import path from .views import PhotoList, PhotoCreate, PhotoDelete, PhotoDetail, PhotoUpdate app_name = 'photo' urlpatterns = [ path('', PhotoList.as_view(), name='index'), path('create/', PhotoCreate.as_view(), name='create'), ] When I hit the localhost:8000, it cannot find my template photo/photo_list.html, but I don't see anything missing. … -
TemplateDoesNotExist at / error in Django
I'm new to Django, and trying to create my first project. I tried to resolve the above mentioned error, spent hours banging my head against the wall, but was unable to correct it.. Given below are the relevant files. I guess it must be a small thing that I am missing, but unable to pin point it. Views.py: from django.shortcuts import render from django.http import HttpResponse, JsonResponse from datetime import timedelta def home(request): if request.GET.get('type') == 'formdata': options = {'fruits': [], 'vendors': [], 'release_version': []} try: options['fruits'] = ['Mango', 'apple', 'banana'] options['vendors'] = ['Amazon', 'flipkart', 'myntra'] options['release_version'] = ['2015','2016','2017','2018'] today = datetime.today() options['end_date'] = today.strftime('%Y-%m-%d') last_week_date = today - timedelta(days=7) options['start_date'] = last_week_date.strftime('%Y-%m-%d') return JsonResponse({'options': options}) except: return JsonResponse({'message': 'An error occured while getting form data'}) return render(request, 'index.html') else: return render(request, 'index.html') Urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home') ] The index.html is the template I want the urls.py to point to, and is in the templates/project_name folder in my project. I have also set the TEMPLATES_DIR in the settings.py. I wonder where I am going wrong. Any help is appreciated. -
Django- how to use server time in views when retrieving data from different timezone?
I have set a timezone in America in settings.py. All data are set in American Timezone in database. If today's date in America is 14 march but in Asia it's 15 March. So if I retrieve today's object from Asia it's not showing anything because it is stored in American time which is 14 march and in Asia it's 15. So it is not showing anything. So how to use server time in views.py so that it will retrieve object based on server time no matter where you stay