Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ProcFile declares types -> (none) ProcFile
I want to host Django server over heroku and my procfile looks like this web: gunicorn DjangoHerokuApp.Portfoliowebapp.wsgi and this my file structure both procfile and requirements.txt are in root folder enter image description here and it is giving me this error continously Procfile declares types -> (none) and this my requirements.txt asgiref==3.4.1 Django==4.0 gunicorn==20.1.0 sqlparse==0.4.2 tzdata==2021.5 Please Help ! I am stuck at this for 2 days -
How to post an image in django server using tiny mce editor? Note: I have integrated the tiny mce editor in a simple html page
I have designed a simple html webpage. Where I've integrated tinymce editor. Someone gave me a uri, Where I need to post an image from tinymce editor to django server by using a uri.In response the server will return a url. That url I need to show in success message. How to do that? -
How does payment work while shopping on a webpage with Django?
I am creating a shopping web app and I'm wondering how does it work? How do I connect my page to the credit card and how does it take money from it? How to implement it in Django? Where to send the money that was taken from the credit card itself? You can probably understand now what I need. Thanks in advance. -
Django-summernote not showing images in editor (404 error)
I'm try create post and add to this post images. And i'm use for this Django-summernote in Django 3.0. Picture upload to folder on hard disk, but not showing in editor. Console show 404 Error. Please, give me advice how to fix it? Thank you! settings.py STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' ADMIN_MEDIA_PREFIX = STATIC_URL + "grappelli/" X_FRAME_OPTIONS = 'SAMEORIGIN' SUMMERNOTE_THEME = 'bs4' # Show summernote with Bootstrap4 #MEDIA_ROOT = os.path.join(BASE_DIR, 'blog/media/') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' urls.py urlpatterns = [ path('admin/filebrowser/', site.urls), path('summernote/', include('django_summernote.urls')), path('admin/', admin.site.urls), path('', include('blog.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) image = models.ImageField(upload_to="", blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def get_absolute_url(self): return "/api/article/%i/" % self.id def __str__(self): return self.title screenshot from console -
Combining DetailView and CreateView in Django 3.2/4.0, as explained in the docs
I'm building a generic blog and trying to enable users to make comments directly on the article page. I am trying to implement this by combining DetailView with CreateView. The docs present 3 different solutions to this issue: FormMixin + DetailView: this is the answer that Django docs advise against, but that is advised by most answers on SO that I could find DetailView only + write the post method: "a better solution" according to Django docs DetailView + FormView: "an alternative better solution", and the one I'm trying to implement. The "alternative better" solution consists in making a DetailView for articles and a FormView for comments, but the docs state that "This approach can also be used with any other generic class-based views", which means that DetailView + CreateView should be possible. I've gone through a number of SO items that reference this solution, but I am unable to implement any of them. This SO question suggests mixing DetailView and CreateView. However, the explanation in that answer is incomplete. Another SO question, among advice to use FormMixins, has this answer that is close, but different. Other questions (1, 2, etc.) only address the FormMixin and DetailView + post methods. … -
How to divide [filtered list by date(from_date, to_date)] by day. Django
i want to display information about likes. I filtered a model (from_date, to_date) and got list of all likes during this time. Now I need to sort and divide it somehow to make it looks something like this: [ { date: 2021-12-10, likes:[ { user: user1, post: post1 }, { user: user1, post: post1 } ] }, { date: 2021-12-11, likes:[ { user: user1, post: post1 }, ] } ] Could you please give me some advices how it is possible to do. models.py class LikesActivity(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.post} liked by {self.user}, {self.created}" class Meta: verbose_name = 'Likes activity' verbose_name_plural = 'Likes activities' views.py class LikesActivityRangeFilter(APIView): def get(self, request, from_year, from_month, from_day, to_year, to_month, to_day): from_date = f"{from_year}-{from_month}-{from_day}" to_date = f"{to_year}-{to_month}-{to_day}" likes = LikesActivity.objects.filter( created__range=[from_date, to_date]).order_by('created') serializer = LikesActivitySerializer(likes, many=True) return Response(serializer.data) -
ModuleNotFoundError: No module named 'ithogwarts.users' in Django
I am trying to create an extend User model but when I start the server I get a ModuleNotFoundError: No module named 'ithogwarts.users'. Here is a structure of the project: │ db.sqlite3 │ manage.py │ ├───ithogwarts │ │ asgi.py │ │ settings.py │ │ urls.py │ │ wsgi.py │ │ __init__.py │ │ │ └───__pycache__ │ ├───main │ │ admin.py │ │ apps.py │ │ models.py │ │ tests.py │ │ urls.py │ │ views.py │ │ __init__.py │ │ │ ├───migrations │ │ │ __init__.py │ │ │ │ │ └───__pycache__ │ │ │ ├───static │ │ └───main │ │ ├───css │ │ │ footer.css │ │ │ header.css │ │ │ index.css │ │ │ │ │ ├───img │ │ │ │ │ └───js │ │ script.js │ │ │ ├───templates │ │ └───main │ │ index.html │ │ layout.html │ │ level_magic.html │ │ │ └───__pycache__ │ ├───templates │ └───registration └───users │ admin.py │ apps.py │ forms.py │ models.py │ tests.py │ urls.py │ utils.py │ views.py │ __init__.py │ ├───migrations │ │ 0001_initial.py │ │ __init__.py │ │ │ └───__pycache__ │ ├───static │ └───users │ └───css │ login.css │ register.css │ ├───templates │ └───users │ login.html … -
value error. model field must be an instance django
I want to save a list of the relational objects using IDs but unfortunately, I'm getting an error from Django which I attached below. error: Cannot assign "[<Tag: Tag object (189)>, <Tag: Tag object (190)>]": "PackageRoom.tag" must be a "Tag" instance. models.py class Tag(models.Model): name = models.CharField(max_length=255, default='') description = models.CharField(max_length=255, default='') singleline = models.ManyToManyField(Singleline) class Meta: db_table = 'tags' class PackageRoom(models.Model): name = models.CharField(max_length=255, default='') tag = models.ForeignKey(Tag, on_delete=models.PROTECT) class Meta: db_table = 'package_rooms' serializers.py class PackageRoomSerializer(serializers.ModelSerializer): tag = serializers.PrimaryKeyRelatedField(queryset=Tag.objects.all(), many=True) class Meta: model = PackageRoom fields = ['id', 'name', 'description', 'tag'] views.py serializer = PackageRoomSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() JSON object which is sent from Frontend: { "name": "example room", "description": "lorem lipsum", "tag": [189, 190] } -
How to resolve this error code below, RelatedObjectDoesNotExist
class Following(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='following', unique=False, verbose_name=('User'), on_delete=models.CASCADE) following_user = models.ManyToManyField(settings.AUTH_USER_MODEL, verbose_name=('Following'), related_name='following_user') created_on = models.DateTimeField(default=timezone.now) class FollowingSerializer(serializers.ModelSerializer): new_following = serializers.PrimaryKeyRelatedField(queryset=User.objects.all(),required=True,write_only=True) class Meta: model = Following fields = [ 'id', 'user', 'following_user', 'new_following', 'created_on' ] read_only_fields = ['following_user'] def create(self, validated_data): user = validated_data['user'] new_following = validated_data['new_following'] user.following.following_user.add(new_following) new_following.followers.following_user.add(user) return user.following class FollowingAPIView(mixins.CreateModelMixin, mixins.DestroyModelMixin,generics.GenericAPIView): permission_classes = [permissions.IsAuthenticated] serializer_class = FollowingSerializer def get_queryset(self): queryset = Following.objects.all() return queryset def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) def delete(self, request, *args, **kwargs): return self.destroy(self, request, *args, **kwargs) This is the full error message. RelatedObjectDoesNotExist at /api/following/ User has no following. Request Method: POST Request URL: http://127.0.0.1:8000/api/following/ Django Version: 3.2.7 Exception Type: RelatedObjectDoesNotExist Exception Value: User has no following. Exception Location: C:\Users\user\Desktop\myhallel-project\venv\lib\site-packages\django\db\models\fields\related_descriptors.py, line 421, in get Python Executable: C:\Users\user\Desktop\myhallel-project\venv\Scripts\python.exe Python Version: 3.9.6 Python Path: ['C:\Users\user\Desktop\myhallel-project\myhallel', 'C:\Users\user\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\Users\user\AppData\Local\Programs\Python\Python39\DLLs', 'C:\Users\user\AppData\Local\Programs\Python\Python39\lib', 'C:\Users\user\AppData\Local\Programs\Python\Python39', 'C:\Users\user\Desktop\myhallel-project\venv', 'C:\Users\user\Desktop\myhallel-project\venv\lib\site-packages'] -
django_heroku.settings(locals()) KeyError: 'MIDDLEWARE' and 'MIDDLEWARE_CLASSES'
settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ALLOWED_HOSTS = ['my-app.herokuapp.com', '127.0.0.1:8000', 'localhost'] django_heroku.settings(locals()) STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'build/assets') ] error (2 exceptions) remote: Traceback (most recent call last): remote: File "/app/.heroku/python/lib/python3.9/site-packages/django_heroku/core.py", line 97, in settings remote: config['MIDDLEWARE_CLASSES'] = tuple(['whitenoise.middleware.WhiteNoiseMiddleware'] + list(config['MIDDLEWARE_CLASSES'])) remote: KeyError: 'MIDDLEWARE_CLASSES' remote: django_heroku.settings(locals()) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django_heroku/core.py", line 99, in settings remote: config['MIDDLEWARE'] = tuple(['whitenoise.middleware.WhiteNoiseMiddleware'] + list(config['MIDDLEWARE'])) remote: KeyError: 'MIDDLEWARE' I am trying to deploy my web app but I am getting this error everytime, cannot find a solution anywhere... nothing wrong with the Procfile, requirements.txt and runtime.txt, any help is appreciated! -
Creating Multible IDs for multible Buttons in one <Input> Tag
I'm working on a TicTacToe game using Django/Djangotemplates, Python and a bit Javascript. I've come across a problem tho. i only have one Button which is for-looped 9 times. its ID is its index. Now I'm not certain how to add the {{index}} which i defined in the for loop in the javascript onclick function. here the html template <div class="grid-container"> {% for index in object.board %} <div class="grid-item"> <input onclick="change(button.id)" class="buttonsize btn-outline-purple" type="submit" value="" name="button" id="{{index}}"> </div> {% endfor %} </div> </div> </article> </form> <script> function change(inputid){ console.log("test") var elem = document.getElementById(inputid); if (elem.value=="") elem.value = "X" } </script> here the models.py class TicTacToe(models.Model): player1 = models.ForeignKey(User, on_delete=models.CASCADE, default="X", related_name="tictactoe_as_player1") player2 = models.ForeignKey(User, on_delete=models.CASCADE, default="O", related_name="tictactoe_as_player2") current_player = models.ForeignKey(User, on_delete=models.CASCADE, related_name="tictactoe_current_player") title = models.CharField(max_length=100) board = models.CharField(max_length=9, default="012345678") def __str__(self): return self.title def get_absolute_url(self): return reverse('tictactoe-detail', kwargs={'pk': self.pk}) and here the views.py class TicTacToeCreateView(LoginRequiredMixin, CreateView): model = TicTacToe template_name = 'website/newgame_form.html' fields = ['player1', 'player2', 'current_player', 'title', 'board'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) class TicTacToeDetailView(UpdateView): model = TicTacToe fields = ['player1', 'player2', 'current_player', 'title', 'board'] def clean(self): if 'button0' in self.data: print('button0') i also got a database but there is really not much in there except … -
File Uploading in deployed Django applications
Where to store the images when a Django application is deployed through "Heroku" if I need to upload images using the same application after deployment ? Amazon S3 services provide a solution but the file accessing urls has a certain expiry period, so after maximum of 7days I cannot access the file using the same URL -
Save multiple values in foreign key django
I wanted to save multiple relational objects in a foreign key but unfortunately, I'm getting an error which I attached below. I already have the object with ID of 189 in my DB error: { "tags": [ "Invalid pk \"189\" - object does not exist." ] } views.py queryset = PackageRoom.objects.all() serializer = PackageRoomSerializer(queryset, many=True) return Response(serializer.data) serializers.py class PackageRoomSerializer(serializers.ModelSerializer): tags = serializers.PrimaryKeyRelatedField(queryset=PackageRoom.objects.all(), many=True) class Meta: model = PackageRoom fields = ['id', 'name', 'description', 'tags'] models.py class Tag(models.Model): name = models.CharField(max_length=255, default='') description = models.CharField(max_length=255, default='') singleline = models.ManyToManyField(Singleline) class Meta: db_table = 'tags' class PackageRoom(models.Model): name = models.CharField(max_length=255, default='') tags = models.ForeignKey(Tag, on_delete=models.PROTECT) class Meta: db_table = 'package_rooms' -
Django cuts off values from the char fields in Model after save() method?
I've been trying to wrap my head around the following: whenever I submit a form that involves some text input in Django, a character is missing when the transaction is fulfilled. I am not only having the same problem with my own forms, but also those managed by allauth (the email always has the first letter missing when user registers). When I use the debugger to see what values are being passed in through the model, it all looks good. What happense after save() is called? Could it be sqllite causing the issue? Appreciate any pointers! Here is the code (I included some debug screenshots): @login_required def create_recurring_task(request): new_task = RecurringTask.objects.create(name=request.POST['name'], cloned_task_notion_id=request.POST['id'], cloned_task_url=request.POST['url'], database_id=request.POST['database-id'], owner=request.user) tasks = request.user.tasks.filter(database_id=request.POST['database-id'] return render(request, "tasks/partials/recurring-user-tasks-list.html", {'tasks': tasks}) -
Does the permission check the group or individual permissions?
so I have been having a small confusion regarding permissions. All my tables are made in the app called app. And each admin user is assigned to a specific group, which is shown below. Similarly for every page, depending on the user's permission they would be able to access different pages. And for every view, there is a custom decorator as shown. Which has the code written in a separate decorators.py file. def permissions_allowed(allowed=[]): def decorator(view_func): def wrapper_func(request, *args, **kwargs): if not request.user.is_staff: messages.warning(request, "403 FORBIDDEN: You are not authorized to view the admin page!") return redirect('home') for perm in allowed: if not request.user.has_perm(perm): messages.warning(request, "You don't have the permissions to complete this action. Please contact the admin!") return redirect ('adminHome') return view_func (request, *args, **kwargs) return wrapper_func return decorator So my questions: Is my syntax to check the permission correct? (as shown in the 2nd pic) When I use request.user.has_perm() does it check the group permissions? the individual permissions? or both of them? Please let me know what I am doing wrong since the code isn't running the way I want it to. Thanks! -
CSRF verification failed after adding a filefield on model
I'm having a weird problem. So I have an application where my model was completely fine until I added a Filefield on it. Now I'm getting a CSRF-Verification failed error, even if I don't try to upload a file and leave it blank, it gives me the error below. This is my model: class Municipality(models.Model): activate_date = models.DateField() deactivate_date = models.DateField() code = models.CharField(max_length=200) name = models.CharField(max_length=200) alt_name = models.CharField(max_length=200, blank=True, null=True) logo = models.FileField( upload_to='Logo/muni', max_length=200, blank=True, null=True) My Application is set up on AWS using AWS Lambda, S3, and other needed services My S3 bucket (where my file should be uploaded to) is defined in my settings.py file with the env variable that has been defined on AWS Lambda environment variables AWS_STORAGE_BUCKET_NAME = env('AWS_STORAGE_BUCKET_NAME', default=None) I don't get why my model won't save even if I don't include a file. The weird thing about it is that when I'm working locally, it doesn't give me this error. And I can save this model with or without uploading a file. Other models where no Filefield or Imagefield is defined are perfectly working online and locally. Any reasons why I'm getting this error whenever I try to add a Filefield … -
Django ModelAdmin join two models using QuerySet for view both columns
In my django application i have two models: class Results(models.Model): device = models.ForeignKey(Device, null=True, on_delete=models.SET_NULL) proj_code = models.CharField(max_length=400) res_key = models.SlugField(max_length=80, verbose_name="Message unique key", primary_key=True, unique=True) read_date = models.DateTimeField(verbose_name="Datetime of vals readings") unit = models.ForeignKey(ModbusDevice, null=True, on_delete=models.SET_NULL) and class VarsResults(models.Model): id = models.AutoField(primary_key=True) key_res = models.ForeignKey(Results, related_name="keyres", on_delete=models.CASCADE) var_id = models.ForeignKey(ModbusVariable, null=True, on_delete=models.SET_NULL) var_val = models.CharField(max_length=400, blank=True) var_val_conv = models.CharField(max_length=100, blank=True, null=True) base_byte_order = models.CharField(max_length=15) var_hash = models.CharField(max_length=400) has_error = models.BooleanField(default=False) Well i would in my admin.py create a ModelAdmin that can use both fields from two models in view: @admin.register(Results) class ModbusAdmin(admin.ModelAdmin): list_display = ('res_key', 'proj_code', 'read_date', 'unit' ...HERE I WOULD ALSO MY VarsResults MODEL FIELDS) list_filter = ('proj_code', 'unit') search_fields = ('proj_code', ) ordering = ('-read_date', 'proj_code') list_display_links = None readonly_fields = () def has_add_permission(self, request): return False def has_delete_permission(self, request, obj=None): return False def save_model(self, request, obj, form, change): pass def delete_model(self, request, obj): pass def save_related(self, request, form, formsets, change): pass How can i use for example a queryset from my two models instead a single model in my ModelAdmin for use both fields? So many thanks in advance -
Django and Angular communication failure
I have developed a small Angular app with a service script to add a consumer form info to a MongoDB database: const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) } @Injectable() export class DbService { baseMongodbApiUrl = "http://localhost:8000/api/apdjango"; constructor(private httpClient: HttpClient) { } addConsumerMongodb(consumer: Post): Observable<Post> { return this.httpClient.post<Post>(`${this.baseMongodbApiUrl}` + `/handle_consumer`, consumer, httpOptions); } } I have also written this Django method in my views.py file to add a consumer: @csrf_exempt @api_view(['GET', 'POST', 'DELETE']) def handle_consumer(request): if request.method == 'POST': try: consumer_data = JSONParser().parse(request) consumer_serializer = ConsumerModelSerializer(data=consumer_data) if consumer_serializer.is_valid(): consumer_serializer.save() print(consumer_serializer.data) response = { 'message': "Successfully uploaded a consumer with id = %d" % consumer_serializer.data.get('id'), 'consumers': [consumer_serializer.data], 'error': "" } return JsonResponse(response, status=status.HTTP_201_CREATED) else: error = { 'message': "Can not upload successfully!", 'consumers': "[]", 'error': consumer_serializer.errors } return JsonResponse(error, status=status.HTTP_400_BAD_REQUEST) except: exceptionError = { 'message': "Can not upload successfully!", 'consumers': "[]", 'error': "Having an exception!" } return JsonResponse(exceptionError, status=status.HTTP_500_INTERNAL_SERVER_ERROR) and of course I have put the url pattern in my urls.py: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/apdjango$', handle_consumer), url(r'^.*', TemplateView.as_view(template_name="home.html"), name="home") ] When I use postman to Post to http://localhost:8000/api/apdjango, it goes through and I see the success message, but when I invoke my Angular service method, I … -
403 Response when I use requests to make a post request
My core code is as follows: import requests url='https://www.xxxx.top' #for example data=dict() session = requests.session() session.get(url) token = session.cookies.get('csrftoken') data['csrfmiddlewaretoken'] = token res = session.post(url=url, data=data, headers=session.headers, cookies=session.cookies) print(res) # <Response [403]> The variable url is my own website, which is based on Django. I know I can use @csrf_exempt to disable CSRF, but I don't want to do that. However, it return 403 response when I use requests to make a post request. I wish someone could tell me what was wrong with my approach. -
Django download files directly from S3 bucket to browser downloads folder
At the moment I am downloading files directly to my desktop from Django, it is possible to change the code so that when a user accesses my report the files will download directly into their browser downloads folder? My code below s3.Bucket(bucket_name).download_file(item, f'/Users/user_name/Desktop/filename.txt') -
Django Error while trying to migrate model on Postgres/Geoserver
I have a doubt similar to Django Error while trying to migrate model on Postgre DB. However I cannot solve my issue. I get the same error django.db.utils.DataError: NUMERIC precision 65535 must be between 1 and 1000 LINE 1: ...RIMARY KEY, "geom" geometry(POINT,4326) NULL, "x" numeric(65... And this is a part of the models.py class Water43262(models.Model): geom = gis_models.PointField(blank=True, null=True) x = models.FloatField(blank=True, null=True) y = models.FloatField(blank=True, null=True) sample = models.FloatField(blank=True, null=True) t_1 = models.FloatField(db_column='t - 1', blank=True, null=True) # Field renamed to remove unsuitable characters. ph_1 = models.FloatField(db_column='ph - 1', blank=True, null=True) # Field renamed to remove unsuitable characters. turb_1 = models.FloatField(db_column='turb - 1', blank=True, null=True) # Field renamed to remove unsuitable characters. -
how to let a superuser fill some forms for other users
I want to create a Django app that has two types of users. A regular user can register and fill in some contact and personal info on their profile page. The staff users have the ability to edit or add some additional info for the regular users. To be more specific, they need to fill a scientific survey for every user. Firstly, I need a page that shows all the users sorted by those who have the survey object and those who don't, and finally, by clicking on their name, the staff user gets redirected to the survey form related to that specific user. Do you guys have any suggestions on how am I supposed to do this? I created a model like this: class ScientificSurvey(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) info1 = models.CharField(max_length=24, choices=SURVEY_CHOICES) info2 = models.CharField(max_length=24, choices=SURVEY_CHOICES) info3 = models.CharField(max_length=24, choices=SURVEY_CHOICES) info4 = models.CharField(max_length=24, choices=SURVEY_CHOICES) info5 = models.CharField(max_length=24, choices=SURVEY_CHOICES) Users themselves cannot access this model and only the staff user is allowed to create or edit one for the users. I couldnt find anything on the web that could help me. -
Image uploading in django application for in production
(1) I'm trying to upload images through my django application, I upload the images into a folder and store its address/url (media url) into the database. I deployed the application in heroku, but uploading cannot be done with error "read-only file system". (2)So I moved to AWS S3 bucket services, where I can store the images in a bucket, but the image accessing urls created while uploading has expiry period of maximum 7 days, which is not good website for production because i can't use the uploaded images after 7 days. The problem arises in to situations, please provide feasible solution/alternative. -
Foregin key value in Django Rest Framework serializer
serializers.py class CarsCreateSerializer(serializers.ModelSerializer): class Meta: model = Car fields = '__all__' class RatesCreateSerializer(serializers.ModelSerializer): car_id = serializers.CharField(source='car.id', read_only=True) class Meta: model = Rate fields = ['car_id', 'grade'] models.py class CarsCreateSerializer(serializers.ModelSerializer): class Meta: model = Car fields = '__all__' class RatesCreateSerializer(serializers.ModelSerializer): car_id = serializers.CharField(source='car.id', read_only=True) class Meta: model = Rate fields = ['car_id', 'grade'] views.py class RateCar(APIView): def post(self, request): serializer = RatesCreateSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def get(self, request): rates = Rate.objects.all() serializer = RatesCreateSerializer(rates, many=True) if serializer: return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_204_NO_CONTENT) I am new to Django Rest Framework and checked some tutorials. Now I am trying to create my own structure which is like following. I want to use POST method with arguments above and I can't manage to save card_id. When I send POST method my result is : -
Save multiple relational objects in foreign key django
I want to make one to many relation between models and in Django, we need to use ForeignKey for it. I will multiple IDs of the relational objects in an array from the frontend but I'm confused that how will I save these multiple relational object in it? each package room can have multiple tags but the tags will have only one package room. models.py class Tag(models.Model): name = models.CharField(max_length=255, default='') description = models.CharField(max_length=255, default='') singleline = models.ManyToManyField(Singleline) class Meta: db_table = 'tags' class PackageRoom(models.Model): name = models.CharField(max_length=255, default='') tags = models.ForeignKey(Tag, on_delete=models.PROTECT) class Meta: db_table = 'package_rooms' the JSON object I will receive from the frontend { "name": "Test Room", "tags": [1, 2, 3, 4, 5] // IDs of Tags }