Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create to select from year to year in html forms?
I want to user to input from this year to that and then I need to forward the list of years to django? But before this how to create that kind of input, I have found something like this, but it is not working what I need. Any ideas? <select name="yearpicker" id="yearpicker"></select> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script type="text/javascript"> let startYear = 1800; let endYear = new Date().getFullYear(); for (i = endYear; i > startYear; i--) { $('#yearpicker').append($('<option />').val(i).html(i)); } </script> -
heroku server error 505 in django work fine locally
i am trying to deploy my web app on heroku server but even on sucessfull deployment it throw server error 500 my settings.py import django_heroku from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES_DIR = BASE_DIR / 'templates' STATIC_DIR = BASE_DIR / 'static' MEDIA_DIR = BASE_DIR / 'media' STATIC_CDN = BASE_DIR / 'staticfiles' STATIC_URL = '/static/' STATICFILES_DIRS = [ STATIC_DIR, ] STATIC_ROOT = STATIC_CDN # MEDIA MEDIA_ROOT = MEDIA_DIR MEDIA_URL = '/media/' # crispy forms CRISPY_TEMPLATE_PACK = 'bootstrap4' # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' django_heroku.settings(locals()) my main projects urls.py from django.contrib import admin from django.urls import path, include from django.views.generic import RedirectView from django.conf.urls import url from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('', include('accounts.urls')), path('accounts/', include('django.contrib.auth.urls')), url(r'^favicon\.ico$',RedirectView.as_view(url='/static/image/favicon.ico')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root = settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) everything works fine locally an idea what causing wrong here -
Django: prefix language slug in i18n_urls
I have a django-cms site, that uses i18n_patterns in urls.py. This works, urls are built like /lang/here-starts-the-normal/etc/. Now, I would like to have urls like this: /prefix-lang/here-starts.... As there will be a couple of country specific domains, this wille be like /ch-de/here-... for Switzerland/.ch domain, /us-en/here-starts.... for the states, and some more. So, when the url would be /ch-de/..., the LANGUAGE would still be de. Hope this is clear? As the content is filled with existing LANGUAGES=(('de', 'DE'), ('en', 'EN'), ...), I cannot change LANGUAGES for every domain - no content would be found in the cms, modeltranslation, only to mention those two. How can I prefix the language slug in i18n_patterns? Is it possible at all? -
filter on new updated queryset return empty queryset using ORM Django
when looping the queryset and update field in the model using save() function, then try to filter on the updated queryset , the filter result returns empty even the there are still elements in the queryset that achieve the condition. please check the code below. qs = queryset.filter(status=models.BankTransfer.STATUS_NEW) for bank_transfer in qs: bank_transfer.status = models.BankTransfer.STATUS_APPROVED bank_transfer.save() Btw when I print qs, it returns with results, but I try to get the first object by using first(), it returns None for bank_transfer in qs.filter(purpose__status='pending_completed'): bank_transfer.purpose.status = 'completed' bank_transfer.purpose.save() -
Django, less than or equal method problem, Django documentation tutorial
I am following Django documentation tutorial (part 5) and in the .../polls/ page instead of getting the questions I made, I get: No polls are available. Files look like this: The problem should be in views.py, line 15, after the line def get_queryset, but I'm not professional! views.py: from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse from django.views import generic from django.utils import timezone from .models import Question, Choice # Create your views here. class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): return Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:5] class DetailView(generic.DetailView): model = Question template_name = 'polls/detail.html' def get_queryset(self): return Question.objects.filter(pub_date__lte=timezone.now()) class ResultsView(generic.DetailView): model = Question template_name = 'polls/results.html' def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): return render(request, 'polls/detail.html', { 'question': question, 'error_message': "You didn't select a choice." }) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results',args=(question.id,))) index.html: {% load static %} <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}"> <title>The index page</title> </head> <body> {% if lastest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are … -
Django Customized Forgot Password error (custom user model)
looking for help! I am not that experienced writing Python/Back-end code even though I am improving. In development/localserver I am trying to create a customized password reset form... but I got the following error after I submitted the email when testing the form and never received and email with the link: save() got an unexpected keyword argument 'use_https' My custom Forgot Password Form class PrivateForgotPasswordForm(forms.ModelForm): helper = FormHelper() helper.add_input(Submit('page_userForgotPassword_content_form_button_submit', static_textLanguage['global_button_submit'], css_class='global_component_button')) class Meta: model = PrivateUser fields = ['email'] widgets = { 'email': forms.EmailInput(attrs={ 'id': 'page_userForgotPassword_content_form_input_email', 'maxlength': '254', 'class': 'global_component_input_box'} ) } def __init__(self, *args, **kwargs): super(PrivateForgotPasswordForm, self).__init__(*args, **kwargs) self.helper.form_id = 'page_userForgotPassword_content_form' self.helper.form_method = 'post' self.helper.form_action = '' self.helper.form_class = 'page_userForgotPassword_content_form' My custom Forgot Password View class UserForgotPasswordView(auth_views.PasswordResetView): with open(str(settings.BASE_DIR) + "/frontend/static/frontend/languages/emails/EN/email_footer__main.json", "r") as temp_file_email_footer_main: email_footer_main_data = json.load(temp_file_email_footer_main) with open(str(settings.BASE_DIR) + "/frontend/static/frontend/languages/emails/EN/email_user_forgotPassword.json", "r") as temp_file_email_forgot_password: email_forgot_password_data = json.load(temp_file_email_forgot_password) extra_email_context = { 'email_footer_static_json_text': email_footer_main_data, 'email_static_json_text': email_forgot_password_data, 'static_json_text': static_textLanguage, 'static_json_textGlobal': static_textGlobal} html_email_template_name = '../frontend/templates/frontend/templates.emails/template.email_user_forgotPassword.html' from_email = 'support@xyz.com' subject_template_name = 'Reset password' template_name = '../frontend/templates/frontend/templates.user/template.page_forgotPassword.html' form_class = PrivateForgotPasswordForm success_url = reverse_lazy('password_reset_done') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context = { 'forgot_password_form': PrivateForgotPasswordForm(), 'email_subject': self.email_forgot_password_data['emailSubject'], 'static_json_text': static_textLanguage, 'static_json_textGlobal': static_textGlobal} return context -
Django - Migrating data inside tables for smooth release
I am using Django Rest Framework for backend development, where I have set up 2 environments. I have split settings files as required and both the environments have different DBs which are working fine, I am using Zappa(AWS lambda) for deploys, I was wondering is there an elegant way of migrating data(not models but data inside models say a few config changes) than preparing PostgreSQL DB rollouts, Could not find much on the internet, so asking here. Please let me know if there are any questions. -
What is the purpose of parameter_name in django SimpleListFilter?
What is the purpose of parameter_name in django SimpleListFilter ? It still works if parameter_name is set to empty string. class EmailFilter(SimpleListFilter): title="Email Filter" parameter_name="user_name" def lookups(self,request,model_admin): return ( ('has_email','Has Email'), ('no_email','No Email') ) def queryset(self, request,queryset): if not self.value(): return queryset if self.value() =='has_email': return queryset.exclude(user__email='') if self.value() =='no_email': return queryset.filter(user__email='') -
How to implement edit-form with Django formset?
I implemented a django-form with a formset. When I create a new object it works. But I faced to a problem with editing form when I don't change formset data (only data outside formset). Formset raises errors: id requeired. If I mark formset fields to delete and then add new fields it works too. Please, explain me what's going wrong and how to solve this problem. Thanks! My formset: IngredientsFormSet = forms.inlineformset_factory( Recipe, RecipeIngredientsDetails, fields="__all__", can_delete=True, min_num=2, max_num=50, extra=0, ) And my view-function: def recipe_edit(request, recipe_id=None): if recipe_id: recipe = get_object_or_404(Recipe, id=recipe_id) else: recipe = Recipe() if request.method == "POST": form = RecipeCreateForm(data=request.POST, files=request.FILES) formset = IngredientsFormSet(data=request.POST, prefix=INGREDIENT_FORMSET_PREFIX) if form.is_valid() and formset.is_valid(): recipe = form.save(commit=False) recipe.author_id = request.user.id recipe.save() form.save_m2m() formset.instance = recipe formset.save() return redirect(reverse_lazy("index")) context = {"form": form, "formset": formset} return render(request, template_name="recipe-create.html", context=context) form = RecipeCreateForm(instance=recipe) formset = IngredientsFormSet( instance=recipe, prefix=INGREDIENT_FORMSET_PREFIX, ) context = { "form": form, "formset": formset, } return render(request, context=context, template_name="recipe-create.html") -
Why does stripe card element not load up when using django stripe?
Hi I've been trying to learn how to build an ecommerce site and am getting stuck with the Django Stripe integration for a custom pay flow. I can get the pre built checkout to work but can't for custom pay flow. Stripe seems to have updated the code on their docs a few months ago so when I try to look up tutorials, they all don't seem to have the same code and I can't seem to figure out how to get it to work. I'm self taught and just a beginner/intermediate maybe so might be missing something obvious. I'm using the code from this page https://stripe.com/docs/payments/integration-builder and trying to convert it into Django. This is my views.py from django.shortcuts import render import stripe from django.http import JsonResponse import json # Create your views here. from django.views import View stripe.api_key = "xxxxxxxxx" class StripeIntentView(View): def post(self, request, *args, **kwargs): try: intent = stripe.PaymentIntent.create( amount=2000, currency='usd' ) return JsonResponse({ 'clientSecret': intent['client_secret'] }) except Exception as e: return JsonResponse({'error':str(e)}) def payment_method_view(request): return render(request, 'custom-landing.html') This is my urls.py from django.contrib import admin from django.urls import path from products.views import payment_method_view,StripeIntentView urlpatterns = [ path('admin/', admin.site.urls), path('custom-landing/', payment_method_view, name='custom-landing-page'), path('create-payment-intent/', StripeIntentView.as_view(), name='create-payment-intent'), ] … -
Very confusing question regarding WEB dev
I have gotten the following questions which is so ambiguous, does anybody knows the answer? You create a static web site that simply consists of several HTML files on a web server. What possible difficulty might you run into with this setup as you continue to maintain your site? a. Updating URL design would require many edits throughout the site b. All of these c. Hyperlinks between pages of the site could become inconsistent d. Changes to the site’s look and feel would need to be made in many files -
Crontab Django Management command seems to start but nothing happens
I have defined a django management command that imports some data into my application database. I run it using a crontab. Sidenote: everything is inside a docker container. This command works perfectly when I use it manually in my container's shell. However, when crontab tries to run it, nothing happens. My crontab line is the following : * * * * * nice -n 19 /usr/local/bin/python3 /code/manage.py my_command "a string argument for my command" # a comment to find the cron easily (I put my code into /code because it seemed a good idea at the time.) I know that crontab calls my command, because /var/log/syslog displays when it is executed. I cannot fathom the reason why nothing happens. As a test in the "handle" method of my command, I wrote print("handling command") as the first line then added >> /code/cron.log at the end of my crontab line. The text didn't appear in the file. Any idea ? -
How to fetch users that i follow?
I want to make a viewset to allow request.user (Authenticated user) to receive the users in a view that they follow. But i do not know how to make an appropriate queryset filter for it. Models (Note: Author is the one following,profile is the one followed) class User(AbstractUser,PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.CharField(max_length=255,unique=True) username =models.CharField(max_length=40,unique=True,default='undefinedusername') class UserFollow(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='following') profile = models.ForeignKey(User,on_delete=models.CASCADE,related_name='followers') View class FetchUserViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) queryset = User.objects.all() serializer_class = UserSerializer filter_backends = [FollowedUserFilterBackend] Filter class FollowedUserFilterBackend(filters.BaseFilterBackend): def filter_queryset(self, request, queryset, view): return queryset.filter( ??? ) I tried following__author = request.user but it returns the user that made the request,not the user that user follows. How can i do it? -
Trying to join a query for salesforce on python
I want to make a query from salesforce using an id opportunity_id="0061g00000BRG00AAH" query = "SELECT+FIELDS(ALL)+FROM+Opportunity+WHERE+ID+=+'"+opportunity_id+"'" print(json.dumps(sf_api_call('/data/v51.0/query/', {"q": query}))) But I get this error: b'[{"message":"\\nSELECT+FIELDS(ALL)+FROM+Opportunity+WHERE+ID+=+\'0061g00000BRG00AAH\'\\n ^\\nERROR at Row:1:Column:6\\nunexpected token: \'+\'","errorCode":"MALFORMED_QUERY"}]' -
How to get multiple fields of a django form in one row
Hej! I want to have multiple fields of a django form next to each other. (Input fields to search in a table) For now I can get them under each other with this template: <form method="post"> {{ form.as_p }} {% csrf_token %} <input type="submit" value="Search"> </form> or two next to each other with: <div class="container"> <div class="row"> {% for field in form %} <div class="col-sm-6"> {{ field.label_tag }} {{ field }} </div> {% endfor %} </div> </div> but then I loose the 'form' of the forms. How can I get multiple (let's say 5) fields in one row? All ideas welcome! Thanks for the help :) -
Definition of the structure of a REST API with django from a data format
I was asked to write an API interface which should retrieve data from a connected object. The format of this data is as follows: { "devEUI": "8cf9572000023509", "appID": 1, "type": "uplink", "time": 1629378939869, "data": { "gwid": "b827ebfffebce2d3", "rssi": -77, "snr": 10, "freq": 868.1, "dr": 5, "adr": true, "class": "C", "fCnt": 852, "fPort": 8, "confirmed": false, "data": "AgUCIzYBAIERAAAAAAAAAAAAAAAAAAAAAAAAAADHDgA=", "gws": [ { "id": "b827ebfffebce2d3", "rssi": -77, "snr": 10 } ] } } I develop with django. I want to write a REST api with django.Should the data and gws fields be classes? How can I define the classes? -
Passing a token in the header of a ListAPIView endpoint from one api to another Django REST
I have 2 APIs in Django REST. One API generates a JWT token. I want to send that token to another API. In the first API (API 1), I am posting the token to the ListItems class (/someendpoint/) in the header of the POST request. import requests token = "someToken" requests.post("/posting/token", {token}) In another API (API 2), I want to receive that JWT token in the request header : in views.py: class ListItems(generics.ListAPIView): permission_classes = [ItemsPermissions] queryset = SomeModel.objects.all() serializer_class = SomeSerializer in urls.py: url_patterns = [ path("/someendpoint/list/", ListItems.as_view(), ] What is the best way to achieve that ? -
https with nginx and docker compose not working
Please I need some assistance. Your contributions will be greatly appreciated I am trying to add ssl to my nginx and docker compose configuration. Currently, everything works fine with http, but it won't work with https. Here is my docker-compose.yml file version: '3.8' services: web_gunicorn: image: ACCT_ID.dkr.ecr.us-east-2.amazonaws.com/web_gunicorn:latest volumes: - static:/static - media:/media # env_file: # - .env pull_policy: always restart: always ports: - "8000:8000" environment: - PYTHONUNBUFFERED=1 - PYTHONDONTWRITEBYTECODE=1 nginx: image: ACCT_ID.dkr.ecr.us-east-2.amazonaws.com/nginx:latest pull_policy: always restart: always volumes: - static:/static - media:/media - ./certbot/conf:/etc/letsencrypt - ./certbot/www:/var/www/certbot ports: - "80:80" - "443:443" depends_on: - web_gunicorn certbot: image: certbot/certbot restart: unless-stopped volumes: - ./certbot/conf:/etc/letsencrypt - ./certbot/www:/var/www/certbot depends_on: - nginx entrypoint: "/bin/sh -c 'trap exit TERM; while :; do certbot renew; sleep 12h & wait $${!}; done;'" volumes: static: media: Here is my nginx.conf configuration that works (http) upstream web { server web_gunicorn:8000; } server { listen 80; server_name domain.com; location / { resolver 127.0.0.11; proxy_pass http://web; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /static/; } location /media/ { alias /media/; } } Here is my nginx.conf configuration that does not work (http and https) upstream web { server web_gunicorn:8000; } server { location / { resolver 127.0.0.11; … -
Django ListView derived classes ignoring paginate_by field
I am using Django 3.2 I am using OOP to keep my code DRY. I have a base class Foo (which derives from ListView), and I am setting common properties in that class. I then have two specialisations of Foo - which I expect to be cognisant of the paginate_by member variable - however, the subclasses seem to be ignoring the variable I set paginate_by to, as it has no effect. This is my code: class UserFooList(LoginRequiredMixin, ListView): http_method_names = ['post'] paginate_by = 2 def post(self, request, *args, **kwargs): # some processing logic return render(request, '/path/to/Foo_list.html', context=context, status=status_code) class UserApprovedFooList(UserFooList): def get_queryset(self): return Foo.objects.prefetch_related().filter(/* query criteria one */) class UserFoosInModerationQueueList(UserFooList): def get_queryset(self): return Foo.objects.prefetch_related().filter(/* query criteria two */) Why is the paginate_by field being ignored by UserApprovedFooList and UserFoosInModerationQueueList - and how do I resolve this? -
{% include %} django template issue
I'm trying to connect my header for a new file, I do it like this {% include filename%}. in other files it works without any problem. Now it only connects the html itself but without statics. {% load static %} <!DOCTYPE html> <html > <head> <meta charset="UTF-8"> <title>Sign In/Up</title> </head> {% include 'inc/_header.html' %} settings STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'essense/static'), ] -
django.db.utils.OperationalError : This probably means the server terminated abnormally (only Django app)
I am currently trying to connect to a Sage Evolution server from a django web application The below error is displayed when I run "inspectdb" or "inspectdb > models.py" The server does connect when I ping it through the command prompt and connect to it via the .bat file I had created to test the connection. So I don't see why it would be an error on the servers side C:\Users\KylePOG\Documents\GMA Programming\accConnect>python manage.py inspectdb > models.py Traceback (most recent call last): File "C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\base.py", line 219, in ensure_connection self.connect() File "C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\postgresql\base.py", line 187, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\psycopg2\__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\KylePOG\Documents\GMA Programming\accConnect\manage.py", line 22, in <module> main() File "C:\Users\KylePOG\Documents\GMA Programming\accConnect\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) … -
Django RestAPI but without CSS
I am making an REST API using Django Restframework It works perfectly but I get an error when I have pushed it to railway app like this Installing SQLite3 -----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "/workspace/manage.py", line 22, in <module> main() File "/workspace/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle collected = self.collect() File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 114, in collect handler(path, prefixed_path, storage) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 338, in copy_file if not self.delete_file(path, prefixed_path, source_storage): File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 248, in delete_file if self.storage.exists(prefixed_path): File "/app/.heroku/python/lib/python3.9/site-packages/django/core/files/storage.py", line 318, in exists return os.path.exists(self.path(name)) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/storage.py", line 38, in path raise ImproperlyConfigured("You're using the staticfiles app " django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. ! Error while running '$ python manage.py collectstatic --noinput'. See traceback above for details. You may need to update application code to resolve this error. Or, you can disable collectstatic for this application: $ heroku config:set DISABLE_COLLECTSTATIC=1 https://devcenter.heroku.com/articles/django-assets ERROR: failed … -
{'required': 'This field is required.', 'null': 'This field may not be null.', 'invalid': 'Invalid data. Expected a dictionary, but got {datatype}.'}
This is the error which is thrown by the serializer.is_valid(). I don't know why this error come. I am new to Django Rest Framework. I am trying to make a simple invoice generating api. which takes info about seller, buyer, items and generate a invoice. So I write models for each and one model for invoice in which seller, buyer are foriegn key. Item model is related to invoice model through a foreign key. Any Help is appreciated. This is my models.py class Seller(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=50) phone = models.CharField(max_length=12) address = models.CharField(max_length=200) def __str__(self): return self.name class Buyer(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=50) phone = models.CharField(max_length=12) address = models.CharField(max_length=200) def __str__(self): return self.name class Invoice(models.Model): id = models.AutoField(primary_key=True) seller = models.ForeignKey(Seller, on_delete=models.CASCADE) buyer = models.ForeignKey(Buyer, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) def total_amount(self): total = Decimal('0.00') for item in self.items.all(): total = total + item.total() return total def invoice_number(self): if len(str(self.id))==1: return 'Invoice00'+self.id elif len(str(self.id))==2: return 'Invoice0'+self.id else: return 'Invoice'+self.id def __str__(self): return f'{self.seller} {self.buyer} {self.date}' class Item(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=20) invoice = models.ForeignKey(Invoice, on_delete=models.CASCADE) price = models.DecimalField(decimal_places=2, max_digits=20) quantity = models.IntegerField(default=1) tax = models.DecimalField(decimal_places=2, max_digits=4) def total(self): total = Decimal(str((self.price-self.tax)*self.quantity)) return total.quantize(Decimal('0.01')) def … -
Django FilterSet, Count and Distinct
I'm building a custom filter for a model, and I wanted to have two optional boolean fields that would alter the way the queryset is created. One boolean for distinct, that would make the result be only unique values, like in .distinct(), and another boolean for count, that would instead return the number of items, like with a .count() I have found this: https://django-filter.readthedocs.io/en/stable/ref/filters.html#distinct but i cant really understand how to use it. Also, I haven't found a way for count My filter looks like this: class MyModelFilter(django_filters.FilterSet): class Meta: model = Inventory fields = ( "service", "provider" "recorded_at", "tenant", "tenant_name", "project_system", "area", "environment", "region", ) data_filter = django_filters.CharFilter(method="json_filter") def json_filter(self, queryset, name, value): string_to_json = json.loads(value) return queryset.filter(data__contains=string_to_json) -
Access a Django server from a VM Linux deployed with Amazon EC2
I have developed a Django app on a Amazon EC2 virtual machine which I access using ssh. When I run python manage.py runserver, everything works fine, and I have Django version 3.2.6, using settings 'crm.settings' Starting ASGI/Channels version 3.0.4 development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. The thing is I would like to see the result of this app in a browser, either on the VM or in the browser of my computer (of course 127.0.0.1 is not working on my "main" Linux) So far, I have tried ipconfig in the VM, but I do not know what to do with the output. Do you guys have any idea / clue? Any assistance is appreciated, feel free to ask for specifications. Thanks in advance