Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Issues deploying Django app to AWS web server
I would like to complete the Django first app but instead of accessing it via the local host on my machine. Id like to access it through a free tier on AWS. This is for an Education tool I am presenting to a class. Im wondering if anyone has done this, or if there is any videos/guides for this? I would also like to have a number of students working on this as well so it would be great if there was also a guide for explaining to the students how to use Docker, pull the container to their local machines (all students will be using VSC as their IDE). The end goal is for the base app to be developed on their local machines (macOS/Windows/Linux etc). When they commit their code to the repo, for it to deploy to an AWS web sever (free educational tier account) for them to see their changes. Then if the changes are good, they can deploy to the "production" server. If these are not the normal steps of the deployment pipeline, might someone clarify for me? Thanks for any assistance! -
Where to define custom data handling for a m2m field in django
Let's say for example I want the many to many 'tags' modelfield to be inputted as a space-separated list, were an unrecognized name be submitted it should also be created in the 'Tag' model. I'm aware this could be written either at: View level Form level FormField level ModelField level I want to adhere to the DRY principle as tightly as possible. For the time being I have defined it at ModelForm level but my setup is not very flexible. I would have to write new forms for every variation in each part of the website I place this formfield in. -
Update table every time my database is changed [HTMX][Dajngo-tables2]
I want to Update table every time my database is changed, without refreshing. Also, I want to keep my quarry parameters from a search when the update happens What I done so far is use hx-get to retrieve my table from another template and view to get me the updated table. However, I don't know where to start to trigger a update when the database is changed Views.py def display_view(request): myFilter = ParticipantFilter(request.GET, queryset=Participant.objects.all()) table = ParticipantTable(myFilter.qs) table.paginate(page=request.GET.get("page", 1), per_page=10) return render(request, 'display.html', {'table': table,'myFilter': myFilter}) def data_only_view(request): myFilter = ParticipantFilter(request.GET, queryset=Participant.objects.all()) table = ParticipantTable(myFilter.qs) table.paginate(page=request.GET.get("page", 1), per_page=10) return render(request, 'updatedDisplay.html', {'table': table}) display.html {% extends "base.html" %} {% block content %} <form method="get"> {{ myFilter.form }} <button type="submit">Search</button> </form> <div id="table-results" hx-get="/updatedDisplay" hx-include = "[name='first_name']"> {% load render_table from django_tables2 %} <table class="table"> {% render_table table %} </table> {% endblock %} </div> updateDisplay.html {% load render_table from django_tables2 %} <table class="table"> {% render_table table %} </table> -
How to capture all the options user selected in a webpage and pass it to the backend using JavaScript?
I have a requirement to capture all the options which the user has selected and pass them to the backend(view in Django. There are text boxes and Radio buttons on the web page user has to select the options, and on click of a save button based on user selections, I have to initiate the process in the backend. -
Django REST: make request.session['key'] available on all views
I'm trying to check if a user logged in saving a token in request.session["token"]. On login, the request.session["token"] is set and the print() works. How do I make that key available on all views? @api_view(['POST']) def login(request): if request.data["usuario"] and request.data["pwd"]: try: user_item = User.objects.get(usuario=request.data["usuario"]) except User.DoesNotExist: return Response({'errors': 'Usuario no existe'}, status=402) usr_pwd = request.data["pwd"] bd_pwd = user_item.pwd if bcrypt.checkpw(usr_pwd.encode('utf-8'),bd_pwd.encode('utf-8')): token = jwt.encode({'user': request.data["usuario"]}, 'palacin', algorithm='HS256') request.session["token"] = token print(request.session["token"]) # <-- THIS PRINT WORKS return Response(200) else: return Response({'errors': 'Usuario y/o contraseña incorrectos.'}, status=401) else: return Response({'errors': 'Usuario y/o contraseña no especificados'}, status=400) @api_view(['POST']) def getUser(request): print(request.session["token"]) # <-- THIS PRINT DOESN'T WORK '''if "token" in request.session: return Response(jwt.decode(request.session["token"], 'palacin', algorithms=['HS256'])) else: return Response({'errors': 'Sesión no iniciada'}, status=403)''' -
Django restframework can't get post data with a multipart parser
i am trying to save an object with an image using django restframework but when i use the FormParser and MultiPartParser classes the request.data object get seemingly encoded msgs and when i try to decode using utf-8 it outputs an error saying this data is not utf-8 i want to have access to the request.data data and be able to save the image for future requests here is my view function: @parser_classes([FormParser, MultiPartParser]) @api_view(['GET', 'POST']) @permission_classes([IsAuthenticated]) def products(request): if request.method == 'POST': print(request.data) serializer = ProductSerializer(data=request.data) serializer.initial_data['user'] = request.user.pk serializer.initial_data['price'] = float( request.data['price']) serializer.initial_data['quantity'] = int( request.data['quantity']) if serializer.is_valid(): serializer.save() return Response({'message': "product added"}, status=status.HTTP_201_CREATED) else: print(serializer.errors) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) my front end code: export const addProduct = async (product) => { const fd = new FormData(); fd.append("name", product.name); fd.append("price", product.price); fd.append("quantity", product.quantity); fd.append("image_url", product.image_url); console.log(product.image_url) //this prints a file object const response = await fetch(`${URL}/products`, { method: "POST", headers: { "Content-Type": `multipart/form-data; boundary=${fd._boundary}`, }, body: fd, }) return response } -
How do I refresh the Google access token with Django allauth?
The access token for google typically lasts 1 hour. How do I refresh the token without having the user login again? github code for project: https://github.com/theptrk/learn_gcal django-allauth Google login is set up the normal way with an added scope THIRD_PARTY_APPS = [ # ... "allauth.socialaccount", "allauth.socialaccount.providers.google", # This allows you to assign a site to a "social application" SITE_ID = 1 SOCIALACCOUNT_PROVIDERS = { "google": { "SCOPE": [ # minimum scopes "profile", "email", # additional scopes "https://www.googleapis.com/auth/calendar.readonly", ], "AUTH_PARAMS": { "access_type": "offline", }, } } # https://django-allauth.readthedocs.io/en/latest/configuration.html # Use this for additional scopes: This defaults to false SOCIALACCOUNT_STORE_TOKENS = True Creating the credentials is different than the docs since the docs use a "secrets file" instead of getting tokens from the db # get user and client credentials token = SocialToken.objects.get( account__user=request.user, account__provider="google" ) client_id = env("GOOGLE_CLIENT_ID", default="") client_secret = env("GOOGLE_CLIENT_SECRET", default="") # create Credentials object from google.oauth2.credentials import Credentials creds=Credentials( token=token.token, refresh_token=token.token_secret, token_uri="https://oauth2.googleapis.com/token", client_id=client_id, client_secret=client_secret, ) Trying to retrieve events is totally fine if the access token is not expired # retrieve google calendar events from googleapiclient.discovery import build from datetime import datetime service = build("calendar", "v3", credentials=creds) try: events_result = ( service.events() .list( calendarId="primary", timeMin=datetime.now().date().isoformat() + "Z", maxResults=30, … -
CSRF verification failed. Request aborted in http URL
In my login showing error when submit the form in http url but https url working fine. my login form is ` {% csrf_token %} Please log in Or click here to register {% if msg %} Error Invalid credentials or inactive account. If you have registered please make sure to activate your account by clicking on the link sent to your email address. Please check your spam folder if you are unable to find the email. {% endif %} <input type="text" class="form-control" name="email" placeholder="Email Address" required="" autofocus="" ng-model="loginEmail"></input> <input type="password" class="form-control" name="password" placeholder="Password" required="" ng-model="loginPwd"></input> <button class="btn btn-lg btn-primary btn-block" type="submit" ng-click="login(loginForm.username.$viewValue, loginForm.password.$viewValue)">Log in</button> </form>` localhost working proper this code but live site not working in http. Also i add {% csrf_token %} in login form please someone help me! -
Django: how to take input as range and store it in the database?
I am beginner in django and thinking to create a website that asks the user for input (the input here is an hour range) and store it in the data base e.g. A slider that ranges from 5am till 9pm the user can set the start and end for example 7am-9am and submit it and then it will be stored in the database I am not sure how to appriach it also how will it be stored in the database as a single entry or multiple entries your help is much appreciated I have been trying continuously to search for tutorials, vidoes, articles, even any piece of information here and there that could give me the kickstart but I failed -
Pass data from the pipeline to views in Django Python Social Auth
I was reading the documentation of Python Social Auth and got curious about the section of Interrupting the Pipeline (and communicating with views). In there, we see the following pipeline code In our pipeline code, we would have: from django.shortcuts import redirect from django.contrib.auth.models import User from social_core.pipeline.partial import partial # partial says "we may interrupt, but we will come back here again" @partial def collect_password(strategy, backend, request, details, *args, **kwargs): # session 'local_password' is set by the pipeline infrastructure # because it exists in FIELDS_STORED_IN_SESSION local_password = strategy.session_get('local_password', None) if not local_password: # if we return something besides a dict or None, then that is # returned to the user -- in this case we will redirect to a # view that can be used to get a password return redirect("myapp.views.collect_password") # grab the user object from the database (remember that they may # not be logged in yet) and set their password. (Assumes that the # email address was captured in an earlier step.) user = User.objects.get(email=kwargs['email']) user.set_password(local_password) user.save() # continue the pipeline return and the following view def get_user_password(request): if request.method == 'POST': form = PasswordForm(request.POST) if form.is_valid(): # because of FIELDS_STORED_IN_SESSION, this will get copied # … -
How to fix 'qr_code' is not a registered tag library. in Django and HTML
How to fix 'qr_code' is not a registered tag library. I use Django version 4.1.4. setting.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', 'qrcode', ] In setting.py, if I use qr_code instead of qrcode, this error will occur ModuleNotFoundError: No module named 'qr_code'. It will display the error 'qr_code' is not a registered tag library. {% load qr_code %} {% qr_from_text request.build_absolute_uri size="T" image_format="png" error_correction="T" %} In HTML, how should I edit? Command I used to install django-qr-code 3.1.1 pip install django-qr-code And I tried installing it with conda after trying it in pip and it didn't work. conda install -c auto django-qrcode -
Django order model by date and move models without date to the end
I have a model tickets, with a sum in it. I'm trying to make spending tickets by nearest expire date. But if I'm ordering by date_expire, it move date_expire=None models to the top. But date_expire=None means that ticket has no limit by time, and should be used after all tickets, that has time limit. My code: ticket = Tickets.objects.filter( sum__gte=0, date_expire__gte=timezone.now(), user_id=user.id, burned=False ).order_by( 'date_expire' ).first() I can try to sort by sorted func with lambda key, but I think there's a better way to do this in orm -
How do I start/stop Hypercorn/Uvicorn server as a background task for an async application (like a discord bot) Python
I am currently creating a django application w/ asgi and I am currently having problems of setting up hypercorn and uvicorn to run in background with graceful shutdown. When I set up my application from asgi to run on hypercorn only using asyncio.create_task and starting it only, the website doesn't run. Hypercorn code snippet: from scripts import funcs import nextcord from nextcord.ext import commands from nextcord import Interaction import asyncio # from uvicorn import Config, Server # import uvicorn import subprocess from subprocess import CREATE_NEW_CONSOLE import signal # import multiprocessing import nest_asyncio import os import sys sys.path.insert(1, 'C:\\Users\\Sub01\\Project\\PaulWebsite\\app') from hypercorn.config import Config from hypercorn.asyncio import serve from hypercorn.run import run import hypercorn import asyncio from paul_site.asgi import application import signal nest_asyncio.apply() createEmbed = funcs.embedCreator() shutdown_event = asyncio.Event() def _signal_handler(*_) -> None: shutdown_event.set() class HYPERCORN: config = Config() coro = None def __init__(self) -> None: self.config.from_object("paul_site.asgi") self.evtLoop = asyncio.new_event_loop() async def start(self): self.coro = self.evtLoop.create_task(await serve(application, self.config)) def stop(self): self.evtLoop.add_signal_handler(signal.SIGINT, _signal_handler) self.evtLoop.run_until_complete( asyncio.to_thread(serve(application, self.config, shutdown_trigger=shutdown_event.wait)) ) class baseCommand(commands.Cog): proc = None def __init__(self, client): self.client = client self.website = HYPERCORN() @nextcord.slash_command() async def bot(self, interaction: Interaction): pass @bot.subcommand(description="Stops the bot") async def shutdown(self, interaction: Interaction): await interaction.response.send_message(embed=createEmbed.createEmbed(title="Exit", description="Bot's down", footer=f"Requested by … -
Resetting a form in Django using HTMX
I am working on a simple form in Django and I would like to achieve reset functionality using HTMX.. In instances where Django gives validation errors, they would go away when user clicks on "reset" button.. I dont know if there are any easier ways to do this (which i would love to listen to), but I prefer the HTMX solution as it would be of use to me later on as well.. In the below, index.html contains the form (portfolio form).. please note, index carries a base.html which contains htmx unpkg.. portfolio-reset.html is the partials/ code that I would like HTMX to do AJAX on.. portfolio_reset is the view to fetch the PortfolioForm.. The problem I'm facing is when I run the code, the HTMX is doing a full page reload of index.html and I am not able to fetch just the portfolio-reset code to just reset the form.. Not sure where I'm going wrong.. Appreciate your help.. index.html {% csrf_token %} {{ portfolio_form|crispy }} <div id="portfolio-reset" ></div>` ` portfolio-reset.html {% load crispy_forms_filters %} {% load crispy_forms_tags %} <div hx-target="this" hx-swap="outerHTML"> <form> {% csrf_token %} {{ portfolio_form|crispy }} </form> </div>` ` portfolio_reset view def portfolio_reset(request): portfolio_form = PortfolioForm() context … -
Django, many to many relationship, how to insert value for all keys in table?
I have 3 models Company, Discount and CompanyDiscountRelation as below: class Company(models.Model): name = models.CharField(max_length=150) def __str__(self): return self.name class Discount(models.Model): name = models.CharField(max_length=150) discount_value = models.IntegerField() def __str__(self): return self.name class DiscountCompanyRelation(models.Model): company= models.ForeignKey(Company, on_delete=models.CASCADE) discount = models.ForeignKey(Discount, on_delete=models.CASCADE) is_active = models.BooleanField(default=True) I know how to assign a previously created discount to one company. I do it by DiscountCompanyRelationForm and choose company from form list. But i want to assign discount to all companies by one-click. How to do this? I tried get all ID's by: Company.objects.values_list('pk', flat=True) and iterate through them but i don't think that's how it should be done and i have problem to save form by: form.save() I tried all day but now I gave up. Sorry if this is basic knowledge. I've been working with django for a few days. -
Django tests freeze when running async Celery tasks
I'm trying to create unit tests in Django, that tests the Celery tasks and whether or not the task creates the objects from the CSV data i give it. For some weird reason my tests freeze when calling .get() on the AsyncResult -objects. However, when i monitor the Celery logs and the database, it looks like they work normally and return success-messages indicating the tasks are completed. Outside the testing environment everything works fine, its just when im running Celery in my tests. I have no idea what is going on. Here's the relevant code: stations/test.py class StationsTests(TestCase): @classmethod def setUpTestData(cls): super(StationsTests, cls).setUpTestData() dirname = os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', 'csvimport')) cls.csv_data_type_station = 'station' cls.upload_type = 'safe_create' cls.file_station = os.path.join(dirname, 'CSVFiles/Station_test_csv.csv') @override_settings(CELERY_EAGER_PROPAGATES_EXCEPTIONS=True, CELERY_ALWAYS_EAGER=True) def test_station_geoJSON_data(self): self.result_upload_csv = upload_csv.delay( self.file_station, self.csv_data_type_station, self.upload_type).get(timeout=10) self.assertEqual(self.result_upload_csv, '10 stations uploaded successfully') self.assertEqual(len(Station.objects.all()), 10) settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'db_hcbapp', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'localhost', 'PORT': '5432' }, } ..... CELERY_BROKER_URL = 'redis://127.0.0.1:6379' CELERY_IMPORTS = ('csvimport.tasks') CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_BACKEND = 'django-db' CELERY_RESULT_EXTENDED = True celery.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings') app = Celery('myapp') … -
Ajax call works for the first cloning row only, how to make it works for every row
I've the next code snippet for append <option> to the "Unit" drop-down list when I select an item from product drop-down list. $(document).ready(function() { var purchase = $('.purchase-row').last().clone(); let purchaseCount = 0; $(document).on('click', '.add_item', function() { var clone = purchase.clone().prop('id', 'product_' + purchaseCount); // var clone = purchase.clone().prop('class', 'product_' + purchaseCount); console.log('clone: ', clone); $(this).prevAll('.purchase-row').first().after(clone.hide()); clone.slideDown('fast'); $('#product_'+ purchaseCount).find('#id_pro-product').removeClass('product').addClass('newProduct'); $('#product_'+ purchaseCount).find('#id_pro-unit').removeClass('unit').addClass('newUnit'); purchaseCount++; console.log('PURCHASE-COUNT: ', purchaseCount);// $(this).parent().slideUp('fast'); // The next code for reinitialize select2 var $example = $(".js-programmatic-init").select2(); $example.select2(); }); $(document).on('click', '.purchase-minus', function() { if (purchaseCount == 0) { // Do nothing. alert('You can not delete this row' ); } else { $(this).closest('.purchase-row').remove(); purchaseCount--; console.log('PURCHASE-COUNT2: ', purchaseCount); } }); $(document).on('click', '.purchase-broom', function() { $(this).closest('.purchase-row').find('input').val(''); }); $(document).on('change', '.product', function(e){ var id = $(this).val(); console.log('CHANGED-PRODUCT: ', id); $.ajax({ type: 'POST', url: '{% url "purchases:get_product_unit" %}', // dataType: 'json', // async: true, // cache: false, data: { 'pro-product': $('.purchase-row select').closest('.product').val(), // this is right // find('#id_pro-product') }, success: function (data) { console.log( 'FROM SUCCESS: ', data['unit'], ); var values_3 = data['unit']; // $('#id_pro-unit').text(''); // $('select').closest('.unit').find('select').text(''); $('select').closest('.unit').text(''); if (values_3.length > 0) { for (var i = 0; i < values_3.length; i++) { // $('#id_pro-unit').append('<option>' + values_3[i] + '</option>'); $('select').closest('.unit').append('<option>' + values_3[i] + '</option>'); } } }, … -
Object of type subscription is not JSON serializable
I use to dumps data into json in django views function. def payment(request, slug): package=subscription.objects.get(slug=slug) print(slug) data={ 'slug':slug, 'jsonPackage':json.dumps(package), } return render(request, 'firmApp/subscription/payment.html',data) But getting an error: Object of type subscription is not JSON serializable!! -
Is there any shortcut to display all the fields of a model without explicitly specifying in Django?
We can create a model form very easily in Django just by passing a model form from views to the templates and displaying it as: {{ form.as_table }} Do we have similar way so that we do not have to type all the model's fields name in templates to display them? -
DateField as a search field. How to make if look like a calendar
class OveroptimisationIdentifiers(models.Model): date = models.DateField(blank=True, null=True) region = models.ForeignKey(SiteRegions, models.CASCADE) site = models.ForeignKey(SiteSites, models.CASCADE) def __str__(self): return "{}: {}: {}".format(self.date, self.region, self.site) class Meta: managed = False db_table = 'overoptimisation_identifiers' unique_together = (('date', 'site', 'region'),) @admin.register(OveroptimisationIdentifiers) class OveroptimisationIdentifiersAdmin(admin.ModelAdmin): exclude = [] actions = [scrape_arsenkin, ] list_filter = ["date", ] search_fields = ["date", ] It is strange to me but this code produces just an input field rather than a calendar picker. Could you help me convert it into a calendar picker? -
raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet
this is django rest_framework api I created this api for restourant. This is menu api . I want to save menu.json's data to my database, but I could not. Can you give any advice to save json data to my models. I got this error: File "C:\Users\OSMAN MERT\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\functional.py", line 49, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\OSMAN MERT\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\fields\related.py", line 113, in related_model apps.check_models_ready() File "C:\Users\OSMAN MERT\AppData\Local\Programs\Python\Python310\lib\site-packages\django\apps\registry.py", line 143, in check_models_ready raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. models.py class Meal(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) is_vegetarian = models.BooleanField(default=False) is_vegan = models.BooleanField(default=False) def __str__(self): return self.name class Ingredient(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) #groups = models.CharField(max_length=100) #meal = models.ForeignKey(Meal, on_delete=models.CASCADE, related_name='ingredients') def __str__(self): return self.name class Option(models.Model): id = models.AutoField(primary_key=True) ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) name = models.CharField(max_length=100) quality = models.CharField(max_length=100) price = models.FloatField() per_amount = models.CharField(max_length=100) def __str__(self): return self.name class MealIngredient(models.Model): id = models.AutoField(primary_key=True) meal = models.ForeignKey(Meal, on_delete=models.CASCADE) ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) path = r"C:\Users\OSMAN MERT\Desktop\menu\menu_core\menu.json" with open(path) as f: data = json.loads(f.read()) for meal in data["meals"]: id = meal["id"] name = meal["name"] meal_obj, created = Meal.objects.get_or_create(name=name) for ingredient in meal["ingredients"]: name_in = ingredient["name"] ingredient_obj, created = Ingredient.objects.get_or_create(name=name_in) MealIngredient.objects.get_or_create(meal=meal_obj, ingredient=ingredient_obj) for ingre in … -
cannot import name 'save_virtual_workbook' from 'openpyxl.writer.excel'
Is there an update to the library? Before it worked perfectly, and today I updated and it no longer loads I searched but I can't find any other option -
How to stream data chunk by chunk in Django using StreamingHttpResponse and receive it in the front end using axios?
I am trying to stream data from my Django backend to my front-end using the StreamingHttpResponse and axios. However, I am encountering an issue where the data is being buffered and only received in the front-end once all the data is ready or when I stop the server. I am using the code provided above for the backend and front-end. I would like to know how I can prevent this buffering and receive the data chunk by chunk in the onDownloadProgress event of axios. Backend: def iterator(): for i in range(1000): yield f'chunk: {i}' sleep(0.2) def generate_post_text(request): stream = iterator() response = StreamingHttpResponse(stream, status=200, content_type='text/event-stream'') response['Cache-Control'] = 'no-cache' response['X-Accel-Buffering'] = 'no' response.streaming = True return response And here is the front end code: axios({ url: '/api/gpt3/generate-post-text', method: 'GET', onDownloadProgress: progressEvent => { const dataChunk = progressEvent.currentTarget.response console.log(dataChunk) }, }).then(({data}) => Promise.resolve(data)) Backend middlewares: MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware',] I run the server locally on a Mac -
Creating object branched from object and setting the root object id to the parent_object field
With this function def post(request, note_id, comment_id=None): """Create a comment under a post/idea.""" request.data["owner"] = request.user["id"] request.data["note_id"] = note_id if comment_id: try: parent_comment = Comment.objects.get(id=comment_id) request.data["parent_comment"] = parent_comment except Comment.DoesNotExist: request.data["parent_comment"] = None else: request.data["parent_comment"] = None serializer = CommentSerializer(data=request.data) if serializer.is_valid(raise_exception=True): serializer.save() return Response(serializer.data) serializer for the comment model class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = "__all__" and my url path path("<uuid:note_id>/comments/<uuid:comment_id>/replies/", views.CommentsGetOrCreateView.as_view(), name="CommentRepliesGetOrCreateView") I'm trying to create Comment off of a Comment that is created off of a Note. Currently i can create a Note and create a Comment off of it and can retrieve comments under a comment but cant POST with the given url below as i need to. I currently get error on postman as ["parent_comment" : "Must be a valid UUID"] I have tried reorganizing my post method and tried changing the serializer so the parent_comment can be null. Ive also tried adding .id at the end of "request.data["parent_comment"] = parent_comment.id" -
Django Website on Godaddy Domain wont load without https://www
My django site cannot be loaded by just typing in example.com or https://example.com I have to fully type https://www.example.com Does anyone know why this may be? I thought it might have to be related to the SSL certicate but that all seemed fine. The domain is hosted with Godaddy and I am using Pythonanywhere.com to deploy my django site.