Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to solve method not allowed (Post) http error 405
Codes in views class UpdateVote(LoginRequiredMixin,UpdateView): form_class = VoteForm queryset = Vote.objects.all() def get_object(self,queryset=None): vote = super().get_object(queryset) user = self.request.user if vote.user != user: raise PermissionDenied('can not change another user vote') return vote def get_success_url(self): movie_id = self.object.movie.id return reverse('core:movie_detail', kwargs={'pk':movie_id}) def render_to_response(self, context, **response_kwargs): movie_id = context['object'].id movie_detail_url = reverse('core:movie_detail',kwargs={'pk':movie_id}) return redirect(to=movie_detail_url) -
Auto increment field of model in viewset during saving
Episode model has episode_number field, which has to be auto incremented while creating new episode. Every story will have episodes with episode_number field starting with one. How to do that? Now I user have to manually enter episode_number. story_id comes from url class Episode(models.Model): title = models.CharField(max_length=255) cover = models.ImageField(upload_to=upload_location) story = models.ForeignKey(Story, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) episode_number = models.IntegerField(null=True) class EpisodeView(viewsets.ModelViewSet): serializer_class = EpisodeSerializer permission_classes = [BasicAuthorizationPermissions] def get_queryset(self): story_id = self.kwargs['story_id'] return Episode.objects.filter(story=story_id) def perform_create(self, serializer): try: story = Story.objects.get(pk=self.kwargs['story_id']) except Story.DoesNotExist: raise NotFound if self.request.user != story.author: raise PermissionDenied return serializer.save(story=story) -
How to use (or open) args in python when some inputs are named and others are not?
I want to make a few user using create_superuser method. I am currently doing this: CustomUser.objects.create_superuser( 'amin@gmail.com', 'password', first_name='Amin', ) But I want to create more than one user. I did not want to give first_name, I would do this: a=[['user1@gmail.com', 'pass'], [user2@gmail.com', 'pass'], ] [CustomUser.objects.create_superuser(*user) for user in a] But in my case, in which I have a third input for which I need to put the name 'first_name', how can I do what I did in above? -
how to add quantity of products and update total in cart using django?
I have cart model and product model this code work fine to add each product one time into cart ,but I wanna be able to add quantity of a product and update the total after added but I'm not sure where I should add the quantity field any ideas ? My cart model :- class CartManager(models.Manager): def new_or_get(self, request): cart_id = request.session.get("cart_id", None) qs = self.get_queryset().filter(id=cart_id) if qs.count() == 1: new_obj = False cart_obj = qs.first() else: cart_obj = Cart.objects.new() new_obj = True request.session['cart_id'] = cart_obj.id return cart_obj, new_obj def new(self): return self.model.objects.create() class Cart(models.Model): products = models.ManyToManyField(Product, blank=True) subtotal = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = CartManager() def __str__(self): return str(self.id) cart views.py file:- def cart_home(request): cart_obj, new_obj = Cart.objects.new_or_get(request) context = { 'cart': cart_obj, } return render(request, "carts/home.html", context) def cart_update(request): product_id = request.POST.get('product_id') if product_id is not None: try: item = Product.objects.get(id=product_id) except Product.DoesNotExist: print("show message to user, product doesn't exist") return redirect("carts:cart") cart_obj, new_obj = Cart.objects.new_or_get(request) if item in cart_obj.products.all(): cart_obj.products.remove(item) else: cart_obj.products.add(item) return redirect("carts:cart") I update the subtotal of the cart using m2m_changed signal and then using pre_save signal to add a fixed shipping cost … -
How to authenticate or logged in the user account with admin permission
I'm new to with django application, I want to check/login a users account without password through admin permission. Is there any built-in feature in Django? Please help or guide me on how to do that? Many thanks! This kind of feature provided by laravel in PHP here is the sample code of PHP: <pre> use Illuminate\Http\Request; use App\User; public function loginAsUser(User $user){ auth()->guard('admin')->logout(); auth()->guard('web')->loginUsingId($user->id); return redirect(route('user.dashboard')); } </pre> -
Local File Directory for Django
I have followed the Digitalocean website tutorial for deploying a Django site. I did it all through the Command Prompt, so all of my files (settings.py, index.html) were accessed through there. Is there a local file directory that I can access so that I can edit all of my files in in a text editor? I also want to easily add CSS files and to the folders. I have to keep on editing on the command prompt. -
How to get episodes from exact story
I have episode, which is related with story(foreign key) with url router = routers.DefaultRouter() router.register('', StoryView, basename='stories') router.register('episodes', EpisodeView, basename='episodes') View: class EpisodeView(viewsets.ModelViewSet): I need to get episodes of story. How to do that is this case? -
Shared domain hosting or private hosting?
i want to develop website based on Django framework and I am unable to decide whether i will need private hosting or public hosting as I will have to install python and many more dependencies. I want to know type of hosting for django based sites. I tried contacting contacting hostgator and hostinger. -
Django and Subprocess: Development Server is Terminated on signal.SIGTERM
I am using subprocess.Popen in a Django application. I then store the pid in a database. The user can then send a rest request to /api/task/task.id/stop/ in order to kill the task. This all works fine, except that when I kill the subprocess the Django development server is also terminated. How do I go about killing the subprocess without killing the dev server? I start my process like this: process = subprocess.Popen(["nohup {} {} {}".format(settings.PYTHON, "task.py", task.id) ], shell=True ) task.pid = process.pid task.save() And I am terminating it like this: os.killpg( os.getpgid(task.pid), signal.SIGTERM ) -
settigns django template variable before extending a template
in jinja2 this is possibe {% set needs_youtube_library = False %} {% extends 'layouts/basic_layout.html' %} as passing a variable into an extends, does not work in a different way afaik. now with django templates, this doesn't even seem to be possible at all, or am I missing something? -
schema design for ecommerce product
I am exploring models in django where I am trying to create a model for e-commerce product. The schema that I have designed is follow for now from django.db import models class Category(models.Model): name = models.CharField(max_length=80) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE) total_stock = models.PositiveIntegerField(default=0) def __str__(self): return self.name class Attribute(models.Model): ''' attribute can be like color, material, size and many more ''' name = models.CharField(max_length=80) def __str__(self): return self.name class AttributeValue(models.Model): ''' Values for the selected attribute like for size attr the values can be Large, Medium, Small and etc ''' name = models.CharField(max_length=100) attribute = models.ForeignKey(Attribute, on_delete=models.CASCADE) price = models.DecimalField(decimal_places=2, max_digits=10) discount = models.DecimalField(decimal_places=2, max_digits=10) stock = models.PositiveIntegerField(default=0) def __str__(self): return self.name class ProductAttribute(models.Model): ''' Associate Particular attribute to Particular product ''' product = models.ForeignKey(Product, on_delete=models.CASCADE) attribute = models.ForeignKey(Attribute, on_delete=models.CASCADE) def __str__(self): return self.product.name class ProductImage(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) image = models.ImageField(upload_to = 'pic_folder/') def __str__(self): return self.product.name My question is when i researched for scalable e-commerce product design(scalable in terms of better table relation and covering most of the factors in e-commerce), i saw various tables like ProductVariant, ProductVariantImage, ProductOptions and etc. So i got confused on those terminology. … -
Trying to get email activation to work, but it fails
Trying to get this tutorial to work in my app: https://medium.com/@frfahim/django-registration-with-confirmation-email-bb5da011e4ef The 'uid' fails whether or not I include the .decode(). message = render_to_string('premium/activation_email.html', {'user':user, 'token': account_activation_token.make_token(user), #this fails both with the .decode() and without 'uid':urlsafe_base64_encode(force_bytes(user.pk)).decode(), }) mail_subject = 'Activate your membership account.' send_mail(mail_subject, message,'info@clinicpricecheck.com', [request.user.email]) These are the two errors: Reverse for 'activate' not found. 'activate' is not a valid view function or pattern name Then if I add .decode(): str object has no attribute decode() here is my urls.py with the activate tag: path('activate/<uidb64>/<token>/', views.activate, 'activate'), my activate view is exactly the same as the one in the tutorial -
Django - KeyError: 'profile' - Trying to save the user profile with DRF and Ajax
I'm trying to save the user profile data with DRF and Ajax but I have an error KeyError. I was reading the DRF docs, especifically this part: Writable Nested Representations that is what i want but, doesn't work for me. I hope you can help me this is my serializer.py class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ('user', 'avatar', 'dob', 'headline', 'country', 'location', 'cp', 'background', 'facebook', 'twitter', 'github', 'website',) read_only_fields = ('user', ) # I tried removing this part but, not work (In some forums say it) class UserSerializer(serializers.ModelSerializer): profile = ProfileSerializer() class Meta: model = User exclude = ('password', 'is_superuser', 'is_staff', 'is_active', 'user_permissions', 'groups', 'last_login',) read_only_fields = ('username', 'email', 'date_joined', ) def update(self, instance, validated_data): profile_data = validated_data.pop('profile') profile = instance.profile instance.username = validated_data.get('username', instance.username) instance.first_name = validated_data.get('first_name', instance.first_name) instance.last_name = validated_data.get('last_name', instance.last_name) instance.save() profile.avatar = profile_data.get('avatar', profile.avatar) profile.dob = profile_data.get('dob', profile.dob) profile.headline = profile_data.get('headline', profile.headline) profile.country = profile_data.get('country', profile.country) profile.location = profile_data.get('location', profile.location) profile.cp = profile_data.get('cp', profile.cp) profile.background = profile_data.get('background', profile.background) profile.facebook = profile_data.get('facebook', profile.facebook) profile.twitter = profile_data.get('twitter', profile.twitter) profile.github = profile_data.get('github', profile.github) profile.website = profile_data.get('website', profile.website) profile.save() return instance my views.py class ProfileRetrieveAPIView(generics.RetrieveUpdateDestroyAPIView): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = (IsAuthenticatedOrReadOnly, IsAuthenticatedOrReadOnly, ) lookup_field … -
I can't figure out how to serve Static Files using AWS Elasticbeanstalk
I have been working on this for two days straight and I can't figure it out. Any help would be appreciated. I'm using Python 3.6 running on 64bit Amazon Linux/2.7.7 of Elastic Beanstalk. This is my file structure: - analytics -- (a bunch of files that I think are irrelevant here) - db.sqlite3 - ecs_site -- __init__.py -- __pycache__ -- settings.py -- static -- css -- (a bunch of files - important) -- fonts -- (a bunch of files - important) -- images -- (a bunch of files - important) -- templates -- (a bunch of files that I think are irrelevant here) -- urls.py -- wsgi.py - manage.py - pages -- (a bunch of files that I think are irrelevant here) - requirements.txt In the settings.py file here's what's there: #STATIC_ROOT = os.path.dirname(__file__) STATIC_ROOT = os.path.join(BASE_DIR, "ecs_site", "static") #SITE_ROOT = os.path.dirname(os.path.realpath(__file__)) #STATICFILES_DIRS = [os.path.join(SITE_ROOT, 'static/')] STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] STATIC_URL = '/static/' #STATICFILES_DIRS = [os.path.join(BASE_DIR, 'ecs_site/static/'), os.path.join(BASE_DIR, 'ecs_site/static/images/'), #os.path.join(BASE_DIR, 'ecs_site/static/fonts/'), os.path.join(BASE_DIR, 'ecs_site/static'), os.path.join(BASE_DIR, 'ecs_site/static/images'), #os.path.join(BASE_DIR, 'ecs_site/static/fonts')] #STATICFILES_DIRS = [os.path.join(BASE_DIR, '/static/'), os.path.join(BASE_DIR, '/static/images/'), #os.path.join(BASE_DIR, '/static/fonts/'), os.path.join(BASE_DIR, '/static'), os.path.join(BASE_DIR, '/static/images'), #os.path.join(BASE_DIR, '/static/fonts')] In the configuration file here's what I have (set within the AWS EB console): -
ImproperlyConfigured Circular Import error Django2 Python3
I continue to get this error even after updating syntax to django2/python3 compatible. No mis-naming that I can see after checking repeatedly. I have tried using url instead of path and django 1 but this still does not fix the issue hackuta/urls.py: from django.urls import include, path from django.contrib import admin from . import views urlpatterns = [ path('admin/', admin.site.urls), path('',views.HomePage.as_view(),name='home'), path('first_app/',include('first_app.urls'),namespace = 'first_app'), path('first_app/',include('django.contrib.auth.urls')), path('test/',views.TestPage.as_view(),name='test'), path('thanks/',views.ThanksPage.as_view(), name='thanks') Error displayed when trying to migrate: File "/home/bbwslayer/.local/lib/python3.6/site-packages/django/urls/resolvers.py", line 593, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf 'hackuta.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. How do I fix this issue for a smooth migration? -
How do I sort the user model by fields in the profile model (1: 1)?
skill_note_reputation is a field in the Profile model that has a 1: 1 relationship with Profileuser. How do I sort user models by skill_note_reputation values? user_list = User.objects.all () Thanks for letting me know how to fix it -
How can i switch from one app to another in Django while passing data?
I am writing a Django application and i got stuck at this line of code in html in one of my Django apps: <a href="{% url "order:order_page" request.cart %} "> ORDER </a> I want the word 'ORDER' to redirrect to a html page in another app while passing the data from 'cart'. How can i do that? (order is the second application, 'order_page' is the name in its view which renders the second html page and 'cart' is a data that i want to pass to it, because i want to display it) -
Vue Nuxt Auth Login Token not stored
I'm currently using a Django backend (with Django Restframework and djangorestframework-simplejwt Package for JWT Token authentication) and Nuxt as the frontend with the Nuxt auth module. Here is my auth part in the nuxt.config.js: auth: { strategies: { local: { endpoints: { login: { url: '/api-token-auth/', method: 'post', propertyName: 'token' }, logout: false, user: { url: '/user/', method: 'post', propertyName: false } logout: { url: '/api-token-logout', method: 'post' }, }, tokenRequired: true, tokenType: 'JWT', } } }, Unfortunately the login doesn't work on the client side. My login view successfully returns: { "refresh":"eyJ0eXAiOiJKV1QiLCJhbhUjOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTU2OTc5MjM2NSwianRpIjoiZGZmYjAzNTAUjkwNGY5Zjk0ODdkYTYzMTQ2YmIxYWUiLCJ1c2VyX2lkIjoiZDMyOGMwYTAtMDU3YS00NDRkLWJlZjUtMTgwOGMyYmU0MzcwIn0.V4AHLHdKCAViVM-_vnOA3thOxgluJo0rP6S_qs8On2I", "access":"eyJ0eXAiOiJKV1jULHUhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTY5NzA2MjY1LCJqdGkiOiJjZDRhZjdjYHzjZTI0OTlmOTlhMTAzNjdkYTMzZWQxNSIsInVzZXJfaWQiOiJkMzI4YzBhMC0wNTdhLTQ0NGQtYmVmNS0xODA4YzJiZTQzNzAifQ.2I2LV3Lzu2WSFjA2OT_L4mXr5Qp0hb2RZF4mzuIYKP0" } I already tried to change the propertyName to access instead of token but also without success. But it has todo with that setting, because when I change to a different JWT package which only returns something like this (in the login view): { "token":"eyJ0eXAiOiJKV1jULHUhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTY5NzA2MjY1LCJqdGkiOiJjZDRhZjdjYHzjZTI0OTlmOTlhMTAzNjdkYTMzZWQxNSIsInVzZXJfaWQiOiJkMzI4YzBhMC0wNTdhLTQ0NGQtYmVmNS0xODA4YzJiZTQzNzAifQ.2I2LV3Lzu2WSFjA2OT_L4mXr5Qp0hb2RZF4mzuIYKP0" } Then it works just fine :/ -
Django + Apache + wsgi
I make app with Django and I wanna to host in my Raspberry Server, but chrome tell me Internall Error. Below my conf file: V-Host: <VirtualHost *:80> ServerAdmin gielas.g@gmail.com DocumentRoot /var/www/html/ptmeble ServerName www.ptmeble.pl ServerAlias ptmeble.pl CustomLog /var/www/logs/ptmeblepl.log combined ErrorLog /var/www/logs/ptmeblepl.log Alias /static /var/www/html/ptmeble/static <Directory /var/www/html/ptmeble/static> Require all granted </Directory> <Directory /var/www/html/ptmeble/ptmeblepl> <Files wsgi.py> Options FollowSymlinks </Files> </Directory> WSGIDaemonProcess ptmeble.pl python-path=/var/www/html/ptmeble/src:/home/pi/grzEnv/lib/python3.6/site-packages WSGIProcessGroup ptmeble WSGIScriptAlias / /var/www/html/ptmeble/ptmeblepl/wsgi.py </VirtualHost> # vim: syntax=apache ts=4 sw=4 sts=4 sr noet wsgi.py: WSGI config for ptmeblepl project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/ """ import os from dj_static import Cling from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ptmeblepl.settings') application = Cling(get_wsgi_application()) apache2/error.log: [Sat Sep 28 23:13:12.390528 2019] [core:notice] [pid 29063] AH00052: child pid 30066 exit signal Aborted (6) Fatal Python error: initfsencoding: unable to load the file system codec ModuleNotFoundError: No module named 'encodings' I don't know what I'm doing bad. Please someone help me -
Django Rest Framework Flatten nested self-referential objects
I have a problem with nested self-referential objects. I have field responses which is children of this Message. It looks like tree but I'd like do this in one level. Is it possible in a simple way? How can I solve this? It's my serializer: class RecursiveField(serializers.Serializer): def to_representation(self, value): serializer = self.parent.parent.__class__(value, context=self.context) return serializer.data class MessageSerializer(serializers.ModelSerializer): message_id = serializers.SerializerMethodField() sender_user_id = serializers.SerializerMethodField() sender_user_fullname = serializers.SerializerMethodField() sender_user_email = serializers.SerializerMethodField() read = serializers.SerializerMethodField() attachments = serializers.SerializerMethodField() responses = RecursiveField(many=True) class Meta: model = Message fields = [ 'message_id', 'sender_user_id', 'sender_user_fullname', 'subject', 'body', 'created_at', 'read', 'read_at', 'attachments', 'responses' ] My present result looks like this: { "results": [ { "message_id": 115, "sender_user_id": 1, "sender_user_fullname": "user1", "subject": "Temat", "body": "<p>Wiadomość</p>", "created_at": "2019-09-28T19:33:40.846822Z", "read": true, "read_at": "2019-09-28T19:35:58.889000Z", "attachments": {}, "responses": [ { "message_id": 116, "sender_user_id": 1, "sender_user_fullname": "user1", "subject": "Re: Temat", "body": "<p>Odpowiedź</p>", "created_at": "2019-09-28T19:35:52.485656Z", "read": true, "read_at": "2019-09-28T19:36:21.932000Z", "attachments": {}, "responses": [ { "message_id": 117, "sender_user_id": 1, "sender_user_fullname": "user1", "subject": "Re: Re: Temat", "body": "<p>Odpowiedź do odpowiedzi</p>", "created_at": "2019-09-28T19:36:20.717966Z", "read": true, "read_at": "2019-09-28T19:36:20.714495Z", "attachments": {}, "responses": [], } ] } ] } ] } I'd like sth like this: { "results": [ { "message_id": 115, "sender_user_id": 1, "sender_user_fullname": "user1", "subject": "Temat", "body": … -
How to show detailed view of phonebook?
I am trying to show a detailed view of the contacts stored in a phonebook. The PhoneBook(id, name) is one of my models which is a foreign key to model Contact(id, first_name, last_name, phone_number, phone_book). In my index page, there is a button which opens the phone book. After that, I want it such that the user may click on a phone book and the detailed view(first_name, last_name, phone_number) would be shown to them. In view.py, I have a function which captures all the phonebook, passes it through context(dict). In my template, I have used a for loop to go through all the phonebooks and print them. I am unable to direct the page to detailed view. How do I get the phonebook the user clicked on? And how to direct the page from ./view to ./detail # view.py def view_phone_book(request): all_phone_books = PhoneBook.objects.all() context = { 'all_phone_books': all_phone_books } return render(request, "CallCenter/view_phone_book.html", context) def detailed_view_phone_book(request): all_contacts = Contact.objects.all().filter(phone_book=phone_book_user_clicked_on) context = { 'all_contacts': all_contacts } return render(request, "CallCenter/detailed_view_phone_book.html", context) # urls.py urlpatterns = [ path('', index, name="index"), path('create/', create_phone_book, name="create"), path('add/', add_to_phone_book, name="add"), path('view/', view_phone_book, name="view"), path('detail/', detailed_view_phone_book, name="detailed_view") ] html5 <!--view_phone_book.html--> <table> <tr> <th>Phone Book</th> </tr> {% for phone_book … -
Image not displaying in django react framework
I am integrating an django e-commerce into rest react framework. On the products page I am able to view the product title, description, add to cart button, and slug but the image will not display. There are no errors in terminal or console.log. When i go to console.log I can see the image url, further when i go to my the MEDIA folder I can see the product image has been uploaded yet it is not displaying. I've included the files where i believe the issue is happening below. This line is suppose to display the image <Item.Image src={item.image} /> ProductList.js: import React from 'react' import axios from 'axios' import { Button, Container, Dimmer, Icon, Image, Item, Label, Loader, Message, Segment } from 'semantic-ui-react' import {productListURL} from "../constants"; class ProductList extends React.Component { state = { loading: false, error: null, data: [] } componentDidMount() { this.setState({loading: true}); axios .get(productListURL) .then(res => { console.log(res.data); this.setState({data: res.data, loading: false}); }) .catch(err =>{ this.setState({error: err, loading: false}); }); } render() { const {data, error, loading} = this.state; return ( <Container> {error && ( <Message error header='There was some errors with your submission' content={JSON.stringify(error)} /> )} {loading && ( <Segment> <Dimmer active inverted> <Loader … -
Printing to PDF Django & ReportLab
I currently have this view in Django, which renders a bunch of records on my html page perfectly def patient_page(request, id): pat = models.patient.objects.get(pk=id) # Goes to patient models returns pk according to page rec = models.record.objects.all().filter(patient_assign__pk=id).order_by('-date') return render(request=request, template_name = 'main/patient_page.html', context = {"pats":pat, "rec":rec } ) I also have this code which prints perfectly, I could easily insert a variable. def write_pdf_view(textobject): #Need to play with filename. response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'inline; filename="txt_obj.pdf"' buffer = BytesIO() my_canvas = canvas.Canvas(buffer) # Create textobject(s) textobject = my_canvas.beginText(30 * mm, 65 * mm) textobject.setFont('Times-Roman', 8) textobject.textLine(text="+ Hello This text is written 30mm in and 65mm up from the mark") my_canvas.drawText(textobject) title = "this is my title" my_canvas.setTitle(title) my_canvas.showPage() my_canvas.save() pdf = buffer.getvalue() buffer.close() response.write(pdf) return response My Question, does anyone have an idea of how I might render to pdf AND print to PDF, i.e. next to the record on the html I have a print button which currently runs my print to pdf script. -
How to make virtualenv Django server work? // 'missing attribute' according to command prompt
after wasting saturdays eve googling for a solution to finally make a Django server work, i need your assistance.. I first of all want to set up my project in that way that http://127.0.0.1:8000/ redirects me to the index.html site. But somehow I am not able to run the Django server within my virtualenv (access denied). I handled error over error in the past few hours (inserted a Secret key, inserted silenced_system_checks since E408/09/10 occured as errors before the current error) and here I stuck now. I am not capable to understand the prompt error at all. I assume that Django wants to start the server but can't find a file/html to return? Console output: Console output + project structure Settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = "censored" ALLOWED_HOSTS = [''] SILENCED_SYSTEM_CHECKS = [ 'admin.E408', 'admin.E409', 'admin.E410', ] DEBUG = 'TRUE' ROOT_URLCONF = 'dasocc_site.urls' INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dasocc_app', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, '/dasocc_site/dasocc_app/templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] STATIC_URL = '/static/' urls.py // dassocc_app dir from django.urls … -
How to make a website based on python program?
I made a python program that changes outputs every week (this week it might output 1, next week 2, etc). I wanted to make a website that had the result of the python program. I had a few ideas on how to make it, but didn't know which way was the best and could work. I don't need to make a big website, just something that could run with local files. Here are my ideas Write the output of the program onto a text file, and use Javascript to read the file, and display it on a website. Make some skeleton HTML code, and write the output to the .html file using python. Use django (I've never used it before, so I don't know if it will work) I don't need the program to be run on the website, since the program doesn't need user input. All I need is to get the output from python onto a website (.html). There would be 50 lines in the text file if I used that method. I tried the first method, but reading from the file didn't work (it couldn't access the text file, and said that XMLHttpRequest was deprecated). I looked …