Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
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__'