Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django MoneyField: Invalid value for MoneyField
I'm having slight of a problem while using MoneyField in Django. I have 2 models: Work and Price. And Price gets Work id as a Foreign Key. In Postman I'm trying to post a Work with a Price, but I keep getting an error. Here is my work_model: from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class Work(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) name = models.CharField(max_length=200) length = models.IntegerField(null=True) width = models.IntegerField(null=True) def __str__(self): return "{}".format(self.name) And here my price_model from django.db import models from .model_work import * from djmoney.models.fields import MoneyField class Price(models.Model): work = models.OneToOneField(Work, on_delete=models.CASCADE, related_name='price') price = MoneyField(max_digits=19, decimal_places=4, default_currency='USD', null=True) shipping = models.IntegerField(null=True) total = models.IntegerField(null=True) def __str__(self): return "{}".format(self.price) When I'm posting a Work in Postman: { "user":"2", "name":"work 20", "price": [ { "price":20, "price_currency":"USD", "shipping":12, "total":32 } ], "length":"50", "width":"60" } I keep getting this error: ValidationError at /works/ ["Invalid value for MoneyField: [OrderedDict([('price', <Money: 20.0000 USD>), ('shipping', 12), ('total', 32)])]."] I've looked everywhere but can't manage to understand my error, does anyone have a clue? Thanks for your responses! -
form for formset object has no attribute 'cleaned deta'
i have genericview which handle 3 difference form(2 formsets), when i try check cleaned_data, i have error, but when i try make the same by debugger i didnt see anything problem, who may know why i can`t make it? My View : class CompanyCreateView(LoginRequiredMixin, CreateView): model = Company template_name = 'main/company/create_page.html' form_class = CompanyCreateForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['page'] = Page.objects.active().filter(slug='add_company').first() if self.request.POST: context['images'] = ImageGalleryFormSet(self.request.POST, self.request.FILES) context['company_locations'] = CompanyLocationFormset(self.request.POST) else: context['images'] = ImageGalleryFormSet(self.request.GET or None) context['company_locations'] = CompanyLocationFormset(self.request.GET or None) return context @transaction.atomic def form_valid(self, form): context = self.get_context_data() images = context['images'] company_locations = context['company_locations'] self.object = form.save() self.object.active = False self.object.status = CompanyConstants.CompanyStatus.NEW self.object.owner = self.request.user self.object.save() for image in range(len(images)): key_image = 'gallery_items-' + str(image) + '-image' form_image = self.request.FILES.get(key_image) if form_image: ImageGallery(image=form_image, company_id=int(self.object.id)).save() print(company_locations.forms[0].get_cleaned_data) for location in range(len(company_locations)): key_locations = 'form-' + str(location) + '-location' key_address = 'form-' + str(location) + '-address' if self.request.POST.get(key_locations): location = self.request.POST.get(key_locations) address = self.request.POST.get(key_address) company = self.object CompanyLocation.objects.create(location=clean_location(location), address=address, company=company) return super().form_valid(form) def get_success_url(self): return reverse('main:profile', args=[self.request.user.username]) when i try print this i have error, this code that i have works correc but, he is bad. MY FORM: class CompanyLocationForm(forms.ModelForm): location = geo_forms.PointField(widget=GooglePointFieldWidget) class Meta: model = CompanyLocation … -
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/catalog/
I got the follwoing error whenever I run the project and automatically catalog/ is added to the url: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/catalog/ Using the URLconf defined in first_project.urls, Django tried these URL patterns, in this order: [name='index'] admin/ first_app/ The current path, catalog/, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. Here is my project urls.py from django.contrib import admin from django.urls import path, include from first_app import views urlpatterns = [ path('', views.index, name='index'), path('admin/', admin.site.urls), path('first_app/', include('first_app.urls')), ] Here is first_app urls.py code: from django.urls import path from first_app import views urlpatterns = [ path('', views.index, name='index'), ] How to get the index page as a default and get rid of the catalog. -
Decorators for authentication using oauth in Django
I am trying to complete Oauth2 using a Decorator in Django. Until before I tried using decorator, I was doing it using this endpoint oauth (which works alright): Note: OSCAR_CALLBACK_URL is URL for oauth endpoint only def oauth(request): if not request.GET.get('oauth_verifier'): return oscar_oauth_init(request) else: res = oscar_oauth_accesstoken(request) return res def oscar_oauth_init(request): oauth = OAuth1(OSCAR_CLIENT_ID, client_secret=OSCAR_CLIENT_SECRET) url=OSCAR_INIT_URL+OSCAR_CALLBACK_URL r = requests.get(url=url, auth=oauth) credentials = convert(parse_qs(r.content)) resource_owner_key = str(credentials.get('oauth_token')[0]) resource_owner_secret = str(credentials.get('oauth_token_secret')[0]) verifier = oscar_oauth_auth(resource_owner_key) request.session['resource_owner_key'] = str(resource_owner_key) request.session['resource_owner_secret'] = str(resource_owner_secret) request.session['verifier'] = str(verifier) return verifier def oscar_oauth_accesstoken(request): verifier = request.GET.get('oauth_verifier') resource_owner_key = request.GET.get('oauth_token') resource_owner_secret = request.session.get('resource_owner_secret') oauth = OAuth1(OSCAR_CLIENT_ID, client_secret=OSCAR_CLIENT_SECRET, resource_owner_key=resource_owner_key, resource_owner_secret=resource_owner_secret, verifier=verifier) r = requests.get(url=OSCAR_TOKEN_URL+verifier, auth=oauth) credentials = convert(parse_qs(r.content)) resource_owner_key = credentials.get('oauth_token')[0] resource_owner_secret = credentials.get('oauth_token_secret')[0] request.session['resource_owner_key'] = str(resource_owner_key) request.session['resource_owner_secret'] = str(resource_owner_secret) return credentials This endpoint was required to be called before other API calls that needed user to be authorized. I am trying to refactor this using the following decorator now: def oscar_login(view_func): def _wrapped_view_func(request, *args, **kwargs): if not request.GET.get('oauth_verifier'): return oscar_oauth_init(request) else: return oscar_oauth_accesstoken(request) return view_func(request, *args, **kwargs) I am not sure how to complete the redirection bit using the decorator. I allowed redirection to the same endpoint oauth (shared above) but the flow stops at end of the endpoint … -
which framework is better for build an audio library site such as soundcloud?
I have a name_cheap regular hosting and I would like to build a web site for users who want to share audio files such as podcast and listening online and maybe using an mobile app, very similar to soundcloud, but I am not sure which is the best framework to do it. Django? Node.js? any other idea. Thanks in advance for help me out. -
Django form gets image data but not text
I have Django form that displays information about the property and the idea of this form is to allow users to amend information about their properties. When displaying the form only image data is displayed, everything else is blank. From if request.user.landlord_profile.landlord_id == project.landlord_id: is the code for the form. views.py def project_detail(request, pk): project = Properties.objects.get(pk=pk) applyButton = Property_Applications.objects.filter(listing=project) propertyReview = Property_Reviews.objects.filter(property=project) # getting the urls property_images = Property_Images.objects.filter(property=project) context = { 'project': project, 'propertyReview': propertyReview, 'property_images' : property_images, } if request.user.is_authenticated: if request.user.last_name == 'False': # allows to tenant to view ads and apply for them if they meet the requirements tenant_profile = Tenant_Profile.objects.get(tenant=request.user.tenant_profile.tenant_id) if request.method == "POST": applyButton = Property_Applications( user=request.user, listing=project,) applyButton.save() context['applyButton'] = applyButton context['tenant_profile']= tenant_profile if request.user.landlord_profile.landlord_id == project.landlord_id: # if the landlord owns this ad, this let's him edit the ad change_listing_form = CreatingListingForm(request.POST, request.FILES, instance=project) if request.method == 'POST': if change_listing_form.is_valid(): change_listing_form.landlord = request.user.landlord_profile change_listing_form.save() messages.success(request, f'Your account has been updated!') else: change_listing_form = CreatingListingForm() context['change_listing_form'] = change_listing_form return render(request, 'project_detail.html', context) project_detail.html - this is what displays the form {% elif request.user.landlord_profile.landlord_id == project.landlord_id%} <p></p> <div style="text-align: center"> <button class="open-button" onclick="openForm()">Manage your Spot</button> </div> <div class="form-popup" id="myForm"> <form class="form-container text-dark" method="POST" … -
How to exchange base docker images safely, when image is down?
I'm learning Docker. Right now I'm working on a Django app and I want to make a container. I'm on Windows 10. When I run docker-compose build, I get: $ docker-compose build Building movies Step 1/9 : FROM python:3.8.2-alpine 3.8.2-alpine: Pulling from library/python Service 'movies' failed to build: no matching manifest for windows/amd64 10.0.18363 in the manifest list entries As far as I've investigated, I'm getting that error because the image is down (because of a bug of docker?) a) https://github.com/nginxinc/docker-nginx/issues/230 b) https://github.com/docker-library/official-images/issues/3835 So what image can replace this one: FROM python:3.8.2-alpine??? I'm following this tutorial Test-Driven Development with Django, Django REST Framework, and Docker from https://testdriven.io/. Dockerfile: # pull official base image FROM python:3.8.2-alpine # set work directory RUN mkdir -p /usr/src/app WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install dependencies RUN pip install --upgrade pip COPY ./requirements.txt /usr/src/app/requirements.txt RUN pip install -r requirements.txt # copy project COPY . /usr/src/app/ -
How to receive Empty files in djnago views and save it even if the file is not uploaded as it is optional?
As my image option is optional , I want to save it even if the file is not uploaded as it is optional, but it is giving me error as it is not able to receive the image. How can I save it in the database even if that field is empty? #Model class Recommendations(models.Model): Name = models.CharField(max_length=100) Company = models.CharField(max_length=100, null=True) Designation = models.CharField(max_length=100, default='Null') Message = models.TextField(null=False) image = models.ImageField(upload_to='Recommender', default='default.png', blank=True) check = models.BooleanField(default=False) # Views Code to receive the data through a form def recommend(request): if request.method == 'POST': try: name = request.POST['name'] company = request.POST['company'] designation = request.POST['designation'] message = request.POST['message'] image = request.FILES['photo'] recom = Recommendations(Name=name,Company=company,Designation=designation, Message=message, image=image) recom.save() messages.success(request,'Recommendation Recieved') return redirect('/') except Exception as problem: print(problem) messages.error(request, problem) return redirect('/') -
How to mock out custom throttle class for testing in django-rest-framework?
I have a custom throttle class like: (print statements are for debugging :)) in api.throttle.py print("befor CustomThrottle class") class CustomThrottle(BaseThrottle): def __init__(self): super().__init__() print("initializing CustomThrottle", self) self._wait = 0 def allow_request(self, request, view): print("CustomThrottle.allow_request") if request.method in SAFE_METHODS: return True # some checking here if wait > 0: self._wait = wait return False return True def wait(self): return self._wait my api.views.py is like: from api.throttle import CustomThrottle print("views module") class SomeView(APIView): print("in view") throttle_classes = [CustomThrottle] def post(self, request, should_exist): # some processing return Response({"message": "Done."}) and my tests is api/tests/test_views.py: @patch.object(api.views.CustomThrottle, "allow_request") def test_can_get_confirmation_code_for_registered_user(self, throttle): throttle.return_value = True response = self.client.post(path, data=data) self.assertEqual( response.status_code, status.HTTP_200_OK, "Should be successful", ) @patch("api.views.PhoneConfirmationThrottle") def test_learn(self, throttle): throttle.return_value.allow_request.return_value = True response = self.client.post(path, data=data) self.assertEqual( response.status_code, status.HTTP_200_OK, "Should be successful", ) the first test passes correctly but still the CustomThrottle class is instantiated but the allow_request method is mocked; the second test shows that neither CustomThrottle class is mocked nor the allow_request method and it fails with status 429 (CustomThrottle has a throttle rate of 2 minutes). -
django: css files not loading in production with nginx
I have seen many similar posts but nothing has been able to make the trick for me. Browser throws me this kind of error for all my css files when i load my static. GET https://www.exostock.net/staticfiles/vendor/font-awesome/css/font-awesome.min.css net::ERR_ABORTED 404 (Not Found) and Home:136 GET https://www.exostock.net/staticfiles/img/logo8.png 404 (Not Found) from the information I read and the django + nginx documentations, I am not able to spot where I am making a mistake. I have been on it for a few days now and I hope that someone could see what I cannot. nginx/sites-available/app.conf server { server_name exostock.net www.exostock.net; location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/exostocksaas/app.sock; } location /static/ { alias /home/ubuntu/exostocksaas/collected_static/; } location ~ \.css { add_header Content-Type text/css; } location ~ \.js { add_header Content-Type application/x-javascript; } } settings.py in django STATIC_URL = '/staticfiles/' # STATICFILES_FINDERS = ( # 'django.contrib.staticfiles.finders.FileSystemFinder', # ) STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'staticfiles') ] STATIC_ROOT = os.path.join(BASE_DIR, 'collected_static') and my html links to statics <!-- Bootstrap CSS--> <link href="{% static 'vendor/bootstrap/css/bootstrap.min.css' %}"> <!-- Font Awesome CSS--> <link href="{% static 'vendor/font-awesome/css/font-awesome.min.css' %}"> <!-- Custom Font Icons CSS--> <link href="{% static 'css3/font.css' %}"> -
How do I allow users of Django to create their own personal blog?
I have created a Django site that allows users to post and comment on these posts. I thought it would be a good idea to allow each user to have their own "page" where they can allow invited members this page to basically use the blog feature that I've designed. The only thing I can't figure out is how to allow users to dynamically create a page that is specific to them. Can this be done with one template? -
django views: How to get the desired column name?
I would like to ask the same question again because my previous was not answered. Here is the link: How to get the desired column name? Thanks very much for the help. -
Why is Django using version 2.0.3 while I have 3.0.5 installed?
I have django installed in a virtual environment, everything works, however when you start a server it starts django 2 instead of 3. (venv) C:\Users\Patrick\PycharmProjects\OptionDetails.com>cd optiondetails (venv) C:\Users\Patrick\PycharmProjects\OptionDetails.com\OptionDetails>py manage.py runserver Performing system checks... System check identified no issues (0 silenced). April 30, 2020 - 18:53:56 Django version 2.0.3, using settings 'OptionDetails.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. (venv) C:\Users\Patrick\PycharmProjects\OptionDetails.com\OptionDetails>py -m pip install -U Django Requirement already up-to-date: Django in c:\users\patrick\pycharmprojects\optiondetails.com\venv\lib\site-packages (3.0.5) Requirement already satisfied, skipping upgrade: asgiref~=3.2 in c:\users\patrick\pycharmprojects\optiondetails.com\venv\lib\site-packages (from Django) (3.2.7) Requirement already satisfied, skipping upgrade: sqlparse>=0.2.2 in c:\users\patrick\pycharmprojects\optiondetails.com\venv\lib\site-packages (from Django) (0.3.1) Requirement already satisfied, skipping upgrade: pytz in c:\users\patrick\pycharmprojects\optiondetails.com\venv\lib\site-packages (from Django) (2020.1) Could not build wheels for Django, since package 'wheel' is not installed. Could not build wheels for asgiref, since package 'wheel' is not installed. Could not build wheels for sqlparse, since package 'wheel' is not installed. Could not build wheels for pytz, since package 'wheel' is not installed. -
Posting product quantity in a Django form
I'm working with an e-commerce webapp and in the product detailed-view I want to give the option to set the quantity before the checkout. I thought I could do this with a simple form: class QuantityForm(forms.Form): quantity = forms.IntegerField(widget=forms.NumberInput(attrs={'class':'required'})) And then implementing it to the view: class BagDetailView(DetailView): context_object_name = 'ctx' model = Bag template_name = 'product_page.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = QuantityForm(initial={'quantity':1}) context['Jackson'] = Bag.objects.get(title = 'Jackson') context['Anthony'] = Bag.objects.get(title = 'Anthony') return context But the problem is the POST request. I cannot call the render() function because I have another view to handle the checkout, so I need to call redirect(). This is the code: def post(self, *args, **kwargs): form = QuantityForm() b = Bag.objects.get(slug=kwargs['slug']) if form.is_valid: return redirect(b)# calls get_absolute_url which redirects to checkout/<slug> And I cannot access the data that I'm posting in the other view. I think it's bad practise to post data like this to another view, but I couldn't come up with anything but that. Is there any other way to pass that data into the other view? Note: I'm not using a cart system because I'm only dealing with two products. -
How to force migrations withouth access to db
I am working on Django application. The situation is: I have some fixtures that i want to apply to database withouth deleting existing data. If i try to import data: python manage.py loaddata products/fixtures/products/small_test_data.json The application return me: Could not load x: null value in column "image_url" violates not-null constraint DETAIL: Failing row contains (2, Test, 99, 1000, null, 2, 3). I know there are kinds solutions where you need to remove some tables from db, but I want to migrate tables withouth deleting or corrupting database. If this is possible, I would like to do it withouth access to database. -
Trying to generate separate DOB fields on edit profile view - Django
I have been looking around and trying to get a drop down menu for Date of Birth e.g. dd/m/yyyy for my project, I'm currently using the following: This code snippet is from the edit profile page of my web application. YEARS= [x for x in range(1940,2021)] birth_date = forms.DateField(label='What is your birth date?', initial="1990-06-21", widget=forms.SelectDateWidget(years=YEARS)) When viewing the actual edit page, this does not appear to render. However, if you were to either inspect element, or view page source you can see the following: <select name="birth_date_month" required id="id_birth_date_month"><option value="1">January</option><option value="2">February</option><option value="3">March</option><option value="4" selected>April</option><option value="5">May</option><option value="6">June</option><option value="7">July</option><option value="8">August</option><option value="9">September</option><option value="10">October</option><option value="11">November</option><option value="12">December</option></select><select name="birth_date_day" required id="id_birth_date_day"><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option><option value="10">10</option><option value="11">11</option><option value="12">12</option><option value="13">13</option><option value="14">14</option><option value="15">15</option><option value="16">16</option> --- Truncated for demo purposes --- Model: birth_date = models.DateField(null=True, blank=True) I am however able to use and view the following successfully, although this is not what I want to view: dob = forms.CharField(widget=forms.widgets.DateTimeInput(attrs={"type": "date"})) However, this just looks like one of those crappy date selectors that aren't particular great... Inefficient date selector Can someone point me in the right direction please? -
Django app not including base.html template in downstream apps
I have a Django application where I am trying to set up a base html template to include footers, navbars etc which I can re-use across the site. The issue I am having is that I get an error when I try to include my base template in the downstream app template folders and indexes. I hope that makes sense. In my main root directory I have templates/base.html and in my app at NewsBase/templates/NewsBase/index.html I have the below: {% extends 'templates/base.html' %} <body> <h1>NewsBase</h1> </body> My routes/urls are working fine as this html renders as long as the extends block is removed. How can I properly include my base.html template from other apps in the solution? Base.html <!DOCTYPE HTML> {% load staticfiles %} {% block content %}{% endblock %} {% include "footer.html" %} </html> Error: TemplateDoesNotExist at / templates/base.html Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 1.11.29 Exception Type: TemplateDoesNotExist Exception Value: templates/base.html Exception Location: /home/etherk1ll/.local/lib/python2.7/site-packages/django/template/engine.py in find_template, line 148 Python Executable: /usr/bin/python Python Version: 2.7.17 Python Path: ['/home/etherk1ll/Development/python_projects/NewSite', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/home/etherk1ll/.local/lib/python2.7/site-packages', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages'] Server time: Thu, 30 Apr 2020 22:30:51 +0000 -
Django Channels Realtime Chat
Django channels Realtime chat Task build realtime chat, as well as sending / receiving notifications not related to the chat. A total of 2 real-time functions. Tools backend - django frontend - Android Mobile App Problem on a localhost, the code works, messages reach the client. Deployed on Heroku, the tariff is free. It turned out that there is a limit on connections = 20 (which is not enough for one user for 10 minutes). After each request, a new connection is created through ASGI, everything is ok for WSGI. To the limit - everything works, but when there are 20 connections, messages reach 2-3 times. Attempts to solve 1. I registered in the code close_old_connections, it did not work to kill the connection. Those for each message creates a new connection. Googled for several days, did not find a solution on this issue. 2. I tried with both Daphne and Uvicorn - the effect is the same Question maybe django-channels is not a suitable option for the task. Perhaps it’s worth abandoning Heroku, deploying to another hosting and raising Nginx, and all the restrictions will disappear? The offial documentation says that django-channels should support up to 1000 connections, but … -
How take values of params a URL in Django and give a Form
models.py class Prueba(models.Model): #collection name cantidad = models.PositiveIntegerField(default=1) def __str__(self): return str(self.cantidad) urls.py from django.urls import path from . import views app_name = "home_app" urlpatterns = [ path( 'confirmar_viaje/', views.SampleView.as_view(), name='userviajes', ), ] View.py class SampleView(CreateView): model=Prueba template_name='testpag.html' form_class=TestForm success_url = '/' def init_page(request): print(request.GET) pasajeros = self.request.form['pasajeros'] print(pasajeros) forms.py class TestForm(forms.ModelForm): class Meta: model=Prueba fields=['cantidad'] I use a DetailView, inside html have a form(html). The result is /test/?pasajeros=99 I want to take from de url params. pasajeros=99 and fill a textfield from form. The code dont have errors but i need to recuperate the param or params. Any Idea? -
Can't add widget to UserCreationForm
I want to style my form. And I need to add placeholder to all inputs but can't add placeholder to password1 and password2. I tried: class RegistrationForm(UserCreationForm): """ The registration form that inherits UserCreationForm. Fiels: ['email', 'username', 'password', 'password_repeat'] Windgets: For all inputs we creates atributte class: .signup_input """ class Meta: model = Account fields = ['email', 'username', 'password1', 'password2'] widgets = { 'email': forms.TextInput(attrs={'placeholder': 'Email'}), 'username': forms.TextInput(attrs={'placeholder': 'Type your username'}), 'password1': forms.TextInput(attrs={'placeholder': 'Choose a password'}), 'password2': forms.PasswordInput(attrs={'placeholder':'Confirmar Password'}), } this is my model: class Account(AbstractBaseUser): """ The class Account inherits AbstractBaseUser. This is a model for users. Fields: ['email', 'username', 'date_joined', 'is_active', 'is_moderator', 'is_admin', 'is_superuser', 'is_staff'] Model manager is: objects = MyAccountManager() """ email = models.EmailField(max_length=20, unique=True, verbose_name='email') username = models.CharField(max_length=12, unique=True) date_joined = models.DateTimeField(auto_now_add=True, verbose_name='date joined') is_active = models.BooleanField(default=True) is_moderator = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) #What user will put into form USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username',] How can I add placeholder to password1 and password2? Thanks) -
Porting and existing nested set hierarchy
I have a nested set category table developed with the PHP ORM Doctrine and I would like to port it to a Django app. I started porting it to django-treebeard, but I am having difficulties and I am not sure it can work. The original table had the needed fields lft, rgt and depth, so I added the tree_id field. I also had a foreign key to Accounts with one tree/account. Thus the table hold multiple independent trees that are not under a common root, with the lft and depth columns starting at 1 for each tree. So basically one nested set for each account in the table. I can add nodes to a tree just fine, but when I call the get_last_child method, I get nodes from other accounts. Does anyone know if there is a way to use treebeard, mptt or any other package without having to restructure the trees? -
Should I use the built-in admin panel Django? [closed]
There are html templates for the admin panel and personal profile of the site. Do I need to customize the built-in admin panel or is it better to use templates separately? -
Django REST Framework, setting up Django Storages/S3 Boto to store some media files to the bucket, and some to local storage
I've setup Django Storages/S3 Boto to save user-uploaded files to the s3 bucket, with the settings bellow: # AWS Bucket access keys AWS_ACCESS_KEY_ID = 'id' AWS_SECRET_ACCESS_KEY = 'key' # AWS Bucket config stuff DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_STORAGE_BUCKET_NAME = 'bucketname' AWS_S3_REGION_NAME = 'us-east-1' AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com/' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} # Media file location MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/' How would i modify the storage settings/configuration so that i can save some user uploaded files to this S3 bucket, while saving some others to the local file system? Currently, my FileField looks like this: class File(models.Model): created_at = models.DateTimeField(auto_now_add=True) email = models.EmailField(default='email@email.com') file = models.FileField(upload_to=upload_path) def __str__(self): return self.email + '-' + self.file.name my "upload_path" looks like this: def upload_path(instance, filename): return instance.email + '/' + filename -
django.core.exceptions.ImproperlyConfigured: The database name '****.amazonaws.com' (85 characters) is longer than PostgreSQL's limit of 63 characters
I am trying to migrate my Django model to the AWS Lightsail database, but I am getting below error. My database is on AWS Lightsail. it is PostgreSQL. I am deploying my project on AWS so I have set up almost everything except model migration. AMAZON DATABASE AVAILABLE CONNECTION OPTIONS: Endpoint-> ************.ap-******-1.***.amazonaws.com, Port-> 5444, User name-> db, Password-> Something MY SETTINGS.PY FILE DATABASE CONNECTION OPTIONS: 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': '****Endpoint*****', 'USER': 'db', 'PASSWORD': 'Something', 'HOST': '5444' } } Terminal Error: > `2, in build_graph self.applied_migrations = recorder.applied_migrations() File "/home/bitnami/portfolio/ManojJha-portfolio/.venv/lib/python3.7/site-packages/django/db/migrations/recorder.py", lin e 76, in applied_migrations if self.has_table(): File "/home/bitnami/portfolio/ManojJha-portfolio/.venv/lib/python3.7/site-packages/django/db/migrations/recorder.py", lin e 56, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "/home/bitnami/portfolio/ManojJha-portfolio/.venv/lib/python3.7/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/bitnami/portfolio/ManojJha-portfolio/.venv/lib/python3.7/site-packages/django/db/backends/base/base.py", line 260, in cursor return self._cursor() File "/home/bitnami/portfolio/ManojJha-portfolio/.venv/lib/python3.7/site-packages/django/db/backends/base/base.py", line 236, in _cursor self.ensure_connection() File "/home/bitnami/portfolio/ManojJha-portfolio/.venv/lib/python3.7/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/bitnami/portfolio/ManojJha-portfolio/.venv/lib/python3.7/site-packages/django/db/backends/base/base.py", line 220, in ensure_connection self.connect() File "/home/bitnami/portfolio/ManojJha-portfolio/.venv/lib/python3.7/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/bitnami/portfolio/ManojJha-portfolio/.venv/lib/python3.7/site-packages/django/db/backends/base/base.py", line 196, in connect conn_params = self.get_connection_params() File "/home/bitnami/portfolio/ManojJha-portfolio/.venv/lib/python3.7/site-packages/django/db/backends/postgresql/base.py" , line 165, in get_connection_params self.ops.max_name_length(), django.core.exceptions.ImproperlyConfigured: The database name '*****************Database End-point*****************.***.amazonaws.com' (85 characters) is longer than PostgreSQL's limit of 63 characters. Supply a shorter NAME in settings.DATABASES.``` So is there any … -
How to plug the reponse of a django view GET request into the same view as a POST request during testing?
I have a Django function-based form view that initializes a form with default data on a GET request, and saves the model object on a POST request: def copy(request, ann_id): new_ann = get_object_or_404(Announcement, pk=ann_id) new_ann.pk = None # autogen a new primary key (quest_id by default) new_ann.title = "Copy of " + new_ann.title new_ann.draft = True new_ann.datetime_released = new_ann.datetime_released + timedelta(days=7) form = AnnouncementForm(request.POST or None, instance=new_ann) if form.is_valid(): new_announcement = form.save(commit=False) new_announcement.author = request.user new_announcement.datetime_created = timezone.now() new_announcement.save() form.save() return redirect(new_announcement) context = { "title": "", "heading": "Copy an Announcement", "form": form, "submit_btn_value": "Create", } return render(request, "announcements/form.html", context) I can't figure out how to test the form.is_valid() branch when the form is posted, without manually providing the form data to self.client.post(url, form_data) in my view. What I want to actually test is that the result of the get provides valid default data for the form that can then be submitted via post request. But I can't figure out how to change the repsonses, so that the form data resulting form the get request is then fed into the form data provided to the post request. EDIT I found the location of the form in the get response, but …