Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Why does Django ignore DATABASE_ROUTERS
I followed the documentation to add a DatabaseRouter to Django. While it looks straight forward, it's not working for me. And when I try to put bogus data to see if django will cough, it looks like it's ignoring it completely. in settings.py DATABASE_ROUTERS = [ "api.db_routers.ReadWriteSegregatedDBRouter", "this.is.an.invalid.path" ] It did not load my router (ReadWriteSegregatedDBRouter) and after adding the invalid path, I never got an error, which tells me django isn't using this (DATABASE_ROUTERS) setting. Is there some other configuration I am missing? Django version 3.1.5 -
Django Rest Framework - Annotate duplicates values
I encounter a really weird bug. When annotating 3 values (AVG, COUNT and SUM) I notice that COUNT and SUM are multiplying each other. For instance: The duration should be half the time and there are only 2 ratings (number_of_ratings - COUNT, album_duration - SUM). I have these annotations in queryset in ViewSet class class AlbumViewSet(ModelViewSet): queryset = Album.objects \ .prefetch_related("tracks", "album_genres", "album_genres__genre_id", "album_links", "reviews") \ .select_related("aoty", "artist_id") \ .annotate(overall_score=Avg("reviews__rating", output_field=IntegerField()), number_of_ratings=Count("reviews__rating", output_field=IntegerField()), album_duration=Sum("tracks__duration", output_field=DurationField())) Here are other files models.py class Album(models.Model): RELEASE_TYPE_ALBUM_CHOICES = [ ("LP", "LP"), ("EP", "EP"), ("Single", "Single"), ("Live", "Live"), ] title = models.CharField(max_length=255) slug = models.SlugField(max_length=255) release_date = models.DateField() artist_id = models.ForeignKey( Artist, on_delete=models.PROTECT, related_name="albums" ) art_cover = ResizedImageField( size=[750, 750], null=True, blank=True, upload_to=rename_album_art_cover) release_type = models.CharField(max_length=10, choices=RELEASE_TYPE_ALBUM_CHOICES, default="LP") created_at = models.DateTimeField(auto_now_add=True) class Track(models.Model): title = models.CharField(max_length=255) position = models.PositiveIntegerField() album_id = models.ForeignKey( Album, on_delete=models.PROTECT, related_name="tracks") duration = models.DurationField(null=True) class Review(models.Model): reviewer_id = models.ForeignKey(Reviewer, on_delete=models.PROTECT) rating = models.IntegerField( validators=[MaxValueValidator(100), MinValueValidator(0)] ) review_text = models.TextField(null=True, blank=True) album_id = models.ForeignKey( Album, on_delete=models.PROTECT, related_name="reviews") created_at = models.DateTimeField(auto_now_add=True) serializer.py class AlbumSerializer(serializers.ModelSerializer): tracks = TrackSerializer(many=True) genres = StringRelatedField( source="album_genres", many=True) aoty = StringRelatedField(read_only=True) links = AlbumLinkSerializer( source="album_links", many=True, read_only=True) artist = SimpleArtistSerializer(source="artist_id", read_only=True) overall_score = serializers.IntegerField(read_only=True) number_of_ratings = serializers.IntegerField(read_only=True) album_duration = … -
Docker-Compose Postgresql Init Entrypoint
I'm attempting to create a Dockerfile that will use a init.sql file to populate a database. However, it doesn't work and from the other answers on this site and elsewhere I don't see the solution. It's simple, so it must be something dumb. The backend is written in Python/Django. Here's the Dockerfile - version: "3.9" services: db: restart: always image: postgres volumes: - ./init.sql:/docker-entrypoint-initdb.d - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_NAME=dev-postgres - POSTGRES_USER=pixel - 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_PASSWORD=stardust depends_on: - db And here's the init.sql file in the docker-entrypoint-initdb.d directory: CREATE DATABASE lightchan; One table to make this as simple as possible. Here's the output of sudo docker-compose build && docker-compose up: sudo docker-compose build && docker-compose up Password: [+] Building 3.3s (15/15) FINISHED => [internal] load build definition from Dockerfile 0.0s => => transferring dockerfile: 32B 0.0s => [internal] load .dockerignore 0.0s => => transferring context: 2B 0.0s => [internal] load metadata for docker.io/library/python:3.8-alpine 0.6s => [ 1/10] FROM docker.io/library/python:3.8-alpine@sha256:97aa60a6e663a7751eed676e880d51ab351a6d310c9 0.0s => [internal] load build context 1.0s => => transferring context: 18.01MB 1.0s => CACHED [ 2/10] … -
Django - Variables in HTML Templates
I'm trying to pull the following variable into a Template <p>Hello, {{request.user.person.first_name}} {{request.user.person.last_name}} | <small>{{request.user.last_login}}</small> </p> person is connected to user in as a one to one field in the models. first_name and last_name fields belong to the person table. This doesn't generate anything. Only user.last_login gets displayed, as last_login belongs to the user table Any ideas on how to do this? The html code above resides in the base.html template, and it would be a pain to have to pass some kind of variable into all child templates that extend the base.html template -
Choices not showing in form, but works in Django Admin
For some reason, I can't see the choices on a select field when I render a Django form in a template, but I can see both choices when looking at the model in Django admin, can someone please help me figure this one out. Models.py class IntervalChoices(models.TextChoices): WEEKLY = "WK", _('Veckovis') DAILY = "DL", _('Dagligen') class NewsEmail(models.Model): interval = CharField(max_length=2, choices=IntervalChoices.choices, default=IntervalChoices.WEEKLY, verbose_name='Intervall') Forms.py class NewsEmailForm(forms.ModelForm): class Meta: model = NewsEmail fields = ('province', 'municipality', 'areas', 'interval', 'ad_type') View.py def get(self, request): form = NewsEmailForm(instance=NewsEmail_obj) return render( request, 'core/profile/profile.html', { 'form': form, } ) Template.html <form> <div class="form-group col-lg-2 mb-0"> {{ form.interval|as_crispy_field }} </div> </form> Right now I'm only seeing the "daily" option in my template.html - but as I said I can see both options in Django admin. I've tried debugging with the following: Printing out the form in the view.py, after I've passed it the NewsEmail object - then I only seem to have one of the choices (the one that shows up in my template.html) form = NewsEmailForm(instance=NewsEmail_obj) pprint(vars(form.fields['interval'])) {'_choices': [('DL', 'Dagligen')], I've also tried printing out the form, BEFORE passing the object, and then I have both choices? pprint(vars(NewsEmailForm.base_fields['interval'])) {'_choices': [('WK', 'Veckovis'), ('DL', 'Dagligen')], I also … -
Django: Model with managed = False automatically includes id in return query
I have a queryset based on a Model that has managed = False in the meta, and django is automatically adding an id field to the queryset even when not included in the .values() list. class GenerateTimeSeriesOuterModel(models.Model): class Meta: db_table = 'GenerateTimeSeriesOuterModel' app_label = 'GenerateTimeSeriesOuterModel' managed = False # Used by TableSubquery(BaseTable): class in Subquery.py to generate 'from (subquery)' subquery = None objects = SubqueryManager() The model has the managed flag set to False, and uses a custom manager. When I try to do something like this: GenerateTimeSeriesOuterModel.objects.all().set_subquery(some_subquery).annotate( 'foo_bar': F('foo_bar') ).values('foo_bar') This returns the following query: select subquery.id, subquery.foo_bar from ( select something as foo_bar from some_table ) as subquery as you can see id is added automatically but does not exist from the subquery so it throws an error. Any thoughts on removing the id? -
Python Django: Get what input field the cursor is in?
I am relatively new to Django and don’t have a lot of experience with python. So far I display some input fields this way, where I'm looping through a range and then making the equivalent amount of fields. But is there some way to know which field is active, like what field is the cursor in? The reason for why I want to know what field is active is because I have created a list with a bunch of special symbols, like math symbols and Greek letters, which the user can click, I then want the active field to display the clicked symbol. hope it makes sense I was made aware of something called focus but I don’t think I understand how to use it. If someone could explain it would be great This is the "important" part of my .html file {% with ''|center:number_of_variables as range %} {% for i in range %} <input type="text" name="know_variable_description{{ forloop.counter0}}" placeholder="Symbol" > <input type="text" name="know_variable_symbol{{ forloop.counter0}}" placeholder="Name" > {{ forloop.counter0}} {% endfor %} {% endwith %} -
Django Rest Framework Cors issues with query params
When I make a GET request without queryparams my backend provides the data no problem, but if I pass any queryparams the request gets rejected. [Example of Rejection in network tab, status column says CORS ERROR][1] The fetch being made is this (it's within a react useEffect) fetch('http://localhost:8000/gems/' + new URLSearchParams({ filters: 'all' })) If I remove the + params it works just fine, but removing the trailing slash also causes the issue. in package.json I have added this "proxy": "https://localhost:8000/", The backend view is this (going to overwrite get_queryset to read the params) class GemViewSet(viewsets.ModelViewSet): queryset = Gem.objects.all() serializer_class = GemSerializer and I've installed the cors app, added the middleware and set CORS_ALLOW_ALL_ORIGINS = True If someone could set me on the right track I'd be very grateful. [1]: https://i.stack.imgur.com/g0dIp.png -
Specify Foreign Key field to be excluded in ModelSerializer
First Let me tell you the problem and my solution. I have a model named ProfileInfo, which inherits from abstract models PersonInfo and CompanyInfo. Each of these abstract models has their own serializers (ModelSerializer), pointing to ProfileInfo model. So assume they are company fields that are excluded from PersonInfoSerializer and vice versa. I added a read_only field is_filled which indicates whether the profile info is completed or not: class PersonInfoSerializer(serializers.ModelSerializer): user = serializers.SerializerMethodField() is_filled = serializers.SerializerMethodField(allow_null=True) class Meta: model = ProfileInfo exclude = [ "company_name", "company_tax_file", ] def get_is_filled(self, obj): data = obj.__dict__ fields = data.keys() - set(self.Meta.exclude) is_filled = True for field in fields: if data[field] is None: is_filled = False break return is_filled The error I get says: AssertionError: The field 'company_tax_file_id' was included on serializer PersonInfoSerializer in the 'exclude' option, but does not match any model field. Note that company_tax_file is a FK relation field in CompanyInfo and I wanna be excluded. How would you write the method get_is_filled? -
The best programming language and frameworsk for a image sharing website [closed]
We are two students who are going to make a image sharing website with image functionality like ROI(Region of interest). The idea is about easy access to medical imgages. E.g a doctor need to send a mediacal image with a ROI to a other doctor. We are both unsure what programming language and framework we shall use. We both are used with PHP with MySQL, but we acknowledge that a framework with Django is more suitable since it combines Python with HTML, CSS and Javascript. The upside is also libary's Python have that might be to use for us. We are curious about the community opinions and idea about this. Thanks for your time. Nicholai -
Django BASE_DIR give different path in different views
views.py def download(request, path): print(settings.BASE_DIR) file_path = os.path.join(settings.BASE_DIR, path) if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/octet/stream") response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) return response raise Http404 def profile(request, username): print(settings.BASE_DIR) .... Here in profile view settings.BASE_DIR is giving correct path (D:\MiniProject\django-project\ProjectBlog) which is set in the settings.py file, but in download.py its giving wrong path (Profile/download/). Why is this duelity? -
custom permission for user owned objects not working ( django rest framework)
Creating a custom permission to ensure only the user who owns an instance of the user object can update it like so class UserUpdatePermission(BasePermission): message = 'only users can edit their profile' def has_permission(self, request, view): return request.user.is_authenticated def has_object_permission(self, request, view, obj): if request.method in SAFE_METHODS: return True request.user == User.objects.get(username=view.kwargs['username']) @api_view(['POST']) @permission_classes([UserUpdatePermission]) @parser_classes([FormParser, MultiPartParser]) def UpdateUserProfile(request, username): user = User.objects.get(username=username) serializer = UpdateUserSerializer(instance=user, data=request.data) if serializer.is_valid(raise_exception=True): serializer.save() return Response(serializer.data) From inserting print statements around the code, i noticed the has_permission function in the class is being called but not the has_object_permission function. So, the object level permission isn't working. What am i getting wrong here? -
Unable to append to list
if sample_collected == 'true': b_id = list(Booking.objects.filter(center__isnull=False,org_type='homedx').values_list('id', flat=True)) for booki_id in b_id: print("Booking ID", booki_id) if booki_id in list(ReceivedPackageTubes.objects.values_list('booking_id', flat=True)): packages = list(Booking.objects.filter(id=booki_id).values_list('packages__name', flat=True)) print("Packages", packages) count_tube = [] for i in packages: pt = package_models.PackageTubes.objects.filter(package__name=i).values_list('tubequantity__tube__name', flat=True).count() count_tube.append(pt) total_tubes = sum(count_tube) print("Total Tubes", total_tubes) collected = list(ReceivedPackageTubes.objects.filter(booking_id=booki_id).values_list('booking_id', flat=True)) print("Collected", collected) collected_ids = [] if len(collected) == total_tubes: collected_ids.append(booki_id) print("Collected ID", collected_ids) In the last line if len(collected) == total_tubes. I am trying to append **collected_id**. in collected_ids = []. Every time it is appending one. I know I need to use for loop but I am unable to do that. Can somebody help. I am learning Python and Django. Thank you !! -
Router not affecting database migrations
I am attempting to use two databases (one for auth models and one for custom models) by following Django docs: Multiple databases, but when I migrate, everything goes to both databases, auth_db and default. I would like to use a router to differentiate between the two, but I followed the docs nearly exactly and did not get the intended results. settings.py INSTALLED_APPS = [ 'api', 'api.authentication', 'api.dictionary', 'api.pdf', 'corsheaders', 'django.contrib.admin', 'django.contrib.admindocs', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django_smtp_ssl', 'rest_framework', 'rest_framework_simplejwt', 'rest_framework_simplejwt.token_blacklist', ] # ... """ Constants below are defined by retrieval w/ os.environ[] in a try/except KeyError block. """ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': DEFAULT_DATABASE_NAME, 'USER': DEFAULT_DATABASE_USER, 'PASSWORD': DEFAULT_DATABASE_PASSWORD, 'HOST': '', 'PORT': '', 'TEST': { 'DEPENDENCIES': ['admin_db'], }, }, 'admin_db': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': ADMIN_DATABASE_NAME, 'USER': ADMIN_DATABASE_USER, 'PASSWORD': ADMIN_DATABASE_PASSWORD, 'HOST': '', 'PORT': '', 'TEST': { 'DEPENDENCIES': [], }, }, } DATABASE_ROUTERS = ['api.authentication.routers.AdminDBRouter'] api/authentication/routers.py class AdminDBRouter: """ A router to control all database operations on models in the authentication application, all and any dependent applications, and Django administrative applications. """ ROUTE_APP_LABELS = { 'admin', 'auth', 'authentication', 'contenttypes', 'sessions', 'sites', 'token_blacklist', } def db_for_read(self, model, **hints): """ Attempts to read models defined in any app in 'self.ROUTE_APP_LABELS' go … -
Fetch API doesn't populate div
I'm a beginner in JavaScript and learning the fetch API. I'm facing difficulties in creating new divs populated with data from the fetch api... any problems? I want the fetch api to run as soon as the page is loaded. JavaScript Code -
Serializer has no attribute 'data'
i am using django rest framework, but if i want to return result from serializer.data I get this error: return Response(serializer.data) AttributeError: 'tuple' object has no attribute 'data' my code is: @api_view(['GET','POST']) def rest(request): if request.method == 'GET': c = C_emploi.objects.all() serializer = C_emploiSerializer(c, many=True), return Response(serializer.data) my serializer : class C_emploiSerializer(serializers.ModelSerializer): class Meta: model = C_emploi fields = '__all__' -
Response time exceeded
I have a problem with a django application. When making a request to an RFC, the response from SAP takes 3 minutes. Time in which the connection from the apache server is cut and it does not allow displaying the data on my website. Timeout 600 KeepAlive On MaxKeepAliveRequests 100 KeepAliveTimeout 600 <VirtualHost *:80> Timeout 600 ProxyTimeout 600 RewriteEngine on RewriteCond %{HTTPS} !=on RewriteRule ^/?(.*)$ https://%{SERVER_NAME}/$1 [R,L] <VirtualHost *:443> Timeout 600 ProxyTimeout 600 ProxyPreserveHost On SSLProxyEngine on # The order is important here ProxyPass /static ! -
You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field
I'm trying to setup the lookup field between two entities, but I can't fix this error. I've already tried these solutions but none of them worked for me(What am I doing wrong?): Django Rest Framework, improperly configured lookup field Django Rest Framework - Could not resolve URL for hyperlinked relationship using view name "user-detail" DRF Could not resolve URL for hyperlinked relationship using view name on PrimaryKeyRelatedField here's my code Models: class Category(models.Model): title = models.CharField(max_length=50, unique=True) slug = models.SlugField(max_length=80, default='') def __str__(self): return self.title class Option(models.Model): title = models.CharField(max_length=80) slug = models.SlugField(max_length=80, unique=True) description = models.CharField(max_length=250) price = models.DecimalField(max_digits=7, decimal_places=2) category = models.ForeignKey(Category, related_name='options', on_delete=models.CASCADE) photo = models.ImageField(upload_to='options', null=True) class Meta: ordering = ['title'] def __str__(self): return self.title Serializers: class CategorySerializer(serializers.HyperlinkedModelSerializer): options = serializers.HyperlinkedRelatedField(many=True, view_name='option-detail', read_only=True) class Meta: model = Category fields = ('url', 'slug', 'title', 'options') lookup_field = 'slug' extra_kwargs = { 'url': {'lookup_field': 'slug'} } class OptionSerializer(serializers.HyperlinkedModelSerializer): category = serializers.ReadOnlyField(source='category.title') class Meta: model = Option fields = ('url', 'slug', 'title', 'description', 'price', 'category') lookup_field = 'slug' extra_kwargs = { 'url': {'lookup_field': 'slug'}, 'category': {'lookup_field': 'slug'} } Views: class CategoryViewSet(viewsets.ReadOnlyModelViewSet): """ Returns the Category list or the requested one """ queryset = Category.objects.all() serializer_class = CategorySerializer lookup_field = … -
Unexpected token < in JSON when using fetch()
I am trying to connect my React signup page to my Django API so when a user signs up a user profile is created in Django. I get this error on my console when I try to create a new user: Signup.js:33 POST http://127.0.0.1:8000/api/v1/users/profiles/?format=api 400 (Bad Request) onSubmit @ Signup.js:33 callCallback @ react-dom.development.js:188 invokeGuardedCallbackDev @ react-dom.development.js:237 VM1121:5 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 4 This is what I see in network inspector: POST /api/v1/users/profiles/?format=api HTTP 400 Bad Request Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "detail": "JSON parse error - Expecting value: line 1 column 2 (char 1)" } This is the code I have on signup.js: 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); } }); }; and in settings.py: CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_METHODS = [ "DELETE", "GET", "OPTIONS", "PATCH", "POST", "PUT", ] I assume I am using the right endpoint. When … -
Django 4.0 - Trying to run a query based on result from another query
guys! What I'm trying to do: I have a User model, a LinkedOrganization model, an Organization model that looks like this: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(db_index=True, unique=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) mobile = models.CharField(max_length=12) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name', 'mobile'] class Meta: verbose_name = 'User' verbose_name_plural = 'Users' # Organization fields class Organization(models.Model): organization_name = models.CharField(max_length=50, unique=True) def __str__(self): return self.organization_name class LinkedOrganization(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='linked_user') organization = models.ForeignKey(Organization, on_delete=models.CASCADE, related_name='linked_organization') is_manager = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) class Meta: unique_together = ( ("user", "organization") ) In my API-view I'm trying to return all the users that are linked to an organization that the requester is a manager of. Now, one requester can be a manager of 1 or more organizations, and I need to get all the users linked to those organizations. Meaning I need it to be sort of 'is member of organization A' OR 'is member of organization B', and iterate through all the organizations. Is it possible to do this with a Queryset in Django? I realized when I wrote this that I could just get the organizations …