Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Google Calendar API v3 error after allowing permission using oauth2.0
I followed the quickstart example to integrate my django app with google calendar. The difference from quickstart to my situation is that i just want to generate a URL and send it back to my user, through from google_auth_oauthlib.flow import InstalledAppFlow SCOPES = ['https://www.googleapis.com/auth/calendar'] flow = InstalledAppFlow.from_client_secrets_file(f"{PATH_TO_FILE}/{CLIENT_SECRET_FILE}", SCOPES) (auth_url, state) = flow.authorization_url() if is_dev(): auth_url += '&redirect_uri=http%3A%2F%2Flocalhost%3A43759%2F' print(auth_url) (OBS: I added this is_dev option, because no redirect_uri was not considered) I get this printed URL and get this steps: 1- The URL from auth_url printed when i ran the program 2- After choosing my user 3- and BAM, I cant proceed (i am redirected to localhost:47759 and cant access) What should I do? -
What is the best practice of handling buttons in Djnago?
I am not sure about the best practice on generating a high amount of buttons, that will connect with Django backend, after they are clicked. I am currently making sample online store in Django as my first project, so I can learn the framework. Each product on the page is going to have a button to add the product to the cart of a logged user. Should I make every button as a form, or handle the buttons with JS and fetch API. I did not fail to notice, Django heavily relies on forms as a default way to get user input, but making a so many generated forms on one page (the products are going to be a list) just doesn't feels right I was thinking of the solution like this: document.querySelectorAll('.add_product').forEach(e => { e.addEventListener('click', e => // POST request (with crsf cookie and all) // redirecting the user, depending on the output ) }) Just get all buttons, get data-pk from <button>, and send it with the JS Fetch API as POST request to Django endpoint The thing I don't like about it is, I see potential CORS Issues, and I do not know if this is the … -
How can i filtering tags with Alpine.js
I want to filter the tags based on user clicks. But the problem is when I use the HTML tag, everything becomes hidden as I cannot see any content on the page. Even when clicking on a specific tag, I do not see any results.The result after using The model.py : class Challenge_code(models.Model): #create a table auther = models.ForeignKey(User, on_delete = models.CASCADE) title = models.CharField(max_length = 200, null = False) body =RichTextUploadingField(blank=True, null=True) image = models.ImageField(null = True,blank=True ,upload_to='attach/') created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) tags = TaggableManager() def __str__(self): return self.title serializers.py from rest_framework import serializers from taggit.serializers import (TagListSerializerField, TaggitSerializer) from .models import Challenge_code class ChallengeSerializer(TaggitSerializer, serializers.ModelSerializer): tags = TagListSerializerField() class Meta: model = Challenge_code #fielsds = ('id','title','body','image','tags') fields = '__all__' the urls.py : urlpatterns =[ path('challengePage/', views.ChallengePage, name ='challengePage'), path('tag/<slug:tag_slug>', views.ChallengePage, name='tag'), path('challenge-list/', views.ChallengeListAPIView.as_view(), name='challenge-list'), ] the views.py : def ChallengePage(request): challenges = Challenge_code.objects.prefetch_related('tags').all().order_by('-created_at') tags = Tag.objects.all() context = { 'challenges' : challenges, 'tags':tags, } return render(request,'challengePage.html',context) class ChallengeListAPIView(ListAPIView): queryset = Challenge_code.objects.all() serializer_class = ChallengeSerializer The ChallengePage HTML page : <script defer src="https://unpkg.com/alpinejs@3.9.0/dist/cdn.min.js"></script> <div style="text-align: center;" x-data = "{tag: 'ALL', challenges: []}" x-init="challenges = await (await fetch('/challenge-list')).json()"> {% for tag in tags %} … -
The page of my website does not load on iPhones
I made my first website (https://pasta-la-vista.ck.ua/), but I ran into a problem. The site works on a computer and Android, but the menu page (https://pasta-la-vista.ck.ua/menu/) does not load on an iPhone. I couldn't find any information about what this is related to, so I hope to find help here. I fixed all the errors that appeared in the console but it didn't help me. I also looked for information on the Internet, but did not find anything Thank you all in advance for your help! -
I have a django app in a ubuntu virtual machine and can't remotely access the postgres database
I deployed an application in django on GCP in a VM (ubuntu 22.04 01 LTS) The app is working normally, database is postgresql. But I can't remotely access the database, I always get timeout error. My settings.py .... DATABASES = { 'default': { 'ENGINE': os.environ.get('DATABASE_ENGINE'), 'NAME': os.environ.get('DATABASE_NAME'), 'USER': os.environ.get('DATABASE_USER'), 'PASSWORD': os.environ.get('DATABASE_PASSWORD'), 'HOST': os.environ.get('DATABASE_HOST'), 'PORT': os.environ.get('DATABASE_PORT'), } } ... My .env file : # Postgres DATABASE_ENGINE = 'django.db.backends.postgresql' DATABASE_NAME = "basededados" DATABASE_USER = "user" DATABASE_PASSWORD = "senha" DATABASE_HOST = "127.0.0.1" DATABASE_PORT = "5432" I created the database like this: sudo -u postgres psql CREATE ROLE user WITH LOGIN SUPERUSER CREATEDB CREATEROLE PASSWORD 'senha'; CREATE DATABASE basededados WITH OWNER user; GRANT ALL PRIVILEGES ON DATABASE basededados TO user; I already set up the postgres.conf file: listen_addresses = '*' And the pg_hba.conf file**:** # IPv4 local connections: host all all 0.0.0.0/0 md5 I alredy allowed port 5432 through the firewall by executing: sudo ufw allow 5432/tcp I'm trying to access the DB like this: psql -h {Virtual machine IP} -d basededados -U user the error: psql: error: connection to server at {Virtual machine IP}, port 5432 failed: Connection timed out Is the server running on that host and accepting TCP/IP connections? Am I … -
admin is not able to approve post for the required like field django
In my django project, users can create posts. but the admin has to approve the post first. Then the users can see the posts created by them in their timeline. The users can like or unlike post from the post-detail page. However, when the admin logs in from the django admin panel to approve post and click the save button, it shows that the like field is required. How can I solve this problem so that the admin can approve the post? blog/models.py from django.db import models from django.utils import timezone from django.contrib.auth import get_user_model from django.urls import reverse from ckeditor.fields import RichTextField # first I installed ckeditor by this command: pip install django-ckeditor # Create your models here. class Category(models.Model): cid = models.AutoField(primary_key=True) category_name = models.CharField(max_length=100) def __str__(self): return self.category_name class Post(models.Model): aid = models.AutoField(primary_key=True) image = models.ImageField(default='blog-default.png', upload_to='images/') title = models.CharField(max_length=200) # content = models.TextField() content = RichTextField() created = models.DateTimeField(default=timezone.now) author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) cid = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='specialization') approved = models.BooleanField('Approved', default=False) like = models.ManyToManyField(get_user_model(), related_name='likes') def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk':self.pk}) @property def total_likes(self): return self.like.count() users/models.py from django.db import models from blog.models import Category from django.contrib.auth.models import AbstractUser # Create your … -
Failed to execute 'fetch' on 'WorkerGlobalScope'
I'm trying to pass variables from background.js file to views.py in Django. I tried many ways to do it and I write the following code, it seems to work but I stuck with this error. I searched a lot for a solution but I didn't found anything yet //background.js fetch("http://127.0.0.1:8000/my_app/views") .then(response => response.text()) .then(responseText => { // Extract the X-CSRF-TOKEN cookie from the response let csrfToken = getCookieValue(responseText, "csrftoken"); // Set up the data to send to the server let data = { variable1: "value1", variable2: "value2" }; // Make the request to the server with the X-CSRF-TOKEN header fetch("http://127.0.0.1:8000/my_app/views", { method: "POST", body: JSON.stringify(data), headers: { "Content-Type": "application/json", "X-CSRF-TOKEN": csrfToken } }) .then(response => response.json()) .then(responseData => { console.log(responseData); }); }); // Helper function to extract a cookie value from a string function getCookieValue(text, name) { let start = text.indexOf(name + "=") + name.length + 1; let end = text.indexOf(";", start); if (end === -1) { end = text.length; } return text.substring(start, end); } the error is the follwing: Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'WorkerGlobalScope': Invalid value please help me.. -
How do I adapt my import statements to my folder structure in Django?
I just set up a basic folder structure for a new project, however I am doing it a bit different than the standard file structure, since my front-end is in React and will be in a separate git repository. The problem is, my virtual environment is installed in the "backend-django" project and when I try to access my package imports (that I installed in my virtual env) in backend/settings.py it does not recognize them. As an example: I pip installed django-environ into my venv but when I go to settings.py (like I normally do) and import environ, I get a 'no module named environ' error. This is my first foray into Django (clearly). For reference, I have previously only used Flask for Python projects. Any help is appreciated! A mockup of my basic folder structure is here: folder structure I have already tried from backend-django import environ and from . import environ. I am still getting the same error. -
Django allauth render login fields manually user or email not displayed
I'm trying to display the login fields manually, instead of using: {{form.as_p}} I'm setting allauth as follows in order to login with email: ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = False ACCOUNT_SESSION_REMEMBER = True ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_UNIQUE_EMAIL = True In HTML I have the following: <form class="login" method="POST" action="{% url 'account_login' %}"> {% csrf_token %} <!-- Email input --> <div class="form-outline mb-4"> {{form.email}} <label class="form-label" for="form2Example1">Email address</label> </div> <!-- Password input --> <div class="form-outline mb-4"> {{form.password}} <label class="form-label" for="form2Example2">Password</label> </div> {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} <a class="button secondaryAction" href="{% url 'account_reset_password' %}">{% trans "Forgot Password?" %}</a> <button class="btn btn-lg btn-block btn-primary" type="submit">{% trans "Sign In" %}</button> </form> The email field is not being displayed, I have also tried with: {{form.user}} and the field is not displayed -
Nginx subdomain running the wrong web application
so I have a ubuntu server that run two different website with two different domain: www.firstwebsite.com www.secondwebsite.com But when I create an AAA record to create a subdomain with the first domain (like this) demo.firstwebsite.com If I go to this subdomain it automatically run the application website of my other domain (www.secondwebsite.com) I tried creating a specific socket&service file for the subdomain for it still run the web application of the second domain. Im not sure what is causing that and how to fix that? thank you -
create superuser in django custom User model with phone number as username
I have a django project which I want it to have phone number as its username field. I've created an app named accounts, and this is the models.py: class UserManager(BaseUserManager): use_in_migrations = True def create_user(self, phone_number, password, **extra_fields): user = self.model(phone_number=phone_number, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, phone_number, password, **extra_fields): extra_fields.setdefault("is_staff", True) extra_fields.setdefault("is_superuser", True) extra_fields.setdefault("is_active", True) if extra_fields.get("is_staff") is not True: raise ValueError("Superuser must have is_staff=True.") if extra_fields.get("is_superuser") is not True: raise ValueError("Superuser must have is_superuser=True.") return self.create_user(phone_number, password, **extra_fields) class User(AbstractUser): phone_number = models.CharField(max_length=20, null=False, blank=False, unique=True) USERNAME_FIELD = "phone_number" username = None first_name = None last_name = None objects = UserManager() REQUIRED_FIELDS = [phone_number] And I've declared it as my user model, in settings.py. AUTH_USER_MODEL = "accounts.User" ACCOUNT_USER_MODEL_USERNAME_FIELD = "phone_number" When I run python manage.py createsuperuser, I get this error: django.core.exceptions.FieldDoesNotExist: User has no field named 'accounts.User.phone_number' I can't figure out what is the problem. -
dockerized django application cannot connect to mysql server on localhost
I have a Dockerized django application I am running and I am trying to connect it to a mysql server I have that is port forwarded from another docker container. I have done a sanity test already and confirmed that I can connect to my mysql server using mysql workbench on my localhost. I have my dockerized django application running on network_mode: host so I thought I would be able to simply connect. Sadly I currently error out on docker-compose build with the error django.db.utils.OperationalError: (2002, "Can't connect to MySQL server on '127.0.0.1' (115)") An accepted resolution to this issue means that my dockerized django application would be able to connect successfully to my mysql server running localhost:29998 SETTINGS.PY (Django Application) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mytestdb', 'USER': 'userone', 'PASSWORD': 'password', 'HOST': '127.0.0.1', 'PORT': '29998', } } DJANGO App compose file version: '3.3' services: mydjangoapp: container_name: mydjangoapp restart: always env_file: .env build: . volumes: - ./apps:/apps - ./core:/core network_mode: host Django app dockerfile: FROM python:3.9 COPY . . # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 COPY requirements.txt . # install python dependencies RUN pip install --upgrade pip RUN pip install --no-cache-dir -r requirements.txt # … -
Receiving email content with in a template using Django contact form
I have set up a fully operational contact form and now I would like to render the users inputs into a html template, so when I receive the email it is easier to read. How do I do this? Do I link the template below some where, or link the form with in a template? Thank you in advance def contactPage(request): if request.method == 'POST': form = contactForm(request.POST) if form.is_valid(): subject = "INQUIRY" body = { 'full_name': form.cleaned_data['full_name'], 'email': form.cleaned_data['email_address'], 'message':form.cleaned_data['message'], } message = "\n".join(body.values()) try: send_mail(subject, message, '', ['email]) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect ('thankyou') form = contactForm() return render(request, "contact.html", {'form':form}) -
django: aggregation-of-aggregation with subquery: cannot-compute-avg-is-an-aggregate
I've been scouting & testing for quite some time now and I'm unable to get anything working with MariaDB. I have a subquery: rating_average_by_puzzle_from_completion_plays = Play.objects.filter(completion_id=OuterRef('id')).values('puzzle_id').order_by('puzzle_id').annotate(puzzle_rating_average=Avg('rating')).values('puzzle_rating_average') where the ratings of all plays corresponding to a given completion are averaged per puzzle_id Afterwards, I'm trying, for each completion, to average the puzzle_rating_average corresponding to each puzzle_id: if I do annotate, I end up with : SequenceCompletion.objects.annotate(rating_avg_from_completion_plays=Subquery(rating_average_by_puzzle_from_completion_plays.annotate(result=Avg('puzzle_rating_average')).order_by().values('result'))) django.core.exceptions.FieldError: Cannot compute Avg('puzzle_rating_average'): 'puzzle_rating_average' is an aggregate if I do aggregate, I end up with : SequenceCompletion.objects.annotate(rating_avg_from_completion_plays=Subquery(rating_average_by_puzzle_from_completion_plays.aggregate(result=Avg('puzzle_rating_average')).order_by().values('result'))) ValueError: This queryset contains a reference to an outer query and may only be used in a subquery. I tried as well: SequenceCompletion.objects.annotate(rating_avg_from_completion_plays=Avg(Subquery(rating_average_by_puzzle_from_completion_plays))) and I end up with: MySQLdb._exceptions.OperationalError: (1242, 'Subquery returns more than 1 row' Nothing I could find on the documentation or in any post would work, so I'll appreciate any help -
Page not found (404) Error in Django when creating a checkout session with Stripe
I am working on my first Stripe integration project to Django and I have landed into a problem that I have not managed to figure out a solution. I am trying to create a session whereby users can be redirected to the page where they can make a payment. Here is my views.py: class ProductLandingPageView(TemplateView): template_name = "landing.html" def get_context_data(self, **kwargs): product = Product.objects.get(name="Test Product") context = super(ProductLandingPageView, self).get_context_data(**kwargs) context.update({ "product": product, "STRIPE_PUBLIC_KEY": settings.STRIPE_PUBLISHABLE_KEY }) return context class CreateCheckoutSessionView(View): def post(self, request, *args, **kwargs): product_id = self.kwargs["pk"] product = Product.objects.get(id=product_id) YOUR_DOMAIN = "http://127.0.0.1:8000" checkout_session = stripe.checkout.Session.create( line_items=[ { # Provide the exact Price ID (for example, pr_1234) of the product you want to sell 'price': '{{product.price}}', 'quantity': 1, }, ], metadata={ "product_id": product.id }, mode='payment', success_url=YOUR_DOMAIN + '/success/', cancel_url=YOUR_DOMAIN + '/cancel/', ) return redirect(checkout_session.url, code=303) Here is my urls.py; urlpatterns = [ path('', ProductLandingPageView.as_view(), name='landing'), path('success/', SuccessView.as_view(), name='success'), path('cancel/', CancelView.as_view(), name='cancel'), path('create-checkout-session/<pk>', CreateCheckoutSessionView.as_view(), name='create-checkout-session'), ] Also here is the templatate where the checkout button is located: <body> <section> <div class="product"> <!-- <img src="https://i.imgur.com/EHyR2nP.png" alt="The cover of Stubborn Attachments" /> --> <div class="description"> <h3>{{product.name}}</h3> <h5>${{product.price}}</h5> </div> </div> <form action="/create-checkout-session" method="POST"> <button type="submit" id="checkout-button">Checkout</button> </form> </section> {% csrf_token %} </body> <script type="text/javascript"> … -
i have defined block content in base.html and extents in index.html , block content is not working
in template/app/index.html {% extends 'base.html' %} {% block content %} replace me {% endblock %} in template/app/base.html <!doctype html> <html> <head> <title>Base title</title> </head> <body> {% block content %} {% endblock %} </body> </html> in app/urls.py from django.urls import path from app import views urlpatterns = [ path('',views.index) ] in app/views.py from django.shortcuts import render # Create your views here. def index(request): return render(request,'app/base.html',{}) this is the code...! i have tried changing the folder location and saw level of the folder -
Can't import anything from django
I'm having problems with importing stuff from django. I'm completely new to python and I'm following a tutorial where I'm taught how to make my first django project (I'm using pycharm btw). The problem I'm encountering is when I try to import something from django it says Unresolved reference 'django'. from django.http import HttpResponse from django.shortcuts import render In this case it only shows the red squiggly line under the two django, HttpResponse and render. Any help would be appreciated I have tried searching on google, but i couldn't find what I'm looking for. -
Django token authentication error: cURL request without header shows 401 unauthorized, but adding header token auth changes to 404 not found error
Titles lays out the issue I am facing. Working on a boiler plate Django app with an API endpoint. I am able to (semi-successfully) access the endpoint via a simple cURL without header which returns a 401, but when I add the header token, I now get a 404 not found error. What could be going wrong? I've tried multiple different combinations of django settings changes across these forums and cannot get it to change. Examples of some things I have tried: Changing order of MIDDLEWARE CORS_ORIGIN_WHITELIST CORS_ALLOWED_ORIGINS CORS_ALLOW_CREDENTIALS CORS_ORIGIN_ALLOW_ALL Playing with REST_FRAMEWORK settings -- both DEFAULT_AUTHENTICATION_CLASSES & DEFAULT_PERMISSION_CLASSES Changing ALLOWED_HOSTS from [] to current value below CORS_ALLOWED_ORIGINS Attaching snippets of relevant code: 401 cURL: curl -X GET http://127.0.0.1:8000/bettor/create/ 404 cURL: curl -X GET http://127.0.0.1:8000/bettor/create/ -H "Authorization: Token <super secret but valid token>" settings.py: from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '<secret hidden key>' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['localhost', '127.0.0.1'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # helpers 'rest_framework', 'rest_framework.authtoken', 'corsheaders', # my apps 'Bets', 'Users', ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", … -
Signals django not working on ubuntu server
I have a site on the server where I work with signals.py The problem is that when I add a db file through the admin panel signals.py does not work EXACTLY ON THE SERVER on my computer everything works fine But there is another model involving signals.py and it works great models.py The model that works class History(models.Model): tg_id = models.BigIntegerField(verbose_name='Telegram ID') amount = models.FloatField(verbose_name='Кол-во') date = models.DateTimeField(verbose_name='Дата транзакции') Problem model class database_sqlite3(models.Model): file = models.FileField(verbose_name='Файл', upload_to='db_file/', help_text='Вы можете добавить сюда базу пользователей') app.py from django.apps import AppConfig class MainConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'main' verbose_name = "Бот" def ready(self): import main.signals signals.py The model that works @receiver(post_save, sender=History) def create_profile(sender, instance, created, **kwargs): if created: obj = User.objects.get(tg_id=int(instance.tg_id)) wallet = obj.wallet if wallet == None: wallet = 0 else: pass User.objects.filter(tg_id=instance.tg_id).update(wallet=wallet + instance.amount)0 Problem model @receiver(post_save, sender=database_sqlite3) def create_profile(sender, instance, created, **kwargs): if created: env = Env() env.read_env() gre = psycopg2.connect( database=env.str('POSTGRES_DB'), user=env.str('POSTGRES_USER'), password=env.str('POSTGRES_PASSWORD'), host=env.str('POSTGRES_HOST'), port=env.str('POSTGRES_PORT') ) cur_gre = gre.cursor() conn = sqlite3.connect(str(instance.file)) cursor = conn.cursor() table_names = cursor.execute("SELECT name FROM sqlite_master WHERE type='table';").fetchall() table_name = [] for i in table_names: table_name.append(i[0]) if 'main_admin_bot' in table_name: cursore = conn.execute(f"SELECT * FROM main_admin_bot").fetchall() for i in cursore: try: sql … -
Make longer access tokens with django_oauth_toolkit
I have setup the OAuth 2.0 authentication in a Django Rest Framework project with the django_oauth_toolkit library. But I have noticed access_token length is quite short. How can I make these tokens larger? I mean, increase the number of characters each token has. I have been searching for a setting to do this, but I haven't found anything. I have read all the avaiable settings in the OAUTH2_PROVIDER setting, but I have found nothing. -
heroku H10 issue
I get the Error: at=error code=H10 desc="App crashed" method=GET path="/" host=quiz-iu.herokuapp.com request_id=9ee6412c-b248-4eeb-8eba-066f07b38a4f fwd="93.201.118.59" dyno= connect= service= status=503 bytes= protocol=https 2022-12-19T17:47:36.743985+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=quiz-iu.herokuapp.com request_id=071363bb-8ce2-4eed-bdc5-93cd3b39581f fwd="93.201.118.59" dyno= connect= service= status=503 bytes= protocol=https And if i set into the consul : heroku run rails console I get: bash: line 1: rails: command not found Can please someone help to fix this issue I try to devolope a app but get the a error -
Restrict access of static files to permission groups
i am fairly new to web-development and i can't really find the best way to handle serving files with django. My situation is: I have users from different departments that can upload, edit and download files. Users should have access to files from other users of the same department, but not of the others. The way it works until now is: each filepath is written in a database, with a reference to which department it belongs. If requesting a file django checks if the department of the user is the same as the file, and denies the access if that not the case. After researching a bit it seemed that serving files that way isnt the standard way, and i should serve them as static files (from the webserver, not directly by django). My question is: can i still restrict the access of static files, or can anyone read them? -
Django: save() prohibited to prevent data loss due to unsaved related object 'predictions'
I am a creating a Django project, where i am using inline_formset to add multiple forms from the frontend (Just like the backend). I am trying create a new object now from the frontend, the main models get saved but the the model that is a foreignKey to the main model is not saving (Inline Model). I am getting the error message: save() prohibited to prevent data loss due to unsaved related object 'predictions'. Here is my CreateView Code. views.py class ProductInline(): form_class = PredictionForm model = Predictions template_name = "core/create/create_bet.html" def form_valid(self, form): named_formsets = self.get_named_formsets() if not all((x.is_valid() for x in named_formsets.values())): return self.render_to_response(self.get_context_data(form=form)) # self.object = form.save() new_form = form.save(commit=False) new_form.user = self.request.user new_form.save() # for every formset, attempt to find a specific formset save function # otherwise, just save. for name, formset in named_formsets.items(): formset_save_func = getattr(self, 'formset_{0}_valid'.format(name), None) if formset_save_func is not None: formset_save_func(formset) else: formset.save() return redirect('core:dashboard') def formset_variants_valid(self, formset): """ Hook for custom formset saving.. useful if you have multiple formsets """ variants = formset.save(commit=False) # self.save_formset(formset, contact) # add this, if you have can_delete=True parameter set in inlineformset_factory func for obj in formset.deleted_objects: obj.delete() for variant in variants: variant.product = self.object variant.save() … -
How can I determine the order of files/sub-folders within user-generated folders in Django?
I am building a Django web app where users can upload files into a folder structure that they also create/control. I know how to facilitate uploading of files and understand the solution proposed in this question about how to "assign" files (or sub-folders) to their parent folders, without having to create actual folders in the underlying file storage. However, in my web-app I would also like to allow users to determine the order of files and sub-folders within each folder without relying on the actual filenames. I know I can set the order of the returned one-to-many model instances by setting the index variable in a meta class (see this question). In my case I could thus insert an "order" field into the file/folder models and then set this value appropriately for each file/sub-folder in a given parent folder. However, this would mean that when a user moves a file from the bottom to the top of the parent folder, for example, every single one of the parent folder's file/sub-folder model instances would need to be edited to reflect their new position in the folder. Maybe my lack of coding experience is misleading me, but this setup looks to me … -
Why do people code flutter apps with dart instead of flet for mobile applications?
Multiple sources encouraged developers to learn dart language so that users can develop flutter apps for both iOS and android platforms. However, I can hardly find sources that say flet language can achieve the same results. For one thing, I think I am somehow fluent in python. If I code in flet language on flutter, I would've skipped few weeks to learn dart just so I can code a mobile app. Coding the app in python would make the code language consistent across both front-end and back-end (django) but I am afraid that would I be missing out on something by not learning to code in dart. What are the implications for me to develop a mobile app for both iOS and android platforms if I coded my app in flet instead of dart with flutter?