Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add multiple fields' reference to "unique_together" error message
I have a model with multiple fields being checked for uniqueness: class AudQuestionList(BaseTimeStampModel): aud_ques_list_id = models.AutoField(primary_key=True,... aud_ques_list_num = models.CharField(max_length=26,... aud_ques_list_doc_type = models.ForeignKey(DocType,... short_text = models.CharField(max_length=55,... aud_scope_standards = models.ForeignKey(ScopeStandard, ... aud_freqency = models.ForeignKey(AuditFrequency, ... aud_process = models.ForeignKey(AuditProcesses, ... unique_together = [['aud_scope_standards', 'aud_freqency', 'aud_process',],] My model form is as described below: class CreateAudQuestionListForm(forms.ModelForm): class Meta: model = AudQuestionList fields = ('aud_ques_list_doc_type', 'aud_scope_standards', 'aud_freqency', 'aud_process', 'short_text', ... def validate_unique(self): try: self.instance.validate_unique() except ValidationError: self._update_errors({'aud_scope_standards': _('Record exists for the combination of key values.')}) The scenario works perfectly well, only that the field names (labels) itself are missing from the message. Is there a way to add the field names to the message above, say something like: Record exists for the combination of key fields + %(field_labels)s. -
Docker-Compose Init Postgres Failing
I've been attempting to make a docker-compose file work, and so far it's been closer and closer, but not quite there. Maybe asking the questions will be useful to someone else in the future. Anyway, the previous thread was here: Docker-Compose Postgresql Init Entrypoint From which I learned, between runs a docker-compose file should have docker compose volumes --down and if the POSTGRES_DATABASE isn't specified, then the POSTGRES_NAME will replicate to the POSTGRES_DATABASE. another suggestion from Discord has been to rewrite some of the volume signature to include the file path to init.sql as in docker-entrypoint-initdb.d/init.sql So if I docker-compose down --volume and then sudo docker-compose build && docker-compose up with version: "3.9" services: db: restart: always image: postgres volumes: # - ./data/db:/var/lib/postgresql/data - ./init.sql:/docker-entrypoint-initdb.d/init.db environment: - POSTGRES_NAME=dev-postgres - POSTGRES_USER=pixel - POSTGRES_DATABASE=lightchan - POSTGRES_PASSWORD=stardust web: build: . restart: always command: sh -c "./waitfor.sh db:5432 -- python3 manage.py runserver" volumes: - .:/code ports: - "8001:8001" environment: - POSTGRES_NAME=dev-postgres - POSTGRES_USER=pixel - POSTGRES_DATABASE=lightchan - POSTGRES_PASSWORD=stardust depends_on: - db Then the following is output: Attaching to lightchan-db-1, lightchan-web-1 lightchan-db-1 | The files belonging to this database system will be owned by user "postgres". lightchan-db-1 | This user must also own the server process. … -
using .all() gives me everything inside the Primary Model How can i change it to gives what i needed
I have 2 models Album and Primary when i go to the Albums Templates and clicking the viewAlbum templates it's shows me every Students from every Album I have created, instead of showing the only students inside the album i have choosing during creating a new student. the create album template: <div class="row"> <div class="col-md-3"> <a href="{% url 'post_create' %}">Create Album</a> </div> <!--Albums--> {% for my_album in albums %} <div class="col-md-9"> <div class="card" style="width: 18rem;"> <img src="{{ my_album.image.url }}" alt="" class="card-img-top"> <div class="card-body"> <p>{{ my_album.name }}</p> <br> <a href="{% url 'view-Album' my_album.pk %}">viewAlbum</a> </div> </div> </div> {% endfor %} </div> </div> the viewAlbum view: def viewAlbum(request, pk): primaries = Primary.objects.all() post = get_object_or_404(Album, id=pk) my_album = Album.objects.get(id=pk) return render(request, 'viewAlbum.html', {'primaries': primaries, 'post':post, 'my_album':my_album}) the students templates: <div class="container"> <div class="row"> <div class="col"> <a href="{% url 'students' %}" class="btn btn-primary">Create Students</a> </div> </div> </div> <br> <div class="container"> <div class="row justify-content-center"> {% for prima in primaries %} <div class="col"> <div class="card my-2" style="width: 18rem;"> <img src="{{ prima.profilePicture.url }}" alt="" class="card-img-top"> <div class="card-body"> <p>{{ prima.firstName }}</p> <br> <a href="{% url 'view-Student' prima.pk %}">view Students</a> </div> </div> </div> </div> {% endfor %} </div> the models: class Album(models.Model): image = models.ImageField(null=False, blank=False) name = … -
Django local server not starting after hard reboot
I am a newbie developing a Django site in a pipenv virtual environment. The server has been starting and working with no problems. After my computer froze and I restarted with a hard reboot, I can't get the Django server to work. Here is the error I see after running, python manage.py runserver ((site1) ) userone@theusers-MBP site1 % python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/userone/.local/share/virtualenvs/site1-wGphEfbP/lib/python3.9/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection self.connect() File "/Users/userone/.local/share/virtualenvs/site1-wGphEfbP/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/Users/userone/.local/share/virtualenvs/site1-wGphEfbP/lib/python3.9/site-packages/django/db/backends/base/base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "/Users/userone/.local/share/virtualenvs/site1-wGphEfbP/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/Users/userone/.local/share/virtualenvs/site1-wGphEfbP/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 187, in get_new_connection connection = Database.connect(**conn_params) File "/Users/userone/.local/share/virtualenvs/site1-wGphEfbP/lib/python3.9/site-packages/psycopg2/__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: connection to server at "localhost" (::1), port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? The above exception was the direct cause of the following exception: Traceback (most recent call … -
Cannot Access Django Object After Creating it
I'm having difficulty running a function with the following code. It works when I run these lines individually in shell, but in the function 500s and I cannot access the object I just created. order = Order.objects.create( user=user, date_created=datetime.datetime.now(), ) print(order.id) #works fine and displays the new id print(Order.objects.get(id=order.id)) # 500s and cannot find the object -
Django Template Multi Image Carousel
I'm trying to create a Carousel that shows multiple pictures of a single cat for a cattery project I'm doing. I'm trying to figure out the right template to make this work. My Models class Cat(models.Model): name = models.CharField(max_length=32, null=True) available = models.BooleanField() main_image = models.ImageField(upload_to="images/") age = models.CharField(max_length=64, null=True) mix = models.CharField(max_length=128, null=True) dob = models.CharField(max_length=16) sex = models.CharField(max_length=16) description = models.TextField(max_length=256, null=True) def __str__(self): return f"{self.name} : {self.sex} {self.age} || Available : {self.available}" class Images(models.Model): name = models.CharField(max_length=64, null=True) image = models.ForeignKey(Cat, on_delete=models.CASCADE) def __str__(self): return self.name My View def available(request): context = {} return render(request, "cattery/available.html", {'available_kittens': Cat.objects.exclude(available=False).all()}) My HTML {% for kitten in available_kittens %} <div class="flexbox-item"> <img class="thumbnail" src="{{ kitten.images.url }}"> <h2> {{ kitten.name }} </h2> <hr> <h4> {{ kitten.sex }} </h4> <h6> {{ kitten.dob }} </h6> <p> {{ kitten.description}} </p> </div> {% endfor %} How can I call the images related to each kitten with a django Template? I know I could just include multiple image fields, but I've seen people suggest this method of creating a secondary class. -
Django object update using htmx and SingleObjectMixin
I'm using htmx for the first time. I have a table where each cell is a grade object. Previous to htmx I made each cell a link to an UpdateView for the object. I am now trying to have the user modify the the object's score field directly in the table using htmx. I'm sure I'm doing several things wrong. My page loads as expected and the table is displayed as expected. when I type in a cell, I get an error Forbidden 403. CSRF Verification Failed. The purpose of this post/question is to figure out how to get past this 403 error. Having said that, if it turns out that I'm going down the completely wrong path with using a SingleObjectMixin, please let me know. View class GradeChange(SingleObjectMixin, View): """ view to handle htmx grade change""" model = Grade def post(self, request, *args, **kwargs): grade = self.get_object() assessment = Assessment.objects.get(grade=grade.pk) print(assessment) classroom = Classroom.objects.get(classroom=grade.cblock) print(classroom) if grade.score == "EXT" or grade.score=="APP" or grade.score=="DEV" or grade.score=="BEG": grade.save() return HttpResponse("S") else: return HttpResponse("") template <table class="table table-bordered table-sm"> <thead> <tr> <th class="col-3" scope="col">Students</th> {% for obj in objective_list %} <th class="col-2" scope="col">{{ obj.objective_name }}</th> {% endfor %} <th scope="col">Comments</th> </tr> </thead> … -
How to get object from detailview in .views? Django
I've created a function that adds the user to an event, that is working fine but, i'm having problems with the one that removes the users from the event, I didn`t figure out how to get the attendant so that the owner can remove it. By now, I have this: views.py (Function that adds the user to the event) @login_required def request_event(request, pk): previous = request.META.get('HTTP_REFERER') try: post = Post.objects.get(pk=pk) Attending.objects.create(post=post, attendant=request.user) messages.success(request, f'Request sent!') return redirect(previous) except post.DoesNotExist: return redirect('/') (Function that removes users from the event, handled by the event owner) @login_required def remove_attendant(request, pk, attendance_id): previous = request.META.get('HTTP_REFERER') try: post = Post.objects.get(pk=pk) attendant = Attending.objects.get(id=attendance_id) Attending.objects.filter(post=post, attendant=attendant).delete() messages.success(request, f'User removed!') return redirect(previous) except post.DoesNotExist: return redirect('/') Urls.py path('post/(?P<pk>[0-9]+)/remove_attendant/(?P<attendance_id>[0-9]+)$', views.remove_attendant, name='remove-attendant'), Any help or comment will be very welcome! thank you!!! -
How test the presence of CSRF in an APIView (DRF)?
I have an API, with JSON as content-type, built with Django Rest Framework. There is an endpoint which permit login the users, for that I am using simple-jwt package, and how the view has permission_classes = [AllowAny] and works through POST method to make the login, so I added the CSRF token to this view: @method_decorator(csrf_protect, name='post') class TokenCookieObtainPairView(TokenObtainPairView): ... When the header and cookie that have the CSRF doesn't match, a template of django (views.csrf.csrf_failure) return a 403 status, but I overrided that (method finalize_response()) to return a message to the consumer. if response.status_code == status.HTTP_403_FORBIDDEN: serializer = MessageSerializer({'message': self.MESSAGE}) new_response = Response(serializer.data, status=status.HTTP_403_FORBIDDEN) return super().finalize_response(request, new_response, *args, **kwargs) I created a test for that view. I am using pytest and the DRF's APIClient. from pytest import mark, fixture @fixture def api_client_csrf() -> APIClient: return APIClient(ensure_csrf_checks=True) @mark.django_db def test_login_view_csrf(api_client_csrf): """Verify that the 'login' view need the CSRF_token.""" path = reverse_lazy('login') credentials = { 'email': 'xxx@yyyy.com', 'password': '******' } response = api_client_csrf.post(path, data=credentials) print(response.data) assert response.status_code == 403 The test failed because the CSRF token is not required and the credentials are invalid, hence pytest return: assert response.status_code == 403 E assert 401 == 403 E +401 E -403 The … -
Fail to access my Model fields in the views using /<int:pk>/ in the urls
I have a model called Primary and I want to access the fields of the models inside my viewStudent template, because i have more fields in the models. the model: class Primary(models.Model): profilePicture = models.ImageField(blank=False, null=False) firstName = models.CharField(max_length=25, blank=False, null=False) sureName = models.CharField(max_length=25, blank=False, null=False) lastName = models.CharField(max_length=25, blank=False, null=False) address = models.CharField(max_length=50, blank=False, null=False) classOf = models.CharField(max_length=20, blank=False, null=False) yearOfGraduations = models.CharField(max_length=20, blank=False, null=False) hobbies = models.TextField(blank=False, null=False) dateOfBirth = models.CharField(max_length=20) year = models.ForeignKey(Album, on_delete=models.CASCADE) when i type this inside my: viewAlbum template it's throws me an error like this: NoReverseMatch at /viewAlbum Reverse for 'view-Student' with arguments '('',)' not found. 1 pattern(s) tried: ['view/(?P[0-9]+)/\Z'] <a href="{% url 'view-Student' primaries.id %}">view Students</a> the urls.py path('viewAlbum', views.viewAlbum, name='view-Album'), path('view/<int:pk>/', views.viewStudent, name='view-Student'), the views: def viewAlbum(request): primaries = Primary.objects.all() return render(request, 'viewAlbum.html', {'primaries': primaries}) def viewStudent(request, pk): post = get_object_or_404(Primary, id=pk) primaries = Primary.objects.get(id=pk) return render(request, 'viewStudent.html', {'post': post, 'primaries': primaries}) inside my viewAlbum template i have tried this: <a href="{% url 'view-Student' primaries.pk %}">view Students</a> but it's not working how can I solves this problem? -
Widgets and static files
I'm trying to use a custom widget for plus and minus buttons and I struggle to link the widget to its css and js files. So in my app I got this form : class MyForm(forms.Form): degree = forms.DecimalField(label="Degree", max_digits=3, decimal_places=1, required=True, widget=PlusMinusNumberInput()) Calling this widget : class PlusMinusNumberInput(Widget): template_name = 'widgets/plus-minus-input.html' class Media: css = { 'all': ('css/plus-minus-input.css',) } js = ('js/plus-minus-input.js',) I got a "static" directory at the root, with my files in css and js folders. The static parts of my settings are as follow : STATIC_URL = '/static/' STATICFILES_DIRS = [Path.joinpath(BASE_DIR, 'static'),] STATIC_ROOT = Path.joinpath(BASE_DIR, 'staticfiles') At the end the html file render well but not the js and css. Do you know why ? -
How to drop tables using Django 2.2 migrations?
Im trying to drop unused tables from the database with a single migration. The models and the references was already removed from the code, but I can't get the migration to work. When I run the makemigration command I get something like this: class Migration(migrations.Migration) dependencies = [ ('hiring', '0040_last_migration'), ] operations = [ migrations.DeleteModel( name='Position', ), migrations.DeleteModel( name='ReviewProcess', ), migrations.DeleteModel( name='ReviewProcessType', ), ] But if i run this migration it makes nothing, also if i run the sqlmigrate command it shows only commented lines in the sql response: BEGIN; -- -- Delete model Position -- -- -- Delete model ReviewProcess -- -- -- Delete model ReviewProcessType -- COMMIT; -
How to make payments with stripe in a django and react app?
So, I am going to build an e-commerce site where the price will depend on how many days the person stays in a housing boat. I am planning to use material UI's date and time picker. So I want to be able to: 1) get the difference of the check in and check out dates in the front-end 2) then compute the total cost in the frontend 3) then make stripe (django backend) know about this total cost and charge accordingly I need help with (3). How do I send the price to the backend and have stripe know about this price? for example, here is some code: Django Backend: import django.conf import settings from rest_framework.views import APIView import stripe from django.shortcuts import redirect # This is your test secret API key. stripe.api_key = settings.STRIPE_SECRET_KEY class StripeCheckOutView(APIView): def post(self, request): try: checkout_session = stripe.checkout.Session.create( line_items=[ { # Provide the exact Price ID of the product you want to sell 'price': '{{PRICE_ID}}', 'quantity': 1, }, ], mode='payment', success_url=YOUR_DOMAIN + '?success=true', cancel_url=YOUR_DOMAIN + '?canceled=true', ) return redirect(checkout_session.url) except: return React Frontend: import "./App.css"; const ProductDisplay = () => ( <section> <div className="product"> <img src="https://i.imgur.com/EHyR2nP.png" alt="The cover of Stubborn Attachments" /> <div className="description"> … -
HELPS - I just ran "git reset --hard HEAD~50" not knowing it would revert all my files
I was trying to solve a problem I was having with Django and used the command "git reset --hard HEAD~50" not knowing it would revert all my files. I just lost a month of code. I'm looking for a fix right now but I wanted to post here instead of touching anything right now. It might be a simple fix but please help. -
Elastic Beanstalk Django project working but not listed in AWS console for Elastic Beanstalk
I followed this tutorial: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html The application is deployed perfectly. On the AWS console for Elastic Beanstalk however, nothing is listed under environments or applications. What could be causing the problem? -
When I try to send mail using Django EmailMultiAlternatives I get an error [closed]
Note: it's working in local host but not in after deploy. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST='smtp.gmail.com' EMAIL_PORT=587 EMAIL_HOST_USER='mymail@gmail.com' EMAIL_HOST_PASSWORD='mypassword' EMAIL_USE_TLS=True EMAIL_USE_SSL=False Error code: Exception Type: SMTPAuthenticationError at /homecontact Exception Value: (534, b'5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbt\n5.7.14 9_jo-fg-EeQ7zjo3vQOvaG6o9TtP_RLjSe1tciyNAxxgmWFHjN7rxYoZRUEAaofnmz2MG\n5.7.14 boEeJELbxm-aTrY4S4T2mbhUmSeSGbT2JNPVLXkfzYGpl5XO54L0gn1U8JGxEFuk>\n5.7.14 Please log in via your web browser and then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 r13-20020ac85c8d000000b002de72dbc987sm9921275qta.21 - gsmtp') -
Django add to watchlist, listings not showing
I am trying to work on a project and one of the features is that users who are signed in should be able to visit a Watchlist page, which should display all of the listings that a user has added to their watchlist. So far, I am redirected when 'add to watchlist' is clicked but it does not bring up the button of 'remove from watchlist' and also when it redirects me to the watchlist page (where i should view the users entire watchlist), it shows me 'No watchlist found.'. URLS.PY path("add_watchlist/<int:listing_id>/", views.add_watchlist, name="add_watchlist"), path("watchlist", views.watchlist, name="watchlist"), MODELS.PY class Watchlist(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) item = models.ManyToManyField(Auction) def __str__(self): return f"{self.user}'s watchlist" LAYOUT.HTML <li class="nav-item"> <a class="nav-link" href="{% url 'all_category' %}?category={{ category.name}}">Category</a> <li class="nav-item"> <a class="nav-link" href="{% url 'create_listing' %}">Sell</a> </li> <li class="nav-item"> {% if user.is_authenticated %} <a class="nav-link" href="{% url 'watchlist' %}">Watchlist</a> {% endif %} </li> </ul> VIEWS.PY @login_required def add_watchlist(request, listing_id): items = Auction.objects.get(pk=listing_id) watched = Watchlist.objects.filter(user=request.user, item=listing_id) if watched.exists(): watched.delete() messages.add_message(request, messages.ERROR, "Successfully deleted from your watchlist") return HttpResponseRedirect(reverse("watchlist")) else: watched, created = Watchlist.objects.get_or_create(user=request.user) watched.item.add(items) messages.add_message(request, messages.SUCCESS, "Successfully added to your watchlist") return redirect('index') @login_required def watchlist(request): watchlists = Watchlist.objects.all() context = {'watchlists':watchlists} return render(request, 'auctions/watchlist.html', context) … -
Django project cannot be accessed using IPV6 address
I am running my Django project on a ubuntu server. I have changed the allowed host in settings.py ALLOWED_HOSTS = ['my_IPV4', 'my_IPV6', 'localhost'] I allowed access to port 8000 by sudo ufw allow 8000. I run the server by python manage.py runserver 0.0.0.0:8000 however I can only access the IPV4 address but the IPV6 address on port 8000 is not reachable. My IPV6 address is active but port 8000 seems not working. Did I miss something on configuring IPV6? -
Using CreateView with 2 Models at the same time
I am learning django. I am attempting to create a website that logs a user's workout. The user will be able to make premade workouts. For each workout routine, there will be a workout name and it will consist of different exercises and the number of sets per exercise. In order to achieve this, I have created a custom through model so I can associate a number of sets to each exercise for that premade workout routine. The trouble I am having is that in order to create a workout routine I need to use the WorkoutRoutine model in order to create a WorkoutRoutine object. Then I also need to use SetAmount in order to assign an exercise associated with a number of sets to the WorkoutRoutine. Here is my models.py: from django.db import models from django.contrib.auth import get_user_model from django.core.validators import MaxValueValidator, MinValueValidator class WorkoutRoutine(models.Model): title = models.CharField(max_length=25) owner = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) exercise = models.ManyToManyField( 'Exercise', through='SetAmount', related_name='workoutRoutines' ) def __str__(self): return self.title class Exercise(models.Model): name = models.CharField(max_length=25) def __str__(self): return self.name class SetAmount(models.Model): workout_routine = models.ForeignKey( 'WorkoutRoutine', related_name='set_amounts', on_delete=models.CASCADE, null=True ) exercise = models.ForeignKey( 'Exercise', related_name='set_amounts', on_delete=models.SET_NULL, null=True, blank=True ) set_amount = models.IntegerField( default=0, validators=[ MaxValueValidator(100), … -
how to return last object which relates to anothe, QuerySet.annotate() received non-expression(s): 23 - django
I've two models : class ClientSeller(models.Model): name = models.CharField(max_length=40,unique=True) class Payment(models.Model): client_seller = models.ForeignKey(ClientSeller,on_delete=models.CASCADE,blank=True,related_name='client_seller') price = models.DecimalField(max_digits=20,decimal_places=3) i want to return last Payment's price field when i get an object from ClientSeller here is what i tried : def loaner_invoice(request,id): obj = ClientSeller.objects.annotate(last_pay=Payment.objects.filter( client_seller=id).values_list('price',flat=True).order_by('-pk')[0]).get(id=id) but it returns this error : QuerySet.annotate() received non-expression(s): 23.000. is there a way to achieve that please ?! thank you for helping .. -
Image not found after upload[django]
I will try to be as clear as possible. I put in production a site developed with Django. Hosting on planethoster. The configuration of statics and media is done. My big question is why when I upload an image, I get a 404 error when the image is present in the media files and the url is good. The images are displayed only after restarting the application. If someone has an idea or has already dealt with this behavior, I am all ears. thank you =) -
Django, Manage threads and websocket for a data visualisation website
I am a Django beginner and here is the project : I am building a data visualisation website. I am loading a continuous data stream and I want the client to be able to choose the data processing to apply (in python, IA treatments with tensorflow for example). Once the treatments are chosen by the client, I want to be able to launch them in a thread and send the results to the client every X seconds in a websocket (and be able to process websocket messages coming from the client at the same time). I have already done it with Flask but I don't succeed with django. I have followed many tutorials, in particular this one, which seem similar to I want to do : https://www.neerajbyte.com/post/how-to-implement-websocket-in-django-using-channels-and-stream-websocket-data The main issue is that I don't know how or even where create my thread. I can't do it in an AsyncWebsocketConsumer class, because it doesn't allow me to launch a thread which is able to send a Websocket request (I need to launch a async function to be able to send a request and I can't launch a async function in a thread). One solution proposed in the above tutorial to send … -
NOT NULL constrain failed when trying to POST data to Django API
I have a project with two apps; a React app for the front-end and Django for backend. I built my signup page in React and the signup process in Django. I would like to connect the two enabling a user to go through the signup page I created and for a user to be created based on the information submitted by the user. Here is my models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=100, blank=True) location = models.CharField(max_length=100, blank=True) password = models.CharField(max_length=32) email = models.EmailField(max_length=150) signup_confirmation = models.BooleanField(default=False) def __str__(self): return self.user.username @receiver(post_save, sender=User) def update_profile_signal(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() Serializers.py: class ProfileSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Profile fields = ('user_id', 'name', 'location', 'password', 'email', 'signup_confirmation') and the POST function in React const onSubmit = e => { e.preventDefault(); const user = { email: email, name: name, location: 'Example', password: password, user_id: 1, }; console.log(user); fetch('http://127.0.0.1:8000/api/v1/users/profiles/?format=api', { method: 'POST', headers: { 'Content-Type':'application/json' }, body: JSON.stringify(user) }) .then(res => res.json()) .then(data => { if (data.key) { localStorage.clear(); localStorage.setItem('token',data.key); window.location.replace('http://localhost:3000/profile/'); } else { setEmail(''); setName(''); setPassword(''); localStorage.clear(); setErrors(true); } }); }; Problem is when I try to create a user; I get this error message in Django … -
Django app running fine on localhost, but not working on elastic beanstalk 500 internal errors
I have a django app, and it works fine on localhost (no problems). It loads a json file into a data structure (Trie), and is being used in a single route. It takes about 2-3 seconds for the file to be read, and build the Trie (there are thousands of words in my list). All of this is fine localhost as it only takes 2-3 seconds a single time (when you start the server). Then when you call a route on the front end with a POST to the route it performs the search on the Trie and returns the results (OK). Everything works fine localhost. However whenever I try this same exact approach on AWS Elastic Beanstalk, it returns 500 Internal Server Error on every route (routes that don't use this Trie are also throwing this exact same error code). So I am going to show some relevant code as to how I load the file, and how it is used in the app. module_dir = os.path.dirname(__file__) file_path = os.path.join(module_dir, 'trie.json') myTrie = Trie() myTrie.load(file_path)#Loads the trie from a json file that is just a list(array) ... ... #in search view post route return Response(myTrie.search(word)) #note word is part … -
Wagtail add RawHTMLBlock to field in model
I'm trying to add field type as RawHTMLBlock in my model I did from wagtail.images.blocks import ImageChooserBlock from wagtail.core import blocks from wagtail.core.fields import RichTextField, StreamField from wagtail.admin.edit_handlers import FieldPanel, InlinePanel, MultiFieldPanel, StreamFieldPanel, FieldRowPanel, PageChooserPanel from modelcluster.fields import ParentalKey from wagtail.images.models import Image from wagtail.images.edit_handlers import ImageChooserPanel from wagtail.images.widgets import AdminImageChooser @register_snippet class DefaultHeader(models.Model): title_html = models.CharField(max_length=100, null=True, blank=True) text_message = RichTextField(null=True, blank=True) code_text = blocks.RawHTMLBlock(null=True, blank=True) background = models.ForeignKey('wagtailimages.Image', related_name='+', null=True, blank=True, verbose_name=_("Background"), on_delete=models.SET_NULL) panels = [ FieldPanel("title_html"), FieldPanel("text_message"), FieldPanel("code_text"), ImageChooserPanel("background", classname="col12"), ] All fields was add after makemigrations except for code_text that field wasn't add in my admin page I have title_html; text_message; background. but not code_text