Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to change netflix password every one hour or daily automatically?
i am working on a project lately . i want to change netflix or any other OTT platform on a hourly or daily basis. Is there a way to do it? -
How can I add the next 1st of August as DateTimeField default value in Django?
I have the following model and want to add the next August (midnight time) from now as a default value for offer_start: class Offer(models.Model): """ A table to store all available offers for an upcoming season """ club = models.ForeignKey(Club, on_delete=models.CASCADE, related_name='offer') season_start = models.CharField(max_length=40) seasons_duration = models.IntegerField() offer_start = models.DateTimeField(auto_now_add=False, default= ???) roi_goal = models.FloatField() roi_point = models.FloatField() def __str__(self): return f'Offer by {self.club} for season {self.season_start}' Is there any way to make such a specification? -
form won't be submitted when i used select fields on the template (dependent on each other) using Django
I have noticed that my form don't want to be submitted because of 2 field that depends on each other(dependend dropdown list, where I have made the "pid" field value(exit in the 2 models) as a common point between the 2 fields), after click on the button the values that i have choose them as a user disappear automatically when i click on the button and in same way the form don't want to be submitted: those are the 2 fields ow i have called them on the html template: Here is the code <select id="select1"> <option selected disabled="true"></option> {% for categories in categoryobj%} <option value="{{categories.pid}}">{{categories.name}}</option> {% endfor%} </select> <select id="select2"> <option selected disabled="true"></option> {% for items_size in sizeobj%} <option value="{{items_size.pid}}">{{items_size.name}}</option> {% endfor%} </select> Js <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(document).ready(function(){ var $select1=$('#select1'), $select2=$('#select2'), $options = $select2.find('option'); $select1.on('change',function() { $select2.html($options.filter('[value="'+this.value+'"]')); }).trigger('change'); }); </script> with the button of submitting: <button class="floated" onclick="location.href='#results'" type="submit">Submit</button> Ps: if i change those two fields to tag : the code html: <p >{{form.profile_family}} </p> <p >{{form.profile_size}} </p> -----> the form is submitting ----> But i don't want that exactly , i want a dependent dropdown list Any help will be appreciated please, thanks. -
WinError 10061 No connection could be made because the target machine actively refused it - Django Python Error when Sending Email
I'm just learning Django and wasn't able to figure this out. I'm trying to make my Django App send emails. But keep encountering this error on Submitting. Error Image I've turned the Allow less secure apps option ON in Gmail Settings, & have tried adding EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' to the settings.py but it prints the emails in the console instead of actually sending them, which doesn't server the purpose Settings.py """ Django settings for expenseswebsite project. Generated by 'django-admin startproject' using Django 4.0.3. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ from pathlib import Path import os from django.forms import EmailField import django_heroku from django.contrib import messages from dotenv import load_dotenv load_dotenv() # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-*akbxcj*md2z0&#vai@lw816t6p#te!fdo^#4j194^x7r7p-zo' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'expenses' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', … -
SSLError. SSL certificate verification failed in beautifulsoup4
this is a part where I search for things on the internet. I am using beautifulsoup4 for web search and scraping them. but it is giving SSL error Here is my code def searchBing(query, num): url = 'https://www.bing.com/search?q=' + query print(url) urls = [] page = requests.get(url, headers= {'User-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36', "Accept-Encoding": "*", "Connection": "keep-alive" }) soup = bs(page.text, 'html.parser') for link in soup.find_all('a'): url = str(link.get('href')) if url.startswith('http'): if not url.startswith('http://go.m') and not url.startswith('https://go.m'): urls.append(url) return urls[:num] # Extraxt text from the internet (from similar website) def extractText(url): page = requests.get(url, headers={'User-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36', "Accept-Encoding": "*", "Connection": "keep-alive" }) soup = bs(page.text, 'html.parser') return soup.get_text() Traceback of the error -
Cookies disappear after reload the page
response.set_cookie(key=SIMPLE_JWT.get('REFRESH_AUTH_COOKIE'), value=response.data.get('refresh'), expires=datetime.now()+SIMPLE_JWT.get('REFRESH_TOKEN_LIFETIME'), samesite='None', secure=SIMPLE_JWT.get('AUTH_COOKIE_SECURE'), httponly=SIMPLE_JWT.get('AUTH_COOKIE_HTTP_ONLY')) I'am using Django Rest Framework to set the JWT Refresh cookie, until this point everything is ok, but when I reload the page the cookie just disappear so I can't retrieve the value any more by JS, but when I send a new request the cookie appears in the Django log. So, I don't know what is happening because the cookie is set in the browser, but in a way that I can't retrieve -
Carousel Bootstrap don't work with data database
Carousel shows the data from the database but the slider does not work and the cards are duplicated. I have tried to add the loop inside the cards or the carousel item itself but it does not work. the slider arrows are not visible because they are on a white background This is my code: <div id="carouselExampleControls" class="carousel slide" data-ride="carousel" data-interval="false"> <div class="carousel-inner"> {% for i in usuarios%} <div class="carousel-item active"> <div class="card mb-3"> <div class="card-body"> <div class="row justify-content-center"> <div class="col-sm-8 align-self-center border-sm-right border-md-right border-xl-right border-lg-right"> <div class="card-body"> <!--<h5 class="card-title">Card title 1</h5> <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p> <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>--> <img src="../../static/ejemploMates/JoseJuan.png" class="img-fluid float-left"> <div class="infoPersonal"> <p>{{i.usuario.username}}</p> <p class="edad">38 años</p> <p class="genero">Género: {{i.genero}}</p> </div> <p class="text-center">A 700 metros de ti y acercándose.</p> </div> </div> <hr class="sm"> <div class="col-sm-4 align-self-center"> <div class="card-body"> <h5 class="card-title">Con piso</h5> <img src="../../static/ejemploMates/fotosPiso.png" class="img-fluid float-left"> <img src="../../static/ejemploMates/Home-Logo-Transparent-File.png" class="img-fluid float-right"> </div> </div> </div> </div> <hr> <div class="card-body"> <div class="row justify-content-center special-card"> <div class="col-sm-8 align-self-center"> <div class="card-body"> <p class="card-text text-center">Soy José Juan y me interesan tus órganos. Vente a compartir piso conmigo.</p> </div> </div> <div class="col-sm-4 … -
Django channels self.send() from custom function
Is it possible to self.send() from custom function inside consumer.py? I have a roulette game which runs inside a loop after every 30 seconds. Inside that loop I call a function to save the winning game details and update the user model with their winnings. I would like to also send that to the front end view so the user does not need to refresh the page to update their balance. The problem currently is that the way I thought to do it is not working as the self.send() inside my custom save_roll() function is not working. How can something like this be achieved? consumers.py @database_sync_to_async def save_roll(self, result, roll_color, round_number): winners = Bets.objects.filter(round_number=round_number, bet_choice=roll_color) multiplier = 0 if roll_color == 'blue' or roll_color == 'red': multiplier = 2 elif roll_color == 'green': multiplier = 14 for winner in winners: winnerId = winner.id winnerBet = winner.bet_value userObj = CustomUser.objects.filter(id=winnerId)[0] newBalance = userObj.user_coins + (winnerBet * multiplier) CustomUser.objects.filter(id=winnerId).update(user_coins=newBalance) self.send(text_data = json.dumps({ 'balance': newBalance })) Roulette.objects.create(win = result, roll_color = roll_color, round_number = round_number, is_over = True) class RouletteGame(AsyncWebsocketConsumer): async def connect(self): self.connected = True await self.accept() while self.connected: await asyncio.sleep(30) server_seed = get_random_string(length=64) public_seed = random.randint(0, 999999) round = await get_round() … -
How do I iterate inside a queryset in django template
My django view returns a dictionary people with values for all keys in list format. The code for the view is: class ProjectDetail(View): def get(self, request, pk, *args, **kwargs): project = Project.objects.get(pk=pk) roles = Role.objects.filter(project=pk) people = {} for role in roles: try: people[role] += Person.objects.filter(role=role.pk) except KeyError: people[role] = [Person.objects.filter(role=role.pk)] context = { 'project': project, 'people': people } return render(request, 'project_management/project_detail.html', context) In order to iterate through the dictionary I used: {% for designation, persons in people.items %} <h5> {{ designation.role_name }} </h5> <ul> {% for person in persons %} <!-- My Problem lies here, this loop is not iterating, it's running only once--> <li> {{person}} </li> {% endfor %} </ul> {% endfor %} The result I got is: I want the items inside queryset listed out separately, instead of being shown inside square brackets. How can I make that happen? -
Joining two tables and search/filter within serialized data with django-rest-framework
I am joining two tables than I would like to do keyword searching. I need to create a single SQL and add a WHERE with argument(s). I am using django-rest-framework. models.py from django.db import models class Paper(models.Model): title = models.TextField() paper_lan = models.CharField(max_length=2) nb_authors = models.SmallIntegerField() class Meta: managed = False def __str__(self): return str(self.title) class Abstract(models.Model): paper = models.OneToOneField(Paper, related_name='abstracts', on_delete=models.CASCADE, primary_key=True) abstract = models.TextField() class Meta: managed = False def __str__(self): return str(self.abstract) serializers.py from rest_framework import serializers from .models import Paper, Abstract class PaperAbstractSerializer(serializers.ModelSerializer): class Meta: model = Paper #fields = '__all__' fields = ['title', 'paper_lan', 'nb_authors', 'abstracts'] depth = 1 class PaperSerializer(serializers.ModelSerializer): class Meta: model = Paper fields = ('title', 'paper_lan', 'nb_authors') class AbstractSerializer(serializers.ModelSerializer): class Meta: model = Abstract fields = ['abstract'] filters.py from django.db.models import Q from django_filters.rest_framework import CharFilter, FilterSet from .models import Paper, Abstract class PaperAbstractFilterSet(FilterSet): query = CharFilter(method='qfilter') class Meta: model = Paper fields = ['query'] def qfilter(self, queryset, name, value): squery = Q(abstracts__icontains=value) return queryset.filter(squery) class PaperFilterSet(FilterSet): query = CharFilter(method='qfilter') class Meta: model = Paper fields = ['query'] def qfilter(self, queryset, name, value): squery = Q(title__icontains=value) return queryset.filter(squery) class AbstractFilterSet(FilterSet): query = CharFilter(method='qfilter') class Meta: model = Abstract fields = ['query'] … -
Auto refresh HTML database data in Django - Ajax?
I have a Django server which is locally hosted and displays sensor data from a MySQL database. This data is displayed on the instruments.html page through variables such as {{qs.value}} which comes from the views.py, models.py and URLs.py. The views.py page is as follows: from django.http import HttpResponse from django.shortcuts import redirect, render from .models import Sensorresult def db(request): qs = Sensorresult.objects.using('Vision').get(sensorresult='1') return render(request, 'authenticate/instruments.html',{'qs':qs}) The problem I have is that I want the database information to update on the html every second, whereas currently it only updates when the page is refreshed. I know I could place a line of javascript at the top of the page and have the entire webpage constantly update, but I only want the database values to update. Does anyone have any suggestions as to how to do this? From googling have come across Ajax, however this is something I have no experience in and I am unsure how my code would be edited to accommodate this? Many thanks -
Django Conditional ORM Query
I am creating a Blog website where for each blog a user can like or dislike the post. Now every time user goes on Index page I want to change the like button i.e if user has liked the post then a dislike button otherwise like button. For this I need to get the variable IsLiked from the views.py file. This is the Query that I have written. posts = Post.objects.exclude(users=request.user).select_related('user__people','ProductAvailability').prefetch_related('images_set').annotate(comments_Count = Count('comments_post',distinct=True)).annotate(Count('Likes',distinct=True)).all().order_by('-id') for post in posts: if(post.Likes.filter(id=user_id).exists()): isLiked = True else: isLiked = False Here the problem is that for every post there is a separate query sent to DB. This is my Blog Post Model -> class Post(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT) # category = models.ForeignKey(Category, on_delete=models.PROTECT) ProductAvailability = models.ForeignKey(ProductAvailability, on_delete=models.PROTECT, null=True, blank=True) title = models.CharField(max_length=255,null=True) description = models.CharField(max_length=1000,null=True) Likes = models.ManyToManyField(to=User, related_name='Post_likes') favourites = models.ManyToManyField(to=User,blank=True,related_name="favourite") Tag1 = models.CharField(max_length=255,null=True,blank=True) Tag2 = models.CharField(max_length=255,null=True,blank=True) Tag3 = models.CharField(max_length = 255, null = True, blank = True) Tag1_Name = models.CharField(max_length=255,null=True,blank=True) Tag2_Name = models.CharField(max_length=255,null=True,blank=True) Tag3_Name = models.CharField(max_length=255,null=True,blank=True) users = models.ManyToManyField(User, related_name='users_hidden_from_post') Created_date = models.DateTimeField(auto_now_add=True) Updated_date = models.DateTimeField(auto_now=True) PS: Please Ignore the redundant Info in the Post Model I want to send the User id with the Query and check if individual post is … -
django way to get and save a tree of folders and files
When I came across a project to save a tree of files - means including subdirectories and files, not just files - I couldn't find an appropriate solution for the problems. note: This question is not the same as this. They speak of two different things, mine: How to save, his/hers: How to show - a tree of files I do not want to write the code purely by myself or use a library that isn't suggested by Django. To understand better, let me say a user will upload these three files: src/statistics test/tests img/9744t3vo5.png though files can be placed in root or home or any other place in the file system (let me say simpler: files path should be relative) But the problem is how to get & save files in that manner (with relative path took effect) not the issue to show files that is solved in the question linked above -
display the selected posts of an authorized user
how to get the selected tasks of an authorized user correctly now class Task(models.Model): user_info = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, name='userInfo') title = models.CharField(max_length=100) text = models.TextField(max_length=10000) class Favourite(models.Model): task_id = models.ForeignKey(Task, on_delete=models.CASCADE, blank=True, null=True, related_name='favourites',name='taskId') user_info = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, name='userInfo') views.py class FavouriteUserView(generics.ListAPIView): serializer_class = FavouriteReceivingSerializer pagination_class = MyCursorPagination permission_classes = [IsAuthor] def get_queryset(self): return Favourite.objects.filter(userInfo=self.request.user) urls.py path('user/<int:pk>/favourites/', FavouriteUserView.as_view()), how to get favorite posts without sending int:id without int:id "detail": "Not found." -
How can I return several aggregates based on a condition within a queryset?
So I have the following model which contains different booleans and one amount field. I now want to render the overall sum amount for each boolean when true (only one boolean will be true at once always). class UserTransaction(models.Model): """ A table to store transactions between a user and Farena """ user = models.ForeignKey(User, on_delete=models.CASCADE) offer = models.ForeignKey(Offer, on_delete=models.CASCADE, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) amount = models.FloatField() is_deposit = models.BooleanField(default=False) is_withdrawal = models.BooleanField(default=False) is_interest = models.BooleanField(default=False) is_investment = models.BooleanField(default=False) is_return = models.BooleanField(default=False) def __str__(self): return f'{self.user.first_name} {self.user.last_name} transacted {self.amount}' I tried to build it with annotate but that would add fields for each instance which wouldn't solve my issue as far as I understand it. Additionally using aggregate I couldn't implement a condition and also wouldn't know how to access the aggregated value in the template? -
Unable to select value in action intermediate page
I have two models User and Group. I'm implementing an action "Change Groups" in UsersAdmin that redirects to an intermediate page with 2 MultipleChoiceFields for Groups, that I want to be used to either remove users from certain groups, add users to other groups, or do both in one go (i.e. move them). The docs are very short about this subject, so in order to do this, I'm following this article. Here's my form: class ChangeUsersGroupsForm(forms.Form): _selected_action = forms.CharField(widget=forms.MultipleHiddenInput) from_groups = forms.ModelMultipleChoiceField(Group.objects, required=False) to_groups = forms.ModelMultipleChoiceField(Group.objects, required=False) My admin action: def change_groups_action(self, request, queryset): if 'apply' in request.POST: from_groups = request.POST["from_groups"] to_groups = request.POST["to_groups"] from_groups_qs = Group.objects.filter(pk__in=from_groups).all() to_groups_qs = Group.objects.filter(pk__in=to_groups).all() user_ids = [u.user_id for u in queryset] # task that will do the job of actually moving the users change_users_groups.delay(from_groups_qs, to_groups_qs) self.message_user(request, "Changed groups of %s users" % len(user_ids)) return HttpResponseRedirect(request.get_full_path()) form = ChangeUsersGroupsForm(initial={'_selected_action': queryset.values_list('id', flat=True)}) return render(request, "admin/change_users_groups.html", {'queryset': queryset, 'form': form}) change_groups_action.short_description = "Change Groups" Here's my template: <!-- users/templates/admin/change_users_groups.html --> {% extends "admin/base_site.html" %} {% block content %} <form action="" method="post"> {% csrf_token %} {{ form }} <br /> <br /> <p>The Group changes will be applied to the following users:</p> <ul> {{ queryset|unordered_list }} </ul> <input … -
How to pass 2 parameters from django template to url path
path('/cart/<int:id>,<str:seller>/', auth_middleware(Cart.as_view()) , name='cart'), <form action="/cart/id={{product.id}}&seller={{price.seller}}" class="col-2 " method="post"> {% csrf_token %} <input hidden type="text" name='product' value='{{product.id}}'> <input type="submit" value=" Add to Cart " class="btn btn-success"/> </form> Wont get it working -
How to use drf implement nested url route?
with ModelViewSet, we can easily have these routes /article #get article list /article/1/ #get article whose id is 1 However, I want to accomplish following routes /article/1/comment #get comment list of article(id=1) /article/1/comment/5/ #get comment(id=5) (suppose that this comment belongs to article(id=1)) /article/1/comment/5/childern #get childern comment list of comment(id=5) .... What should I do? -
django.db.utils.OperationalError: sequence must have same owner as table it is linked to
This error is of Django - Postgres Schema of tables are public, type = table and owner are same what is this issue can you help me solving this -
Django HEIC to PNG conversion
I'm trying to convert heic to png, which I successfully achieved in Python with the help of Wand library. I also saved the file locally to see, if the convertion worked, and it did. The problem is that Django's serializer cant take in Wand image, and I have to convert it to InMemoryUploadedFile. Whatever I do, I still can't make the serializator to take in the converted image. views.py update_post() @api_view(['PUT']) @permission_classes([IsAuthenticated]) def update_post(request, id): image = request.FILES['image'] print(image.size, image.name, image.file, image.content_type, image.field_name) if image.content_type == 'image/heif': img = Image(file=image) img.format = 'png' img_io = io.BytesIO() img.save(file=img_io) filename = image.name.replace('.heic', '.png') img.save(filename=filename) img_file = InMemoryUploadedFile( img_io, 'image', filename, 'image/png', sys.getsizeof(img_io), None) print(img_file.size, img_file.name, img_file.file, img_file.content_type, img_file.field_name) image = img_file #request.data['image'] = img_file #request.FILES['image'] = img_file # data = request.data # print(img_file, image) loggedin_user = request.user.username post = Post.objects.get(id=id) post_user = post.user if (str(post_user) == str(loggedin_user)): serializer = PostSerializer( instance=post, data={'caption': request.data['caption'], 'image': image}) if serializer.is_valid(): print(serializer.validated_data) serializer.save() else: print('achjo') print(serializer.data) return Response(status=status.HTTP_200_OK) -
Django Invalid HTTP_HOST header: '<ip>'. You may need to add '<ip>' to ALLOWED_HOSTS
<ip> is showing an actual ip address, I just didn't include it in the title. I believe this ip address is the internal ip of my EC2 instance. I'm using AWS Elastic beanstalk to host. I see this question has been answered a lot on SO, and the answer is always to add the ip address to the ALLOWED_HOSTS, but in my case I've set ALLOWED_HOSTS=['*'] and I'm still getting the error. The weird thing is, I'm only getting the error when I try to access the site from my phone. When I access from the desktop browser, it works fine... Things I've tried: I've double checked my elastic beanstalk deployment and the changes are definitely deployed. -
Apache - Django - File upload error code 500
I'm having an issue with hosting my django project on Apache. In my project I have the models Product and ProductImage. A Product has multiple ProductImages, and creating a ProductImage simply saves an image file and saves the name of the file in the database. All of this works perfectly fine when I use the runserver command. However as soon as I use Apache to host my project (using mod_wsgi) it doesn't work anymore. I'm suspecting something is going wrong with the file upload. I'm quite new to this so I'm not sure what's a good way to debug this? I've checked /var/log/apache2/error.log but nothing useful is in there. ProductImage view: class ProductImageViewSet(viewsets.ModelViewSet): serializer_class = ProductImageSerializer queryset = ProductImage.objects.all() def create(self, request, *args, **kwargs): product_id = request.data["product_id"] name = request.data["name"] file = request.data["file"] name = default_storage.save(name, file) serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save(name=name, product_id=product_id) # success response return Response({"message": serializer.data}, status=status.HTTP_200_OK) Is there something I'm missing? -
Show all items of an invoice - django
I would like to get all items belonging to an invoice and show them to a template without success. What i have done so far is the following: I have two models: class Invoice(models.Model): PAYMENT_OPTIONS = ( ('CASH', _('CASH')), ('DEPOSIT', _('DEPOSIT')), ('CARD', _('CARD')), ) INVOICE_TYPE = ( ('Service', _('Service')), ) invoice_number = models.CharField(max_length=7, unique=True, default='INV4898') invoice_user = models.ForeignKey(Account, on_delete=models.CASCADE) invoice_type = models.CharField(max_length=30, choices=INVOICE_TYPE, default='Service') payment_option = models.CharField(max_length=30, choices=PAYMENT_OPTIONS) invoice_name = models.CharField(max_length=30, null=True, blank=True) vat = models.CharField(max_length=9, blank=True, null=True) gross_amount = models.DecimalField(max_digits=6, decimal_places=2) vat_amount = models.DecimalField(max_digits=6, decimal_places=2) net_amount = models.DecimalField(max_digits=6, decimal_places=2) created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.invoice_user.first_name} {self.invoice_user.last_name} - {self.invoice_number}" class Item(models.Model): invoice = models.ForeignKey(Invoice, related_name='items', on_delete=models.CASCADE) title = models.CharField(max_length=255) quantity = models.IntegerField(default=1) unit_price = models.DecimalField(max_digits=6, decimal_places=2, default=Decimal('0.00')) net_amount = models.DecimalField(max_digits=6, decimal_places=2, default=Decimal('0.00')) vat_rate = models.CharField(max_length=10, default=0) discount = models.DecimalField(max_digits=6, decimal_places=2, default=Decimal('0.00')) is_paid = models.BooleanField(default=False) created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.invoice.invoice_number}" In the views.py i have a list view like, in which i'm trying to get a list of all invoices based on invoice_number and then match each invoice_number to an invoice in items. However using below code first pring brings all invoice_number(s) and second print brings all items for all invoices, not … -
How to get the current port in a django application?
How can I get the current port of my running django application? I don't have access to the request, and I can't use the Site object. -
How to make a view that lists project instances with option buttons
I am trying to build a django webapp that manages and executes a few python programs I wrote. Background information: The setup: I have a folder called projects with subdirectories called project_1, project_2 and so on. In every project_x folder, there are a few config_whatever.csv files and a routin_projectX.py python code file that reads the config_whatever.csv files and does a routine accordingly. All project_x subdirectories have the exact same structure. Currently I am managing the project instances by either editting the config files with an editor and restarting the routin_projectX.py function or for instance copying a template project_x directory , editing the config files and then executing the routin_projectX.py. The webapp is intended to be able to manage those project instances. My end goal: I would like to create a view that shows a table , listing all project_x subdirectories of the projects folder as rows and a few buttons with functionality as columns, specifically: edit forwards to a view where editting the config_whatever.csv files is possible, start/stop running the routine or restart-ing it, as well as delete-ing the project (removing it from the list and deleting the project directory) and less important ones (run once, read error logs), for …