Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to prevent form update conflict among multiple users in Django?
I have a form like a student form. It can be updated by a function in view. There are multiple users that have the update permission for this form. The problem is when 2 users open the form of a student(id=1) at the same time. They can change fields and save the form. All changes of a user will be ignored and lost. How to prevent this conflict. I want if a user opens a specific student form, other users can not open it until the first user close the form or it's time for the update be expired. -
How to convert javascript object to python readable
I'm trying to parse below object from javascript post data into python using ast.literal_eval(obj) but ending up into below error Error: malformed node or string: <_ast.Name object at 0x7fb484eb8070> Object Value: '[{"dose":"1","duration":"2","name":"Item1","code":"pharma2","usage":{"morning":true,"afternoon":false,"evening":false,"night":false,"sos":false}},{"dose":"1","duration":"4","name":"Item2","code":"pharma1","usage":{"morning":false,"afternoon":false,"evening":false,"night":true,"sos":false}}]' -
How to choose one item in many to many relationship as special?
What is the best practice to choose one item from a m2m relationship? Lets say I've got an album of photos: class Photo(models.Model): img = models.FileField() class Album(models.Model): photos = models.ManyToManyField("Photo") But now I also want to pick one photo as a cover. I could use a Foreign Key in Album to one Photo, but then I'd always need to check whether this photo is actually in the photos of that album. Is there a better way? Sorry for the basic question I just somehow can't find the right words to google it. Thanks, Michael -
How to pass Django InMemoryUploadFile to serializer in case with images?
I'm creating an API using Django Rest Framework to save images from file directly or from url. I've got no problem with first case but with second. So, my models looks like this: class Image(models.Model): picture = models.ImageField(upload_to="site_media", blank=True) url = models.URLField(null=True, blank=True, max_length=255) parent_picture = models.IntegerField(null=True, blank=True) @property def name(self): return os.path.split(self.picture.name)[-1] @property def width(self): return self.picture.width @property def height(self): return self.picture.height Next, my serializer class: class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = [ 'id', 'name', 'url', 'picture', 'width', 'height', 'parent_picture' ] The main idea is if you pass the URL while post request, API needs to download image from this URL and store it in database. To do this I overwrote create method in Django Rest Framework ModelViewSet class: from io import BytesIO import urllib import os from django.core.files.uploadedfile import InMemoryUploadedFile from PIL import Image as PILImage from rest_framework import status from rest_framework import viewsets from rest_framework.response import Response from .models import Image from .serializers import ImageSerializer class ImageViewSet(viewsets.ModelViewSet): serializer_class = ImageSerializer queryset = Image.objects.all() def create(self, request, *args, **kwargs): if request.data["url"]: url = request.data["url"] image_extensions = { ".jpg": "JPEG", ".jpeg": "JPEG", ".png": "PNG", ".gif": "GIF" } image_path = urllib.parse.urlparse(url).path image_filename = image_path.split("/")[-1] extension = os.path.splitext(image_filename)[-1] … -
Django Admin Templates - How to add a "back to list" button?
Working with Django admin - still pretty new. I need to add a button to the footer (that appears when editing or adding an object) that sends the user back to the list page for that object. I am able to add the button itself to the footer by adding templates/admin/submit_line.html: {% load i18n admin_urls %} <div class="submit-row"> {% if show_save %}<input type="submit" value="{% trans 'Save' %}" class="default" name="_save" {{ onclick_attrib }}/>{% endif %} {% if show_delete_link %}<p class="deletelink-box"><a href="{% url opts|admin_urlname:'delete' original.pk|admin_urlquote %}" class="deletelink">{% trans "Delete" %}</a></p>{% endif %} {% if show_save_as_new %}<input type="submit" value="{% trans 'Save as new' %}" name="_saveasnew" {{ onclick_attrib }}/>{%endif%} {% if show_save_and_add_another %}<input type="submit" value="{% trans 'Save and add another' %}" name="_addanother" {{ onclick_attrib }}/>{% endif %} {% if show_save_and_continue %}<input type="submit" value="{% trans 'Save and continue editing' %}" name="_continue" {{ onclick_attrib }}/>{% endif %} <input type="submit" value="{% trans 'Go Back' %}" {{???}}/> </div> But I don't know where to go from there. Presumably it is possible because Django breadcrumbs exist (and the relevant page is always the most recent link in the breadcrumbs), but I don't know how I'm supposed to get the link to the relevant page. -
when ever i am adding def str function to name it the model gives error
def __str__(self): return self.category_name when ever i am adding this str function in my model class Category(models.Model): category_name = models.CharField(max_length=50, unique=True,blank=True,null=True) slug = models.SlugField(max_length=100, unique=True,blank=True,null=True) description = models.TextField(max_length=255, blank=True,null=True) cat_image = models.ImageField(upload_to='photos/categories', blank=True,null=True) class Meta: verbose_name = 'category' verbose_name_plural = 'categories' def get_url(self): return reverse('core:category', args=[self.slug]) then it gives me error TypeError at /admin/core/product/ str returned non-string (type NoneType) -
Passing Django view data to JavaScript Chart
I have some data that is returned via Django view, I'm trying to render the data in an Apex Pie Chart. So I need to pass the data into JavaScript as this is where the data series is. var pieColors = getChartColorsArray("#pie_chart"), options = { chart: { height: 320, type: "pie" }, series: [44, 55, 41, 17, 15], labels: ["Series 1", "Series 2", "Series 3", "Series 4", "Series 5"], colors: pieColors, legend: { show: !0, position: "bottom", horizontalAlign: "center", verticalAlign: "middle", floating: !1, fontSize: "14px", offsetX: 0 }, responsive: [{ breakpoint: 600, options: { chart: { height: 240 }, legend: { show: !1 } } }] }; (chart = new ApexCharts(document.querySelector("#pie_chart"), options)).render(); How do I pass the data in as it needs to be dynamic in the sense that the data in the pie chart could change based on other actions within the app? Should just embed the JS into my HTML template and then set the series values to series: [{{ value.1 }}, {{ value.2 }}, ...], Thanks -
LeaderboardAPI : I want to show only Today's record by comparing it with the created date
My Modely.py I am storing playername, TotalPoints, created_date by POST API from django.db import models from django.utils.translation import ugettext as _ # Create your models here. class leaderboard(models.Model): name = models.CharField(_("playername"), max_length=255) TotalPoints = models.IntegerField(_("TotalPoints")) created_date = models.DateTimeField(auto_now_add=True) My Serializers.py file: This is my Searializer: from rest_framework import serializers from .models import leaderboard class leaderboardSerializers(serializers.ModelSerializer): class Meta: model = leaderboard fields = [ 'name', 'TotalPoints', ] class lwithcdateSerializers(serializers.ModelSerializer): class Meta: model = leaderboard fields = [ 'name', 'TotalPoints', 'created_date', ] My Views class Leaderboard(APIView): def get(self, request, formate=None, **kwargs): today = datetime.date.today() serializer = lwithcdateSerializers(leaderb.objects.all().order_by('-TotalPoints') [:40], many=True) return Response(serializer.data) Please check the above code and let me know how can I display only Today's record -
Django - Changed DB from Sqlite3 to Postgres - do I need to do something else to reflect changes?
In my server, I changed the DB to Postgres from SQlite3. Because this is a new website and doesn't have much data yet (except test stuff) I didn't have to do DB migration or whatever else it is called. I just changed settings.DATABASES to include Postgres. Here's my settings.DATABASES in settings.py: from sys import platform if platform == 'darwin': # OSX DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR + '/db.sqlite3', } } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'pfcbookclub', 'USER': 'admin', 'PASSWORD': 'g&zy8Je!u', 'HOST': '127.0.0.1', 'PORT': '5432', } } I develop on an M1, and psycopg2 doesn't seem to work for me, how many ever times I try to install libq or openssl with Homebrew on Rosetta, which is why I decided to use Sqlite on my Mac and Postgres on my server. Now, when I pulled these changes with git onto my server, I refreshed the page on my domain, but all the test data I had filled in my Sqlite3 database still showed. I thought it would be empty because I haven't filled up the Postgres DB with anything and I didn't do any sort of migration that would convert db.sqlite3 into Postgres … -
This page isn’t working right now. If the problem continues, contact the site owner. HTTP ERROR 405
I am getting the following error message when I fill the form: This page isn’t working right now. If the problem continues, contact the site owner. HTTP ERROR 405. Kindly advise. views: from django.shortcuts import render, get_object_or_404 from .models import Post from django.http import HttpResponseRedirect from django.urls import reverse from django.views.generic import ListView from .forms import CommentForm from django.views import View class UltimatePostView(View): def get(self, request, slug): post = Post.objects.get(slug=slug ) context = { "post": post, "post_tags" : post.tag.all(), "comment_form" : CommentForm() } return render(request, "gold-blog/post-detail.html", context ) def post(self, request, slug): comment_form = CommentForm(request.POST) post = Post.objects.get(slug=slug ) if comment_form.is_valid(): comment = comment_form.save(commit=False) comment.post = post comment.save() return HttpResponseRedirect(reverse("post-detail-page", args=[slug])) context = { "post": post, "post_tags" : post.tag.all(), "comment_form" : comment_form } return render(request, "gold-blog/post-detail.html", context) -
Django admin is very slow when loading from the OneToOne user model
I think I am doing admin model wrong because it is taking like 30 seconds to load and I think its because my sql queries are too inefficient and there may be creating more look ups than needed. Is there a way that I can speed this up? class UserInformationAdmin(admin.ModelAdmin): list_display = ( 'user_username', 'user_first_name', 'user_last_name', 'major' ) @admin.display(description='user.username') def user_username(self, obj): try: return obj.user.username except Exception: return None @admin.display(description='user.first_name') def user_first_name(self, obj): try: return obj.user.first_name except Exception: return None @admin.display(description='user.last_name') def user_last_name(self, obj): return obj.user.last_name``` -
how to trigger email to admin panel in django through contact form using form.is_valid()?
Whenever a user sends email through the contact form, it should be displayed to the admin in the admin panel. Now, when I click submit, it goes back to "contact.html" as stated in function, what are the possible reasons it is not being valid when it is saved? I'm pretty sure I'm filling the form correctly from the web. here is the model: class Contact(models.Model): name = models.CharField(max_length=100) email = models.EmailField(default="default") subject = models.CharField(max_length=100) message = models.CharField(max_length=100) def __str__(self): return self.name the function in views.py: def display3(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): form.save() return render(request, 'success.html') form = ContactForm() context = {"form": form} return render(request, 'contact.html', context) lastly, this is in forms.py: class ContactForm(ModelForm): class Meta: model = Contact fields = '__all__' -
Unable to fetch row elements values using Javascript
I'm little new to Javascript. This is using django as backend. I'm trying to capture data from table columns like 'dose', 'duration' and 'usage' which uses text box and checkbox. Whenever I hit the button with id='qty', then I'm able to see correct value for first click but when I click the button for another element it still submits same previous data instead of data on the same row. Below is the sample output that I captured from console log #Item 1 Log [Log] Object (e28c8d12-1a95-44e5-9813-dfc2f4bf3bb1, line 502) code: "" dose: "1" name: "PARACIP" price: undefined quantity: "2" total: NaN usage: {morning: false, afternoon: false, evening: false, night: false, sos: false} #Item 2 Log [Log] Object (e28c8d12-1a95-44e5-9813-dfc2f4bf3bb1, line 502) code: "" dose: "1" name: "Paracetamol" price: undefined quantity: "2" total: NaN usage: {morning: false, afternoon: false, evening: false, night: false, sos: false} Object Prototype HTML Code <table id="example" class="table table-striped table-bordered" style="width:100%"> <thead> <tr> <th>Item</th> <th>Dose</th> <th>Duration</th> <th>Usage</th> <th>Action</th> </tr> </thead> <tbody> {% for item in inventory %} <tr> <td>{{ item.brand }} {{ item.item_name }}</td> <td> <input type="text" class="form-control" name="dose", id="dose"> </td> <td> <input type="text" class="form-control" name="duration" id="duration"> </td> <td> <div class="form-check form-check-inline"> <input class="form-check-input" type="checkbox" id="morning" name="morning"> <label class="form-check-label" … -
Error in DRF only! UNIQUE constraint failed: questions_question.id
Here is the model, serializer and view. When I try to create a new question with the API endpoint It's showing the UNIQUE constraint failed: questions_question.id but It's going to be saved into the admin panel. Please share an idea to solve the error! models.py class Question(models.Model): author = models.ForeignKey( User, on_delete=models.CASCADE, related_name='all_questions') title = models.CharField(max_length=225) desc = models.TextField() slug = models.SlugField(max_length=225, # unique=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self) -> str: return f"{self.title}" serializers.py class QuestionsSerializer(serializers.ModelSerializer): author = serializers.StringRelatedField(read_only=True) class Meta: model = Question fields = "__all__" view.py class QuestionCreateAPI(generics.CreateAPIView): model = qs_models.Question queryset = qs_models.Question.objects.all() serializer_class = own_serializers.QuestionsSerializer permission_classes = (permissions.IsAuthenticated, ) def perform_create(self, serializer): return super().perform_create(serializer.save(author=self.request.user)) Terminal Error return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: UNIQUE constraint failed: questions_question.id But it still saving on the admin panel -
Django Button Handling
I only want to display 2 buttons which should submit on click. If the buttons are clicked it should only display form 2 on the User button or else another form on Doctor button(add field to form 2). Currently it does work if I used radios if I used another submit button but I'd like for button click handling in the wizard which I'm unsure of. flow: form1-> show_message_form_condition {'is_doctor': True} for both buttons clicks and for radio it's is_{'is_doctor': True} and {'is_doctor': False}-> display form 2 if value is false. forms.py class PickUserType(forms.Form): is_doctor = forms.BooleanField(required=False) class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') class Meta: model = Profile fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', ) Both of them {% block content %} <form method = "POST" action='.' enctype="multipart/form-data"> {% csrf_token %} <!-- A formwizard needs this form --> {{ wizard.management_form }} <!-- {{form_as_p}} --> <button type="submit" value="Doctor" name="0-is_doctor">Doc</button> <button type="submit" value="User" name="0-is_doctor">User</button> <!-- {% for field in form.visible_fields %} {{ field.errors }} {% for radio in field %} <div class="form-check form-check-inline"> {{ radio }} </div> {% endfor %} {% endfor %} <input type="submit" … -
wagtail No module named wagtail.contrib
I did start wagtail fresh installation after I did and I want to use python instead python3 pip3 install wagtail wagtail start wagtail02 cd wagtail02 pip3 install -r requirements.txt when I try to do python manage.py migrate I get an error message Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/lotfi/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/lotfi/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute django.setup() File "/home/lotfi/.local/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/lotfi/.local/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/home/lotfi/.local/lib/python2.7/site-packages/django/apps/config.py", line 120, in create mod = import_module(mod_path) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named wagtail.contrib I don't find a solution on internet but if I do python3 manage.py migrate it work, is there a solution to make it working using python instead of python3 -
Add new page function does not work as it should. How can I add new page? Django
I am trying to create a Addpage function with the following features; Clicking “Create New Page” in the sidebar should take the user to a page where they can create a new encyclopedia entry. When the page is saved, if an encyclopedia entry already exists with the provided title, the user should be presented with an error message. Otherwise, the encyclopedia entry should be saved to disk, and the user should be taken to the new entry’s page. VIEWS.PY class AddPageForm(forms.Form): title = forms.CharField() content = forms.CharField(widget=forms.Textarea( attrs={ "class": "form-control", }) ) def add_page(request): if request.method == "POST": form = AddPageForm(request.POST) if form.is_valid(): title = form.cleaned_data['title'] content = form.cleaned_data['content'] # saveInput = SaveInput(title=data['title'], content=data['content']) # saveInput.save() entries = util.list_entries() for entry in entries: if title.upper() == entry.upper(): return render(request, "encyclopedia/errorpage.html") else: return redirect('encyclopedia:entrypage', title=title) util.save_entry(title, content) else: return render(request, "encyclopedia/addpage.html", { "form": AddPageForm() }) URL.PY app_name = "encyclopedia" urlpatterns = [ path("", views.index, name="index"), path("wiki/<str:title>", views.entry_page, name="entrypage"), path("add_page", views.add_page, name="addpage"), ADDPAGE.HTML <h1>Add Page</h1> <form action="{% url 'encyclopedia:addpage' %}" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit" class="btn btn-secondary"> </form> {% endblock %} UTILS.PY def save_entry(title, content): """ Saves an encyclopedia entry, given its title and Markdown content. If … -
DJango Python deployment on Heroku stopped working
We have django based python 3.7 version application was running properly on heroku but suddenly since 2 week all new deployment fails with following error. Its working on my local machine with runserver command. Here is errors logs for more reference. please help me as my prod app needs new changes to deployed and now everything is blocked. Updated Pipfile.lock (599d25)! Installing dependencies from Pipfile.lock (599d25)… To activate this project's virtualenv, run pipenv shell. Alternatively, run a command inside the virtualenv with pipenv run. Removing intermediate container 2125752d2f35 ---> a3b53b037080 Step 10/11 : RUN pipenv install --system ---> Running in fcb5350323a4 Installing dependencies from Pipfile.lock (599d25)… An error occurred while installing importlib-metadata==4.10.0 ; python_version < '3.8' --hash=sha256:92a8b58ce734b2a4494878e0ecf7d79ccd7a128b5fc6014c401e0b61f006f0f6 --hash=sha256:b7cf7d3fef75f1e4c80a96ca660efbd51473d7e8f39b5ab9210febc7809012a4! Will try again. An error occurred while installing zipp==3.7.0 --hash=sha256:9f50f446828eb9d45b267433fd3e9da8d801f614129124863f9c51ebceafb87d --hash=sha256:b47250dd24f92b7dd6a0a8fc5244da14608f3ca90a5efcd37a3b1642fac9a375! Will try again. Installing initially failed dependencies… [pipenv.exceptions.InstallError]: File "/usr/local/lib/python3.7/dist-packages/pipenv/cli/command.py", line 254, in install [pipenv.exceptions.InstallError]: editable_packages=state.installstate.editables, [pipenv.exceptions.InstallError]: File "/usr/local/lib/python3.7/dist-packages/pipenv/core.py", line 1874, in do_install [pipenv.exceptions.InstallError]: keep_outdated=keep_outdated [pipenv.exceptions.InstallError]: File "/usr/local/lib/python3.7/dist-packages/pipenv/core.py", line 1253, in do_init [pipenv.exceptions.InstallError]: pypi_mirror=pypi_mirror, [pipenv.exceptions.InstallError]: File "/usr/local/lib/python3.7/dist-packages/pipenv/core.py", line 862, in do_install_dependencies [pipenv.exceptions.InstallError]: _cleanup_procs(procs, False, failed_deps_queue, retry=False) [pipenv.exceptions.InstallError]: File "/usr/local/lib/python3.7/dist-packages/pipenv/core.py", line 681, in _cleanup_procs [pipenv.exceptions.InstallError]: raise exceptions.InstallError(c.dep.name, extra=err_lines) [pipenv.exceptions.InstallError]: ['Collecting importlib-metadata==4.10.0 (from -r /tmp/pipenv-01ok21hj-requirements/pipenv-lkap3a1h-requirement.txt (line 1))'] [pipenv.exceptions.InstallError]: ['Could not find a version … -
Django ChoiceField get choice value in template
I have a radio button which is a yes / no. YES_NO_CHOICES = [(False,'No'),(True,'Yes')] I also have a choicefield in my ModelForm show_game = forms.ChoiceField(widget=forms.RadioSelect, choices=YES_NO_CHOICES, required=True) I dislike the HTML provided by Django; hence, I made a custom html with css which looks like this: <div class="form-check form-check-inline"> <input class="form-check-input" type="radio" name="id_show_game" id="{{radio.id_for_label}}" value="{{radio.id}}" {% if forloop.counter0 == 0 %}checked="checked"{% endif %}> <label class="form-check-label" for="{{radio.id_for_label}}">{{radio.choice_label}}</label> </div> However, value is appearing empty: How do I access the value of radio which is a ChoiceField WITHOUT using the following: {{radio}} <- result from {% for radio in gameInfoForm.show_game %} {{form}} <- ModelForm type -
I can't center <textarea>
I try to center my <textarea> elements in my pet project but I can't find a way to do that. I have tried using the following approaches: Changing my textarea in CSS: textarea { display: flex; justify-content: center; align-items: center; } Using the text-align property: <div style="text-align: center"><textarea>I am <textarea></textarea></div> Using also <center> tag. Surprisingly, it worked. But I don't like this solution because it is condemned to use. Down here is link of the picture from my project (I can't post one due I don't have enough reputation). Here you can see I have two blocks: textarea provided by Django framework and standard HTML textarea. Both of them are not centered. (https://i.imgur.com/1AzKrWJ.png) Here is my code: <p>Write the reason(s) for refusal:</p> {% render_field form.refusal_reason placeholder="Text..." %} <div style="text-align: center"><textarea>I am <textarea></textarea></div> I have been finding for a solution for a long time but haven't succeed. I will be happy for any useful answer. -
Django - Displaying Images in Templates
I have a Django Website and I am currently working on a delete view that has to be a function-based view for later use. I need to display a name and an image in the template of the data I am deleting at that moment. I had it working as a class-based view but now I need it to be a function-based delete view. The code below works and displays the name but when it comes to the image(which is an image field so I cant just type in a URL in the src) it just displays that little miscellaneous image box on the screen and not my actual image. In the templates, if I put {{ image.url }} it displays nothing. How can I get and image to display in the template from a specific pk in a function-based view. views.py def deleterepo(request, pk): context = {} context['name'] = Add_Repo.objects.values_list('name', flat='True').filter(user=request.user).get(pk=pk) context['image'] = Add_Repo.objects.values_list('image', flat='True').filter(user=request.user).get(pk=pk) obj = get_object_or_404(Add_Repo, pk=pk) if request.method == "POST": obj.delete() return HttpResponseRedirect("/front_page/sheets/") return render(request, "sheets/repo/delete_repo.html", context) {{ name }} <img src="{{ image }}"/> -
Django. I can't download files
I am creating a function to download the created text file when the button is selected on HTML. I created it, but it doesn't download. Is it correct to understand that if this process is successful, it will be downloaded to the download folder? Can you help me? HTML <form action="" method="get"> <button class="btn btn-primary mt-1" type="submit" name="process">PROCESS</button> </form> views ・・・Preprocessing・・・ def downloadtest(readfile): with open(readfile, "r") as f: lines = f.readlines() for line in lines: print(line, end="") response = HttpResponse(f.read(),content_type="text/plain") response["Content-Disposition"] ='attachment; filename=readfile' return response tried lines = f.readlines() for line in lines: print(line, end="") We have also confirmed that the file exists and can be read by this process. -
Online waiting: django submit form and display result in same page
I have an emergent task to make a web page which allow user to input some data and the backend do some calculation and the result needs to be displayed in the same page just below the input field (like air ticket online price check). I am new to django and html. below is my first test web page of a simple online calculator to try to figure out how to make such web service. I found a problem that when clicking the "submit" button, it tends to jump to a new web page or a new web tab. this is not what I want. Once the user input the data and click "submit" button, I want the "result" field on the page directly show the result (i.e. partially update only this field) without refresh/jump to the new page. Also I want the user input data kept in the same page after clicking "submit". I saw there might be several different ways to do this work, iframe/AJAX. However, I have been searching/trying for answers and solutions for several days and none of the answers really work for this very basic simple question!! html: <form method="POST"> {% csrf_token %} <div> <label>num_1:</label> … -
how to collect static files and upload them s3 using django and zappa
I am using django and zappa (https://github.com/zappa/Zappa). I am trying to collect the static file of django and upload it to s3 and after running the command python manage.py collectstatic --no-input for some reason i keep getting these errors: ...raise error_class(parsed_response, operation_name) botocore.exceptions.ClientError: An error occurred (AccessControlListNotSupported) when calling the PutObject operation: The bucket does not allow ACLs ... raise err_cls("S3Storage error at {!r}: {}".format(name, force_str(ex))) OSError: S3Storage error at 'admin/css/widgets.css': An error occurred (AccessControlListNotSupported) when calling the PutObject operation: The bucket does not allow ACLs I have the following configuration: settings.py (i am using django_s3_storage) DEBUG=False ... S3_BUCKET = "my-bucket" STATICFILES_STORAGE = "django_s3_storage.storage.StaticS3Storage" AWS_S3_BUCKET_NAME_STATIC = S3_BUCKET STATIC_URL = "https://%s.s3.amazonaws.com/" % S3_BUCKET STATIC_ROOT = "https://%s.s3.amazonaws.com/" % S3_BUCKET AWS_DEFAULT_ACL = None the current aws user, is part of the group admin of users that i have created, which has administratorAccess policy and on top of that i have created the policy below that i have attached to the same group: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "s3:ListBucket" ], "Resource": [ "arn:aws:s3:::my-bucket" ] }, { "Effect": "Allow", "Action": [ "s3:DeleteObject", "s3:GetObject", "s3:GetObjectAcl", "s3:PutObject", "s3:PutObjectAcl", "s3:CreateMultipartUpload", "s3:AbortMultipartUpload", "s3:ListMultipartUploadParts", "s3:ListBucketMultipartUploads" ], "Resource": [ "arn:aws:s3:::my-bucket/*" ] } ] } Also, i … -
How to update a wagtail UserProfile avatar (or other fields) alongside other CustomUser fields into one django form
I'm using Django and Wagtail to build a webapp. This webapp will be used by a group of members in which some will have admin permissions and most will not. I created a custom user model like so: class User(AbstractUser): bio = models.TextField( verbose_name=_("bio"), blank=True, help_text=_("Write a bit about yourself"), ) phone = PhoneNumberField( verbose_name=_("phone number"), blank=True, ) street_address = models.CharField( verbose_name=_("street address"), max_length=150, blank=True, ) city = models.CharField( verbose_name=_("city"), max_length=50, blank=True, ) I would like to leverage some fields that are provided by wagtail.users.models.UserProfile (as seen in https://github.com/wagtail/wagtail/blob/main/wagtail/users/models.py), like the avatar field, preferred_language field, etc for my own use. I know I can access those fields in my templates using user.wagtail_userprofile.avatar etc. What I'm looking to achieve, is to have a UserUpdateView that can update my User model, including some fields from wagtail.users.models.UserProfile into the same form, but I dont see how to do this. Regards!