Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django static path of the image is not working
I am trying to load the static path of the image which is not working but the static path of the css files are working perfectly . I have tried every different way but still getting 404 this is i am trying to access the image which is inside the folder of ip in static folder <div class="col-auto"> <img src="{% static 'ip/best.png' %}"/> </div> I have load the static block above {% load static %} and the settings.py configuraion of static url STATIC_URL = '/static/' STATICFILES_DIRS=[ os.path.join(BASE_DIR,'static') ] -
Multiple images in Django + Postgres, by storing filepaths in ArrayField of CharField, or separate model for images, with foreignKey to product?
I'm creating an ecommerce site with Django and Postgres, where products will have multiple images. As I found out, using the ArrayField that Postgres provides, is not possible to store ImageField or FileField, it only works for integers, text etc. A very common approach to store multiple images per product, is to create another model called image, with a single ImageField, and a foreighKey to the product. But I am sceptical to use this, as I will need additional Get Requests to fetch the images. I am afraid these additional fetches will make my site slower. My calculation is, one Get Request to get all the products, which contain names, descriptions, and once I have their id's, I call another GET request to get the images, which reference to those foreign key id's in images. I had another idea, since the Postgres ArrayField, works fantastic using it as array of CharField, to just store the file paths to the images, to the media folder where I am storing them. I searched a lot all over stackoverflow and google, but I don't find anyone else mentioning this approach, although it makes sense to me. So, my question is: Is storing the … -
Django blog.models.Post.DoesNotExist: Post matching query does not exist
I am currently trying to add an Ajax to my like button to prevent refreshing, I am not an expert I am trying to learn from mistakes and small training exercises like this one but I am getting an error: blog.models.Post.DoesNotExist: Post matching query does not exist. and I don't know where the error is coming from Here is the views.py def like_post(request): user = request.user if request.method == 'POST': post_id = request.POST.get('post_id') post_obj = Post.objects.get(id=post_id) if user in post_obj.liked.all(): post_obj.liked.remove(user) else: post_obj.liked.add(user) like, created = Like.objects.get_or_create(user=user, post_id=post_id) if not created: if like.value == 'Like': like.value = 'Unlike' else: like.value = 'Like' like.save() context = { 'post_id': post_id, } if request.is_ajax: html = render_to_string('blog/like_section.html',context, request=request) return JsonResponse({'form': html}) return redirect('blog:post-detail', slug=post_obj.slug) Here is the template like-section.html <form action="{% url 'blog:like-post' %}" method="POST" class="like-form" id="{{post.id}}"> {% csrf_token %} <input type="hidden" name="post_id" value='{{post.id}}'> {% if user not in post.liked.all %} <button id="like" class="bwhite sm-button" style="color: grey; background-color: Transparent; background-repeat:no-repeat; border: none; cursor:pointer; overflow: hidden; outline:none;"> <i class="far fa-thumbs-up" type="submit"></i> </button> {% else %} <button id="like" class="bwhite sm-button" style="color: blue;background-color: Transparent; background-repeat:no-repeat; border: none; cursor:pointer; overflow: hidden; outline:none;" > <i class="far fa-thumbs-up" type="submit"></i> </button> {% endif %} <div class="like-count{{post.id}}">{{ post.num_likes }} Likes</div> </form> … -
JavaScript - Display a bar graph with dictionary in ECharts
is there a way to display a bar graph with given source dataset in one dictionary? I'm using ECharts and it's hard to understand their documentation :( My data: {"TCP": 1003, "UDP": 232, "ICMP": 4, "IP": 0} And my option is right there: var option = { dataset: { source : myChart }, title: { text: 'Protocol' }, xAxis: { data: ['TCP', 'UDP', 'ICMP', 'IP'] }, yAxis: { data: [0, 100, 300, 500, 700, 900, 1100] }, series: [{ name: 'Protocol', type: 'bar', }] }; Thanks a lot for any advice ! @EDIT So the problem is in my JavaScript code... I can't access values, what's the problem ? const proto = JSON.parse(document.getElementById('proto').textContent); console.log(proto); console.log(proto['IP']); I forgot to mention proto element is from django variable {{ proto|json_script:"proto" }} @EDIT2 Only working is to put a variable with safe tag, is it okay? Or may it be vulnerable to xss? var proto = JSON.parse('{{ proto|safe }}'); -
cant create filters in django project
i want add filter in the project but this error comes to me in CMD AttributeError: module 'rest_framework.filters' has no attribute 'DjangoFilterBackend' the Project Name = frame the ProjectApp Name = framework Views.py from typing import Tuple from django.shortcuts import render from .serializer import TaskSerializers from rest_framework import viewsets from .models import Task from rest_framework import filters import django_filters # Create your views here. class myviewset(viewsets.ModelViewSet): queryset = Task.objects.all() serializer_class = TaskSerializers filter_backends =(filters.DjangoFilterBackend,filters.OrederingFilter) filter_fields=('completed',) ordering = ('-date_created') Installed app: INSTALLED_APPS = [ 'framework', 'rest_framework', 'django_filters', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] -
Can not change parent abstract model name in Django
In part of my Django server I had this models: class Review(models.Model): time = models.DateTimeField(auto_now_add=True) ip = models.GenericIPAddressField() class Meta: abstract: True class Click(Review): view_delay = models.DurationField() ad = models.ForeignKey( to=Ad, related_name='clicks', on_delete=CASCADE ) class View(Review): ad = models.ForeignKey( to=Ad, related_name='views', on_delete=CASCADE ) But now I want to change the abstract class Review to BaseAdEvent due to code readability. When I want to Make new migrations I get following questions and I answer all of them with y(yes): Did you rename the advertising.Review model to BaseAdEvent? [y/N] y Did you rename click.review_ptr to click.baseadevent_ptr (a OneToOneField)? [y/N] y Did you rename view.review_ptr to view.baseadevent_ptr (a OneToOneField)? [y/N] y Migrations for 'advertising': advertising/migrations/0009_auto_20201114_1828.py - Rename model Review to BaseAdEvent - Rename field review_ptr on click to baseadevent_ptr - Rename field review_ptr on view to baseadevent_ptr but when I want to migrate the migrations I get following error: django.core.exceptions.FieldError: Auto-generated field 'review_ptr' in class 'View' for parent_link to base class 'Review' clashes with declared field of the same name. Is there anyway I could rename my parent model other than deleting the previous migrations and drop all tables? -
PostgreSQL: How to set up individual roles on PythonAnywhere (for Django)?
I am running my Django app on PythonAnywhere. The postgreSQL database was created with something like createdb -h xxx.postgres.eu.pythonanywhere-services.com -p 10077 -U super postgres It looks like this: postgres=# \du List of roles Role name | Attributes | Member of -----------------------+------------------------------------------------------------+----------- postgres | Superuser, Create role, Create DB, Replication, Bypass RLS | {} pythonanywhere_helper | Superuser | {} super | Superuser, No inheritance +| {} | 10 connections | PythonAnywhere says on the Postgres settings page: For security, it may be best to set up individual roles with lower privileges for each of your web applications. Sounds like a good idea, but how can I do that? I made some experiments (with postgreSQL via Docker, inspired by that article) and I found out, that I can do this: postgres=# CREATE USER django; CREATE ROLE postgres=# \du List of roles Role name | Attributes | Member of -----------+------------------------------------------------------------+----------- django | | {} postgres | Superuser, Create role, Create DB, Replication, Bypass RLS | {} I guess, there are some attributes missing. How can I configure this properly for my Django app? Is it even possible to change that in hindsight? -
Which one I should start design Ionic UI firstly or Django as a backend
As a title describe, Which one I should start design Ionic UI firstly or Django as a backend -
How to execute annotate in Django model with foreign keys?
Django novice question here :) I have the following model Domain: domain_name domain_description These domains can be scanned multiple times The other model is ScanHistory: last_scan_date scan_status domain_name = models.ForeignKey(Domain, on_delete=models.CASCADE) When scanned, these domains produce several subdomains ScannedHost: subdomain cname scan_history = models.ForeignKey(ScanHistory, on_delete=models.CASCADE) These subdomains will have vulnerabilities associated with it VulnerabilityScan: vulnerability_of = models.ForeignKey(ScanHistory, on_delete=models.CASCADE) severity vulnerability_name How do I find out the domain which are top 3 most vulnerable Domain? A most vulnerable Domain is any domain that has the highest count of Unique Vulnerability despite n numbers of time it is scanned. I stumbled upon Django annotate, but I don't seem to solve this. -
DRF Get likes and dislikes grouped by day
I have a models named Post and Like. How can i get json with ount of likes and dislikes grouped by date (date field in Like model)? Here is my models.py class Post(models.Model): """Post model""" author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=255) body = models.TextField() created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Like(models.Model): """Like model""" LIKE = ( ('like', 'like'), ('dislike', 'dislike') ) user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='likes') like = models.CharField(max_length=255, choices=LIKE) date = models.DateField(auto_now=True) Here is my serializers.py: class AnaliticsSerializer(serializers.ModelSerializer): """Like analitic""" class Meta: model = Like fields = '__all__' Here is my vievs.py: class AnaliticView(ListAPIView): queryset = Like.objects.all() serializer_class = AnaliticsSerializer filter_backends = [DjangoFilterBackend] filter_fields = ['date'] result what i want [ { "date": "2020-11-14", "total_likes": 25, "total_dislikes": 17 }, { "date": "2020-11-15", "total_likes": 38, "total_dislikes": 8 }, { "date": "2020-11-18", "total_likes": 11, "total_dislikes": 0 } -
React Plus Django: Can't update the django backend while creating a new Todo item
I created a Django + React Todo App which is working as expected on the frontend but the functionality of updating the backend when a new item/todo is not know to me well. Also, i was able to manage the delete functionality but not the rest (got stuck with handleItem function). Need help to make the add items functionality work :( Frontend Code below, Backend code is here "https://bitbucket.org/Yash-Marmat/backend/src/master/" import React, { Component } from "react"; import axios from "axios"; import "bootstrap/dist/css/bootstrap.min.css"; import "font-awesome/css/font-awesome.min.css"; //import "@fortawesome/react-fontawesome"; import "./App.css"; class App extends Component { constructor() { super(); this.state = { newID: 11, edit: false, cloneID: 0, cloneTitle: "", todoData: [], // will come from django backend }; this.handleUserInput = this.handleUserInput.bind(this); this.handleAddItem = this.handleAddItem.bind(this); this.handleEdits = this.handleEdits.bind(this); this.renderEdits = this.renderEdits.bind(this); this.handleUpdates = this.handleUpdates.bind(this); this.onRemove = this.onRemove.bind(this); this.handleStrike = this.handleStrike.bind(this); this.refreshList = this.refreshList.bind(this); this.getTodos = this.getTodos.bind(this); this.increment = this.increment.bind(this); } // increment id increment() { this.setState((prevState) => ({ newID: prevState.newID + 1, })); } // Todo Creation Function (part 1) handleUserInput(event) { this.setState({ userInput: event.target.value, }); } // PROBLEM BELOW // Todo Creation Function (part 2) handleAddItem(id) { const someID = this.state.newID; //console.log(someID) this.setState((prevState) => ({ todoData: [ ...prevState.todoData, { id: someID, task: … -
Count of values between a certain range for columns of dataframe pandas and render from views.py as dictionary to Django html file
I am new to Python and Django. I need to calculate count values over a range, for dataframe columns and render it as a dictionary object so that I can view it as Django html. I don't know how to do so. I tried to see if I can use histrogram but could not find ways to get output in below format. Similarly I can see that Pandas has Cut function but it looks like it adds against an column. Below are columns from dataframe. In all I have 1190 records in each columns, these are basically percentages of deviations observed. Symbol Date Col1 Col2 XXX 16-02-2020 -0.67 -3.69 XXX 17-02-2020 1.18 4.47 XXX 18-02-2020 -3.02 -0.21 XXX 19-02-2020 -2.15 -0.64 XXX 20-02-2020 4.32 0.40 XXX 21-02-2020 3.89 4.73 . . . What I want to see is output as below. This will be one at a time. i.e Show output for Col1 if selected from list or col2 or col3 so on and so forth. Range Count Total Records More than 3% 7 1190 Between 2% and 3% 9 1190 Between 1% and 2% 97 1190 Between 0% and 1% 433 1190 Between 0% and -1% 528 1190 Between … -
Best way to hot-swap between two APIs in a Django application?
I am not looking for any direct code answers, merely some suggestions or examples. I am pretty new to Django, so I would love to get pointers rather than solutions :) I suppose this is a back-end task, but could also be front-end if someone points me to right location. I want to create a service, that is robust, such that if one API fails, it uses an counterpart API that does the same action. For instance if I use Sendgrid, and it fails, it reverts to using Amazon SES, MailGun or something similar.. The failing part is what I am puzzled about. How do I check that the API failed or is too slow to respond, for the service to redirect to the other API? Is there a good paper or documentation for a "hot-swap" mechanism, if one service is unresponsive? The goal is to makke the user's not wait around or receive error messages, butthat the service just runs at all times. -
Cannot access backend with nginx container
I have a multi container app with an nginx container. I cannot access backend with this config. "Site cannot be reached" App is running locally. This config works without using nginx as a container but when I try use it in a container I cannot access the backend. Why can't I reach my backend using nginx container? Here's my config upstream django { ip_hash; server django:8000; } upstream nuxt { ip_hash; server nuxt:3000; } server { # the port your site will be served on listen 80; # the domain name it will serve for server_name $SERVER_NAME; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste location /static/ { alias /static/; } location / { proxy_pass http://nuxt; proxy_set_header Host $http_host; proxy_set_header X-Forwarded-Host $host; } location ~ /(api|admin|static)/ { proxy_pass http://django; proxy_set_header Host $http_host; proxy_set_header X-Forwarded-Host $host; } } Docker-compose django: container_name: django build: context: ./backend dockerfile: scripts/dev/Dockerfile env_file: .env environment: - DEBUG=True command: > sh -c "./wait-for-it.sh db:5432 && ./autobets/manage.py collectstatic --no-input && ./autobets/manage.py makemigrations && ./autobets/manage.py migrate --no-input && ./autobets/manage.py runserver_plus 0.0.0.0:8000" expose: - "8000" ports: - "8000:8000" volumes: - ./backend:/app depends_on: - db - rabbitmq restart: on-failure … -
Adding Ajax to Like button not working properly
I am trying to learn more about Ajax and using Like buttons without refreshing the page but I am facing some obstacles trying to figure them out to understand how they work. I am currently getting TemplateDoesNotExist at /blogs/like although it is available, I have messed with it trying to solve it but I need some help knowing what is wrong and how to fix it. The like button was working perfectly without the Ajax but now I am adding it to prevent refreshing so I need some guidance to understand what am I doing wrong Here is the views.py class PostDetailView(DetailView): model = Post template_name = "blog/post_detail.html" # <app>/<model>_<viewtype>.html def get_context_data(self, *args, **kwargs): context = super(PostDetailView, self).get_context_data() post = get_object_or_404(Post, slug=self.kwargs['slug']) comments = Comment.objects.filter( post=post).order_by('-id') if self.request.method == 'POST': comment_form = CommentForm(self.request.POST or None) if comment_form.is_valid(): content = self.request.POST.get('content') comment_qs = None comment = Comment.objects.create( post=post, user=self.request.user, content=content) comment.save() return HttpResponseRedirect("blog/post_detail.html") else: comment_form = CommentForm() context["comments"] = comments context["comment_form"] = comment_form return context def get(self, request, *args, **kwargs): res = super().get(request, *args, **kwargs) self.object.incrementViewCount() return res class PostCommentCreateView(LoginRequiredMixin, CreateView): model = Comment form_class = CommentForm def form_valid(self, form): post = get_object_or_404(Post, slug=self.kwargs['slug']) form.instance.user = self.request.user form.instance.post = post return … -
Django - Update the final result in views.py every n seconds
I built a stock screener that I want to update the final result based on the latest prices during the market hours. I simplify my original files for better understanding of what I really need. models.py class ScreenerModel(models.Model) pct_choices = [(0, 'all'), (1, 'above 1'), (2, 'below 1')] price_choices = [(0, 'all'), (1, 'above 5000'), (2, 'below 5000')] user = models.ForeignKey(User, on_delete=models.CASCADE, default=None) pct = models.IntegerField(choices=pct_choices, default=0) price = models.IntegerField(choices=price_choices, default=0) urls.py urlpatterns = [ path('users/tmp/<int:pk>/', views.ScreenerModelUser, name='tmp_user'), ] views.py import pandas as pd from .models import ScreenerModel from django.contrib.auth.decorators import login_required from django.shortcuts import render @login_required def ScreenerModelUser(request, pk): user_screener = ScreenerModel.objects.get(user_id=request.user.id, pk=pk) df = pd.read_csv('https://raw.githubusercontent.com/AmirForooghi/stocks_csv/master/stocks_sample.csv') pct_user = user_screener.pct if pct_user == 1: df = df.loc[df.pct > 1] if pct_user == 2: df = df.loc[df.pct < 1] price_user = user_screener.price if price_user == 1: df = df.loc[df.close > 5000] if price_user == 2: df = df.loc[df.close < 5000] context = {'df': df.to_html()} return render(request, 'screener/tmp_user.html', context) tmp_user.html {{ df|safe }} My Problem: As you can see I have online prices in the df and in the views I just filter them according to the user preference. Obviously the prices change during market hours. I want to update the final … -
Two modelformset in one view in django
I'm new to django and I'm trying to have two modelformset in one view but I'm getting the 'ManagementForm data is missing or has been tampered with' error. I have already check the docs and I know that I have to use the management_formset tag and prefix, but I still having the error. I have looked for the answer and I wasn't able to fix the bug. With only one formset all is working as espected. Views.py def soil_page(request): SoilFormSet = modelformset_factory(model=Soil,exclude=False,min_num=1,extra=0) CMCFormSet = modelformset_factory(model=CMC,exclude=False,max_num=1) if request.method == "POST": formset = SoilFormSet(request.POST or None, request.FILES or None, prefix='soils') cmcform = CMCFormSet(request.POST or None,request.FILES or None, prefix='cmcs') if formset.is_valid(): formset.save() if cmcform.is_valid(): cmcform.save() else: formset = SoilFormSet(prefix='soils') cmcform = CMCFormSet(prefix='cmcs') return render(request,'soil/soil_form.html',{'formset':formset, 'cmcform':cmcform,}) HTML <div class="container"> <form id="myform" method="post"> {% csrf_token %} {{ formset.management_form }} {{ formset.as_p }} <input type="submit" value="Save" form='myform'/> </form> </div> <div class="container"> <form id="cmcform" method="post"> {% csrf_token %} {{ cmcform.management_form }} {{ cmcform.as_p }} <input type="submit" value="Save" form='cmcform'/> </form> </div> I hope you can help me. Thanks. -
How to add the heroku nginx buildpack to a python django app with gunicorn?
I am trying to deploy a python with django on heroku and configure an nginx reverse proxy to have like a filter which won't let the requests pass to my django backend until the token is checked to an third party IDP. ** STEP 1 ** I am following this tutorial to add the nginx buildpack : https://elements.heroku.com/buildpacks/hq-mobile/v3-nginx-buildpack After I've added the buildpack and start the app, I get the following message: bin/start-nginx: line 37: bundle: command not found After some digging I noticed some paths need to be added to the config vars for the heroku app in order for bundler to get the needed dependencies : So I've added this paths: heroku config:add GEM_PATH=vendor/bundle/1.9.3 heroku config:set PATH=bin:vendor/bundle/ruby/1.9.3/bin:/usr/local/bin:/usr/bin:/bin Then the config/unicorn.rb file: require 'fileutils' listen '/tmp/nginx.socket' before_fork do |server,worker| FileUtils.touch('/tmp/app-initialized') end Procfile: web: bin/start-nginx bundle exec unicorn -c config/unicorn.rb gunicorn -c gunicorn.conf.py MyApp.wsgi gunicorn.conf.py # gunicorn.conf def when_ready(server): # touch app-initialized when ready open('/tmp/app-initialized', 'w').close() bind = 'unix:///tmp/nginx.socket' workers = 4 Even after adding this, the error still persists. ** STEP 2 ** Once the normal buildpack will be in place I want to follow this tutorial to configure nginx how I want: https://www.nginx.com/blog/validating-oauth-2-0-access-tokens-nginx/ What configuration is needed to … -
How to correctly render the template in class based views? Django translation
I'm working on my Django APP which I give the users the opportunity to choose if they want to see the website in English or Spanish. The problem here is that django is not rendering the correct template. I've tried the "get_template_names" with the language session key, but still dont works... I don`t know if the problem here is the dispatch function. Any help or comments would be helpfull! thank you! views.py class PostListView(LoginRequiredMixin, ListView): model = Post context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 10 def get_template_names(self): language = self.request.session.get(translation.LANGUAGE_SESSION_KEY) if language == 'es': return ['blog/home.html'] else: return ['blog/en_home.html'] def dispatch(self, request, *args, **kwargs): event_change_sets(Post.objects.all()) event_change_sets_co(Post.objects.all()) return super().dispatch(request, *args, **kwargs) The LocaleMiddleware is also activated. settings.py MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Europe/Madrid' USE_I18N = True USE_L10N = True USE_TZ = True LANGUAGES = [ ('en', 'English'), ('es', 'Español') ] -
How to send event to client from any place of server using django channels and websockets
Now I'm building a website using django and angular, And I want to add websocket communication between client and server. I followed the instructions of django channel documentation.( https://channels.readthedocs.io/ ) I want to send any event from any place of django server code. But when multiple users connect via socket, the data sent from server always goes to the last connected user. And here's what I did. First in consumers.py, I defined my ChatConsumer class as follows and added a new handler named "tweet_send" function class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() ... # here's what I added a new tweet send handler async def tweet_send(self, event): content = event['content'] content["group_name"] = self.room_group_name # Send message to WebSocket await self.send(text_data=json.dumps({ "type": "MESSAGE", "data": content })) And somewhere of django server side(in serializers.py), when a new tweet is created, I send a new tweet data to all users using django.channel_layer ... def create(self, validated_data): ... new_tweet.save() # send message via channels channel_layer = get_channel_layer() all_users = list(Member.objects.filter(is_active = True).values_list('id', flat = True)) for user_id in all_users: async_to_sync(channel_layer.group_send)( "chat_{}".format(user_id), # this is the group name … -
multiple model search in django
I want to implement a multi model search in django( search a query from two different models).I have models called location, PropertyFLat and PropertyRoom where location is foreign key in rest of the two models.Now i want to make a search and display result from both PropertyFlat and PropertyRoom models. views.py def search(request): if request.method == 'POST': search_request = request.POST.get('search', False) if search_request: match = PropertyFlat.objects.all().filter( Q(price__istartswith=search_request) | Q(location__state__startswith=search_request) | Q(location__district__startswith=search_request) | Q(location__municipality__startswith=search_request) ) if match: return render(request, 'search_result.html', {'searched': match}) else: match = PropertyFlat.objects.all() error = 'No result found !' return render(request, 'search_result.html', {'error': error, 'error_view': match}) elif search_request == '' or search_request == 'None': return redirect('/') else: price = request.POST.get('price', False) state = request.POST.get('state', False) district = request.POST.get('district', False) if price == '' and state == '' and district == '': return redirect('/') else: match = PropertyFlat.objects.all().filter( Q(price__icontains=price) & Q(location__state__icontains=state) & Q(location__district__icontains=district) ) if match: return render(request, 'search_result.html', {'searched': match}) match = PropertyFlat.objects.all() error = 'No result found !' return render(request, 'search_result.html', {'error': error, 'error_view': match}) return render(request, 'search_result.html') models.py class Location(models.Model): state = models.CharField(max_length=100) district = models.CharField(max_length=100) municipality = models.CharField(max_length=100) ward_no = models.IntegerField() def __str__(self): return "%s %s %s" % (self.state, self.district, self.municipality) class PropertyRoom(models.Model): location = … -
PermissionError at /insert
//Error Page Contents [Errno 13] Permission denied: 'd:/upload/' Request Method: POST Request URL: http://localhost/insert Django Version: 2.1 Exception Type: PermissionError Exception Value: [Errno 13] Permission denied: 'd:/upload/' Exception Location: C:\Users\cocoa\PycharmProjects\myweb\board\views.py in insert, line 27 Python Executable: C:\python study\myweb\Scripts\python.exe Python Version: 3.8.5 //insert content @csrf_exempt def insert(request): frame='' fsize=0 if 'file' in request.FILES: file=request.FILES['file'] fname=file._name with open('%s%s' % (UPLOAD_DIR, frame), 'wb') as fp: for chunk in file.chuncks(): fp.write(chunk) fsize=os.path.getsize(UPLOAD_DIR + fname) row=Board(writer=request.POST['writer'], title=request.POST['title'], content=request.POST['content'], filename=fname, filesize=fsize) row.save() return redirect('/') //views.py Partial Contents row=Board(writer=request.POST['writer'], title=request.POST['title'], content=request.POST['content'], filename=fname, filesize=fsize) row.save() ``` An error occurs when I add a title, name, attachment, and press the confirmation button. What's wrong? Please let me know if you need anything else. I have shallow Python knowledge. I would appreciate it if you could let me know in detail. -
Django template tag if doesn't compare as expected
Django version: $ python -m django --version 3.1.2 My template contains this form: <form method="post"> {% for samtalepartner in elev %} <input type="radio" name="elev" id="elev{{ forloop.counter }}" value="{{ samtalepartner.id }}"> <label for="elev{{ forloop.counter }}"> {{ samtalepartner.id }}{{ request.POST.elev }} {% if samtalepartner.id == request.POST.elev %} <b>{{ samtalepartner.fulde_navn }}</b> {% else %} {{ samtalepartner.fulde_navn }} {% endif %} </label> <br> {% endfor %} <input type="submit" value="Fremhæv valgte"> </form> When I submit first time the browser shows: 1 Andersine Andersen 2 Sida Dida When selecting #2 and submitting again, I expected, as 2==2: 12 Andersine Andersen 22 <b>Sida Dida </b> However, browser shows: 12 Andersine Andersen 22 Sida Dida How come that the two values do not compare and executes the {% if %} statement (rather than the {% else %}? -
Substract a substring from a string in a model object in Django
I'm building a blog website with Django, and for posts on the blog I want to have 2 pages, first page would be the page where all the posts are displayed as a list, and the second would be a page for a specific post, with all the details. On the first page I want to show every post with title, date, and a part of the post's text. I thought that I can add to the post model another field which'll hold a substring from the hole post's text. My post model is this: class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=500) content = models.TextField() display_content = models.TextField(blank=True) tags = models.CharField(max_length=100) date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return self.title I want for every post the display_content field to hold the first 167 characters from the content field + "...", and I'm not sure that I'd have to implement something directly on the class Post, maybe a function, or if I need to make this operation on the view function that renders this page with posts. -
NGINX docker-compose - Host not found in upstream nuxt:3000
I'm trying to configure a deployed app on an EC2 instance I'm not able to get visit the application when it's up on ec2 public IP. I've checked the security groups and allowed all inbound traffic to ports just to see If I can reach the homepage or admin page of django. Say my ec2 IP address is 34.245.202.112 how do I map my application so nginx serves The frontend(nuxt) at 34.245.202.112 The backend(django) at 34.245.202.112/admin The API(DRF) at 34.245.202.112/api When I try to do this the error I get from nginx is nginx | 2020-11-14T14:15:35.511973183Z 2020/11/14 14:15:35 [emerg] 1#1: host not found in upstream "nuxt:3000" in /etc/nginx/conf.d/autobets_nginx.conf:9 This is my config docker-compose version: "3.4" services: db: restart: always image: postgres volumes: - pgdata:/var/lib/postgresql/data environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres ports: - "5432:5432" expose: - 5432 networks: - random_name django: container_name: django build: context: ./backend env_file: .env environment: - DEBUG=True command: > sh -c "./wait-for-it.sh db:5432 && ./autobets/manage.py collectstatic --no-input && ./autobets/manage.py makemigrations && ./autobets/manage.py migrate --no-input && ./autobets/manage.py runserver_plus 0.0.0.0:8001 " - "8001" volumes: - ./backend:/app depends_on: - db restart: on-failure nginx: image: nginx container_name: nginx ports: - "80:80" restart: always depends_on: - nuxt - django volumes: - ./nginx/conf:/etc/nginx/conf.d - …