Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Change queryset based on query_param
I'm using django-filters, but I've been having some issues using it alongside an annotation. The use case here is that I want the /streams viewset to return only Stream objects with at least 1 ManyToMany to a Tag. class StreamViewSet(viewsets.ModelViewSet): queryset = Stream.objects.annotate(num_tags=Count("tags")).filter(num_tags__gt=0) serializer_class = StreamSerializer filterset_class = StreamFilterSet def filter_queryset(self, queryset): filter_backends = (filters.DjangoFilterBackend,) for backend in list(filter_backends): queryset = backend().filter_queryset(self.request, queryset, view=self) return queryset @action(detail=True, methods=["patch"]) def add_tags(self, request, pk): tag_names = request.data["tags"] stream = Stream.objects.get(pk=pk) for tag_name in tag_names: tag = Tag.objects.get(name=tag_name) stream.tags.add(tag.id) stream.save() return Response(f"Added {len(tag_names)} tags to {stream.id}.") if query_param tagless is False or not provided I'd like to use num_tags__gt=0, but if tagless is True, I'd like to use Stream.objects.all(). I can't seem to figure out how to achieve this result. Any help in the right direction is appreciated. -
What is the difference between the fields associated with choice and to in the django model?
What is the difference between the fields associated with choice and to in the django model? eg what is the difference between frontal and number_of_rooms field What is the difference between defining choice and creating a model and defining the domain of another model? thanks in advance #django models.py class Advertise(models.Model): owner = models.ForeignKey(to="advertise.User", on_delete=models.CASCADE, null=True) title = models.CharField(max_length=100) description = models.TextField(max_length=500) price = models.PositiveIntegerField(default=0) square_meter = models.PositiveIntegerField(default=0) number_of_rooms = models.PositiveIntegerField(choices=NumberOfRoomsChoices.CHOICES) building_age = models.PositiveIntegerField(choices=NumberOfBuildingAgeChoices.CHOICES) floor = models.PositiveIntegerField(choices=NumberOfFloorChoices.FLOOR_CHOICES) number_of_floors = models.PositiveIntegerField(choices=NumberOfFloorChoices.FLOORS_CHOICES) number_of_bathrooms = models.PositiveIntegerField(choices=NumberOfBathroomsChoices.CHOICES) heating = models.PositiveIntegerField(choices=HeatingChoices.CHOICES) balcony_exists = models.BooleanField(default=False) using_status = models.PositiveIntegerField(choices=UsingStatusChoices.CHOICES) fee = models.PositiveIntegerField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) status = models.PositiveIntegerField(choices=AdvertiseStatusChocies.CHOICES) visibility = models.PositiveIntegerField(choices=AdvertiseVisibilityChoices.CHOICES) # collections frontal = models.ManyToManyField(to="advertise.Frontal") interior_feature = models.ManyToManyField(to="advertise.InteriorFeature") exterior_feature = models.ManyToManyField(to="advertise.ExteriorFeature") locality = models.ManyToManyField(to="advertise.Locality") transportation = models.ManyToManyField(to="advertise.Transportation") landscape = models.ManyToManyField(to="advertise.Landscape") sutiable_for_disabled =models.ManyToManyField(to="advertise.SuitableForDisabled") def __str__(self): return f"{self.title}" -
my django 3 project is shwoing 'ModelForm has no model class specified'
i am a beginner django developer, "ModelForm has no model class specified. " is given on my project , what i can do pls help, i will be greatfull to you if you solve my problem models.py from django.db import models class product(models.Model): name = models.CharField(max_length=50) forms.py from django.forms import ModelForm from .models import product class productform(ModelForm): class Meta: model:product fields: '__all__' views.py from django.shortcuts import render from formt.forms import productform def index(request): form = productform() context = { 'form' : form } return render(request, 'index.html' , context ) index.html <h1>form model</h1> <form action=""> {% csrf_token %} {{form}} <input type="submit" text="submit"> </form> -
Django Rest Framework: Creating a custom create method for a writable nested presentation
I'm trying to create a custom create method for a hyperlinked model serializer in Django Rest Framework. I'm following the documentation on how to create said method. The issue I'm having is that none of the data from the foreign key relation is being validated. The data itself is coming through (I can check this by printing self in the serializer), but in the validated data "Skills" ends up being an empty ordered dict. I'll show an example of this below, after presenting my models, serializers, views and urls. Here's my model. It's modeling a work experience entry in a resume: class WorkExperience(models.Model): title = models.CharField(max_length=256, default="Title") description = models.TextField(default="Description of the work") organization = models.CharField(max_length=256, default="Acme Inc.") start_date = models.DateField(null=True) end_date = models.DateField(null=True) skills = models.ManyToManyField(Skill, related_name="work") owner = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=False, default=1, related_name="work_experience", ) resume = models.ForeignKey( Resume, on_delete=models.CASCADE, null=False, default=1, related_name="work_experience", ) def __str__(self): return f"{self.owner.email} work experience as {self.title}." class Meta: ordering = ["id"] My Serializer for the model looks like this: class WorkExperienceSerializer(serializers.HyperlinkedModelSerializer): skills = SkillSerializer(many=True) class Meta: model = WorkExperience fields = [ "title", "description", "start_date", "end_date", "organization", "skills", ] def create(self, validated_data): print("print self: ", self) # Here I'm printing self print("print … -
Nginx not serving staticfiles correctly on docker?
I want nginx to act as a reverse proxy and serve static files for django (api). docker-compose.yml: version: '3' services: api: build: api container_name: api volumes: - static_volume:/home/admin/api/static ports: - "8000:8000" env_file: - ./config/api/.env depends_on: - db db: image: postgres:latest container_name: db volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./config/api/.env-db nginx: image: nginx:latest container_name: ngx volumes: - static_volume:/home/admin/api/static - ./config/nginx:/etc/nginx/conf.d ports: - "80:80" depends_on: - api volumes: postgres_data: static_volume: config/nginx/default.conf: upstream refridge { server api:8000; } server { listen 80; location / { proxy_pass http://refridge; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { autoindex on; alias /home/admin/api/static/; } } After spinning them up with docker-compose up -d --build and running django's migrate and collectstatic command, I see the following logs when trying access django's admin page: docker logs api Waiting for postgres... PostgreSQL started [2020-08-17 20:26:04 +0000] [1] [INFO] Starting gunicorn 20.0.4 [2020-08-17 20:26:04 +0000] [1] [INFO] Listening at: http://0.0.0.0:8000 (1) [2020-08-17 20:26:04 +0000] [1] [INFO] Using worker: sync [2020-08-17 20:26:04 +0000] [30] [INFO] Booting worker with pid: 30 [2020-08-17 20:26:04 +0000] [31] [INFO] Booting worker with pid: 31 [2020-08-17 20:26:04 +0000] [32] [INFO] Booting worker with pid: 32 Not Found: /static/admin/css/responsive.css Not Found: /static/admin/css/login.css Not Found: /static/admin/css/base.css … -
ModuleNotFoundError: No module named 'profiles.url'
Can anyone tell why it's showing ,my code is correct. view.py from django.shortcuts import render from django.http import HttpResponse def test_view(request): string = "hello world" return HttpResponse(string) url.py from django.urls import path from .views import test_view app_name = 'profiles' urlpatterns = [ path('',test_view, name ='test-view-1') Two errors first error is `ModuleNotFoundError: No module named 'profiles.url'` second error is [1]: https://i.stack.imgur.com/LfY0J.png -
Django - override existing data, after admin approval?
I have been tasked with adding some new functionality to an existing view. Basically, on user signup if the company is already in the database, I am sending an email to an admin, saying "User wants to claim company". If admin approves, that user will be added to the company, and I want to override the previous info (address, phone, etc.) with the info this user put in at registration. I thought the best way to do this was to add a field to the Account model, called is_approved and set it to False, and when the admin approves, they will set it to True and the new info will be stored, overriding the existing data. I have a Company model, and a Pending_Companymodel, both with the same exact info. My view... company_obj = Company.objects.filter(I am filtering the DB here) if not company_obj: """If no company match, create new one""" new_company = Company.objects.create( name=company.title(), zip=int(zip_code), primary_email=email, website=website, phone_no=phone_no, street=street, city=city, state=state, ) new_company.owner.add(user) else: """Add employee to company, send email to admin for approval, if approved, update company instance with new data.""" # If DEBUG = True send_mail('Test Subject', 'Test message', 'test@gmail.com', ['testemail@gmail.com', ], fail_silently=False) pending_company = PendingCompanyDetail.objects.create( name=company.title(), zip=int(zip_code), … -
vscode devcontainer causes "The folder you are executing pip from can no longer be found."
I have a docker containerized Django project. I also use vscode devcontiners. If I don't start vscode with its associated devcontainer I am able to run management commands from the terminal like this: docker-compose run manage migrate But if I open vscode and start programing within the devcontainer the next time I try to run the management command I get this error: The folder you are executing pip from can no longer be found. The odd thing is that I am still able to run other docker commands from the terminal without issue such as this: docker-compose run --rm tests Of note this was not always the case. I say it probably started around 3 months ago. The only other time I've heard about this error happening before when a container is started with "delegated" volumes. I’m not sure if vscode uses delegated volumes or not. May be able to add more files to this post if nessisary. -
Django DRF calculated fields check
I want to check if the computational values coming from the frontend to the price table are correct. E.g; The discount added to this by giving the Sales Price, the early booking discount is reduced to CostPrice. The difference between CostPRice and SalesPrice gives profiRate. The webFakePrice is calculated by calculating the salesPrice * webFakePriceRate for the price to be fake on the web. I want to check if these FrontEnd are calculated correctly. I could not find a keyword for it. How should I loop this since there are multiple record in one? Model.py salesPrice = models.FloatField (blank = True, null = True) costPrice = models.FloatField (blank = True, null = True) commissionRate = models.FloatField (blank = True, null = True) discountRate = models.FloatField (blank = True, null = True) earlyBookingRate = models.FloatField (blank = True, null = True) totalCommission = models.FloatField (blank = True, null = True) profitRate = models.FloatField (blank = True, null = True) webFakePriceRate = models.FloatField (blank = True, null = True) webFakePrice = models.FloatField (blank = True, null = True) view.py def create (self, request, * args, ** kwargs): many = True if isinstance (request.data, list) else False serializer = PriceSerializer (data = request.data, … -
Getting the post instance in Django class based views
I currently use a function based view to let users write comments on posts, but I'm trying to convert it to class based views Function views.py def comment(request, pk): form = CommentForm(request.POST) # Post instance post_instance = get_object_or_404(Post, pk=pk) if request.method == 'POST': if form.is_valid: obj = form.save(commit=False) obj.commenter = request.user obj.post = post_instance obj.save() return redirect('/') else: messages.error(request, 'Comment Failed') return render(request, 'comment.html', {'form': form}) Class views.py class CommentView(FormView): template_name = 'comment.html' form_class = CommentForm success_url = '/' def get_object(self): pk = self.kwargs.get('pk') post_instance = get_object_or_404(Post, pk=pk) return post_instance def form_valid(self, form): obj = form.save(commit=False) obj.commenter = self.request.user obj.post = post_instance obj.save() return super().form_valid(form) I'm trying to implement the same logic for saving the comment but I get the error: name 'post_instance' is not defined get_object() is returning the 'post_instance' variable but I can't access it. Could you guys show me where I'm doing a mistake, thanks in advance! -
Which SQL paradigm to use when grouping counts by type?
Let's say I have a database with data from a pizza shop in it. I keep track of customers and their orders via two tables: customer and orders. orders has a FK to customer so that I can easily see which orders belong to which customer. I can count all of the customer's orders like this: SELECT c.id, COUNT(o.id) AS order_counts FROM customers AS c, JOIN orders ON c.id = o.customer_id GROUP BY c.id Which gives me something like this: results = [ { “customer_number”: 1, “order_counts”: 5 }, { “customer_number”: 2, “order_counts”: 10 }] However, what if I want to "explode" the order_counts results to show me all the individual pizza types, and then count those types? I would add a new table called pizzas which has a name column, and then get my results to look like this: results = [ { “customer_number”: 1, “counts”: { “Hawaiian”: 2, “Meat Lovers”: 2, "Four Cheese": 1 } }, { “customer_number”: 2, “counts”: { “Hawaiian”: 5, “Meat Lovers”: 5, "Four Cheese": 0 } }] Which SQL principals/paradigms would I need to leverage to achieve this? I suspect I need a subquery and/or a nested GROUP BY statement. Bonus Question: is this … -
Getting 'RelatedObjectDoesNotExist' error in Django when I edit a field in my admin page
I am trying to create dynamic detail pages for my ecommerce website in django. I added a slug field in my models.py file and migrated it. However, when I edit my slug field in the admin page I get the follwoing error. [Error.] [1]: https://i.stack.imgur.com/EMu9U.gif [code for models.py] https://i.stack.imgur.com/SZVj0.png Is there a step I missed? -
given a date start and date end, give me the duration in an array of 24 values corresponding to hours of the day
I am very new to Django rest framework and stack overflow even, I was struggling with finding a title so please feel free to give a better alternative. I have a set of jobs that get posted to a database. the jobs are now grouped per machine and per given hour. For now I am only displaying the total count of jobs per hour. My API end point looks like this now : Api end point Here's where I am struggling: I need to get the duration of the job separated by hour. I have a Datetime when it started and a Datetime when it ended. I also have a total of the duration. For example: suppose a job starts at 11h15 and ends at 12h15. this would mean that for hour 11 the total duration is 45 minutes. For hour 12, the duration is 15 minutes. I thought of getting the time passed between 11h15 and 12h00 and then the time passed between 12h15 and 13h00. But I am not exactly sure how i could do this. also note that some jobs go for more than an hour and some even more than a day. I am sure there … -
Django .create() for each item in queryset? Like: Reporter.objects.all().article_set.create(...)
https://docs.djangoproject.com/en/3.1/topics/db/examples/many_to_one/, Taking Django's Reporter/Article as a comparable example for my real problem, i need to create one new article for each reporter in my queryset. My approach now is as follows: reporters = Reporter.objects.filter(...) for reporter in reporters: article = Article() article.reporter = reporter ... article.save() The problem is that i have 25k "reporters", so it takes too long to process the request and raises timeout. I wonder if there is a better method for that, sort of like: Reporter.objects.filter(...).article_set.create(...) -
django postgresql timestamp on entry creation is not ordered in the database
I am quite new to django and I have a small app, with the following models: class TimeStampedModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: abstract = True class SomeModel(TimeStampedModel): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) some_json = JSONField(blank=True,default=dict) def __str__(self): return self.uuid I now make some requests to a webserver and write the return value of the request to the database via model forms like so: data = requests.get(BASE_URL) form_data=collections.OrderedDict() form_data[ "some_json" ] = data.json() form = SomeModel (form_data) if form.is_valid(): form.save() logger.debug( "***** GOOD: form saved from %s", data.json() ) else: logger.debug("** form not valid because: %s ", form.errors) pass It seems to work fine, but when I inspect the database I see that the timestemps are not ordered :( So, the top 5 entries on the database look like so (for the created_at field): 2020-08-17 19:59:14.377394+01 2020-08-17 19:58:31.017813+01 2020-08-17 20:00:33.302018+01 2020-08-17 19:59:57.626536+01 2020-08-17 19:59:07.671274+01 I am baffled as to how the database can write in non-ascending time stamps.. Am I missing something here? Shouldnt the database contain ordered values for the created_at field? My naive thinking leads me to think: [1] I make the rerquest and get data [2] write data to database this process should create … -
Django ORM uses wrong string searching for foreign object
I have two models: Account and SourceDocument (posted below). When I create a SourceDocument, I first get the correct Account, set it to the SourceDocument.account field and then save SourceDocument. The expected result is for SourceDocument.account to be the same as the Account object I queried. However, it's using the wrong string to search for the object during .save() and the ORM is trying to search using Account.code. The string used to find the object was correct a couple of weeks ago. It has since changed. At first, I thought there was an issue with Postgres. I did REBUILD TABLE accounting_account and REBUILD DATABASE with no change. Originally, the Account.code field was unique so I removed the index with no change. Using the helpful debugsqlshell command from django-debug-toolbar, I've found the issue likely lies within the Django ORM, but I'm not sure where. Here's the debugsqlshell testing I did: >>> from accounting.models import * >>> a = Account.objects.get(is_receivable=True) SELECT "accounting_account"."id", "accounting_account"."code", "accounting_account"."name", "accounting_account"."description", "accounting_account"."type", "accounting_account"."is_payable", "accounting_account"."is_receivable", "accounting_account"."is_bank", "accounting_account"."allow_payments" FROM "accounting_account" WHERE "accounting_account"."is_receivable" LIMIT 21 [1.99ms] >>> a.pk 11 >>> a.code '1210' >>> s = SourceDocument() >>> s.account = a >>> s.save() SELECT "accounting_account"."id", "accounting_account"."code", "accounting_account"."name", "accounting_account"."description", "accounting_account"."type", "accounting_account"."is_payable", "accounting_account"."is_receivable", "accounting_account"."is_bank", … -
How to pass variable to TabularInline admin template?
I need to add a few custom rows (which are different model) to admin inline so that everything looks seamlessly as one table. My idea was to include admin/edit_inline/tabular.html in new template and add a custom table below. Then I'd create a custom admin view that would handle saving etc. My issue is that I cannot find a way to pass any variable to InlineModelAdmin template - I thought any variable at top level in class is available in template via {{ variable }} tag - this way I could pass my table structure to template and generate it there. -
Django App deployed to EB Could not translate host name
I tried to send an email after an user object gets created. I use celery to perform the task. My application was deployed to AWS Elastic Beanstalk (Linux2 Python3.7). I have one RDS configured for my environment. Whenever I created a new user, my celery worker got the same error as follow: This is the error I got in celery-worker.log [2020-08-17 10:51:20,667: INFO/MainProcess] Received task: account.tasks.send_user_email_when_user_created_by_admin[0c202693-43b7-44b7-a9b9-0362bc38afac] [2020-08-17 10:51:20,675: WARNING/ForkPoolWorker-1] Sending email for new usr [2020-08-17 10:51:20,693: ERROR/ForkPoolWorker-1] Task account.tasks.send_user_email_when_user_created_by_admin[0c202693-43b7-44b7-a9b9-0362bc38afac] raised unexpected: OperationalError('could not translate host name "aa1rm1r9klym9tk.ce9nktrqundw.us-west-2.rds.amazonaws.com" to address: Name or service not known\n') Traceback (most recent call last): File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection self.connect() File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/db/backends/base/base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/db/backends/postgresql/base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "/var/app/venv/staging-LQM1lest/lib64/python3.7/site-packages/psycopg2/__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not translate host name "aa1rm1r9klym9tk.ce9nktrqundw.us-west-2.rds.amazonaws.com" to address: Name or service not known This is the code I used for sending an email to user @receiver(post_save, sender=User) def create_profile_handler(sender, instance, created, **kwargs): if created: profile = models.Profile(user=instance) profile.save() transaction.on_commit(tasks.send_user_email_when_user_created_by_admin.delay(instance.id)) I don't know where this host name came from as I couldn't find such rds under my account. I did the nslookup aa1rm1r9klym9tk.ce9nktrqundw.us-west-2.rds.amazonaws.com 8.8.8.8 and … -
Django rest api custom class implementation
I have created a class for retrieving data about a specific food product from farsecret API. In class I have created 3 functions for: *obtaining authorization *getting id of item, for which we are looking *download data of item class IngredientImport(APIView): def get_authorization_token(self): request_token_url = "https://oauth.fatsecret.com/connect/token" consumer_key = os.environ.get('NTS_Client_ID') consumer_secret = os.environ.get('NTS_Client_Secret') data = {'grant_type':'client_credentials', "scope":"basic"} access_token_response = requests.post( request_token_url, data=data, verify=False, allow_redirects=False, auth=(consumer_key, consumer_secret) ) return access_token_response.json()["access_token"] def get_list_by_name(self, name, access_token): api_url = "https://platform.fatsecret.com/rest/server.api" params={ "method":"foods.search", "search_expression":name, "page_number":1, "max_results":1, "format":"json" } header = {"Authorization":access_token} api_call_headers = {"Authorization": "Bearer " + access_token} response = requests.get( api_url, params=params, headers=api_call_headers ) items = response.json()["foods"] try: return response.json()["foods"]["food"]["food_id"] except KeyError: return None def import_item(self, item_id, api_token): if item_id == None: return None api_url = "https://platform.fatsecret.com/rest/server.api" params={"method":"food.get", "food_id":item_id, "format":"json"} api_call_headers = {"Authorization": "Bearer " + access_token} response = requests.get( api_url, params=params, headers=api_call_headers ) item = response.json()["food"]["servings"]["serving"] item_name = response.json()["food"]["food_name"] if type(item) == list: item = item[0] try: portion_size = float(item["metric_serving_amount"]) carbs = round(float(item["carbohydrate"]) / portion_size * 100, 2) fats = round(float(item["fat"]) / portion_size * 100, 2) proteins = round(float(item["protein"]) / portion_size * 100, 2) except KeyError: return None How can I implement this class in my aplication to avoid creating 3 different paths in … -
Django 2.2 compatibility with PostgreSQL
I'm working on a Django app on a Linux server and found out the existing PostgreSQL isn't supported by Django. If Postgres is upgraded to the most recent version (looks like v 12), will it be compatible with Django 2.2 and psycopg2 version 2.8.5? Is there a "too new" version of Postgres that I should worry about for either Django or psycopg2? I've tried to answer this question for myself using the relevant Django docs and psycopg docs, and I think everything will be okay, but I haven't found a definitive answer. I just don't want to have to make the system administrator uninstall and reinstall and older version of Postgres. -
Django-sitetree item.is_current always returns False
I have the following code in my nav.html: ..... {% sitetree_menu from "menu" include "trunk" template "nav/nav-item.html" %} ..... and following in my nav-item.html file: {% load sitetree %} <ul class="navbar-nav"> {% for item in sitetree_items %} <li class="nav-item"> <a href="{% sitetree_url for item %}" class="nav-link {% if item.has_children %}dropdown-toggle{% endif %} {% if item.is_current or item.in_current_branch %} active {% endif %}">{{item.title_resolved}} </a> {% if item.has_children %} {% sitetree_children of item for menu template 'nav/nav-sub-item.html' %} {%endif%} </li> {% endfor %} </ul> All features of sitetree are working well but item.is_current always returns False. I can't understand what the problem is. Has anybody experienced such kind of problem? -
Django - referencing value from template in views.py
I have a Pandas dataframe that I am displaying as an HTML table. I turned the first column of that table into a column of clickable buttons that return a unique value and link to a webpage with information regarding the selected topic. The col. was turned into a button with the following format: '<button type="submit" name="info" value=' + df['Name:'] + '>More Info</button>' However, in order to display the unique page when the button is clicked I need to be able to reference the button "value" I have tried referencing the button value from my view in the following ways: if request.POST.get('info', ''): value = info.value return redirect('detail') if request.POST.get('info'): value = value return redirect('detail') However, neither "value" or "info" can be called. Does anyone know how I can reference the value of the button from my views.py? -
django & postgres timezone localtime vs utc
I save a datetime to my postgres db, when I then display it on my website it's wrong... In my models.py: datetime_start = models.DateTimeField() In postgres the time is saved like this: utc+2h: In my django I made following settings: USE_TZ = True TIME_ZONE = 'Europe/Paris' In my template I get the time, for testing I display once the utc and once the localtime: <th> Start </th> <td>{{activity.datetime_start |utc|date:"d.m.Y H:i"}}</td> <td>{{activity.datetime_start |localtime|date:"d.m.Y H:i"}}</td> And here the output on my website: Why this output is wrong? The utc time should be: 06:00 And the localtime should be: 08:00 I'm confused, what did I make wrong with the timezones and times? Does django interpret the postgres time wrong? -
File Type conversion in Django
I have started doing a project that converts file from one type to another like from .pdf to .doc etc. But in django I'm not able to access the file and pass it to the conversion program. Python has library for conversion of files, but how to do it and can it be done? Thank you!! -
Nesting If statements to detect request value in Django views
I am trying to get third button to work on a simple app I am making. I set up if statements to detect the value of the request for two buttons, but I am getting stuck on how to configure the logic statement to get a third parameter through. My issue is that I need to have the form filled with any data before the subscriptions button will work properly. When the form is blank the app will indicate the form needs to be filled out. I am not familiar with javascript to have the buttons run from that. My hope is that I can learn how to configure the if statement to have the subscriptions call work without the form being filled out. Below is the UI as and the views.py def. The Amount and Delete functions work fine. It is just the subscription button that won't work until I put literally any data into the two text fields fields. def usage(request): if request.method == 'POST': form = UsageForm(request.POST) if form.is_valid(): if request.POST.get('subscription') == 'Subscription': dt = datetime.today() month = dt.month year = dt.year day = calendar.monthrange(year, month)[1] eom = str(month) + "/" + str(day) + "/" + str(year) …