Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using USB barcode scanner in django
I have a web page where the users can type in the text box or scan a barcode and the MCO number will just appear in the textbox, how to do that so that when it scans the barcode, the MCO Number will just appear in the textbox? This is how the website looks like, when scan the barcode, the MCO number will appear in the textbox views.py @login_required() def investigation(request, pk): photo = get_object_or_404(Photo, id=pk) if request.method == "POST": form = investigationForm(request.POST, instance=photo) if form.is_valid(): mcoNum = form.cleaned_data['mcoNum'] if Photo.objects.filter(mcoNum=mcoNum).exists(): photo.status = 'Technical Investigation' photo.Datetime = datetime.now() form.save() return redirect('Viewworkshop') else: form = AddMCOForm(instance=photo) context = { "form": form, "photo": photo } return render(request, 'workshop/investigation.html', context) investigation.html <!DOCTYPE html> <html> <head> <script> $(function () { $("#datetimepicker1").datetimepicker(); }); </script> <meta charset='utf-8'> <meta http-equiv='X-UA-Compatible' content='IE=edge'> <title>SCS Technical Investigation</title> <meta name='viewport' content='width=device-width, initial-scale=1'> <!-- CSS only --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script> <!-- Font Awesome --> <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous"> <!-- Moment.js --> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js" integrity="sha256-VBLiveTKyUZMEzJd6z2mhfxIqz3ZATCuVMawPZGzIfA=" crossorigin="anonymous"></script> <!-- Tempus Dominus Bootstrap 4 --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.1.2/css/tempusdominus-bootstrap-4.min.css" integrity="sha256-XPTBwC3SBoWHSmKasAk01c08M6sIA5gF5+sRxqak2Qs=" crossorigin="anonymous" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.1.2/js/tempusdominus-bootstrap-4.min.js" integrity="sha256-z0oKYg6xiLq3yJGsp/LsY9XykbweQlHl42jHv2XTBz4=" crossorigin="anonymous"></script> </head> … -
Invalid header padding
While log in I generate token like below: payload = {'id': user.id, 'iat': datetime.datetime.utcnow()} token = jwt.encode(payload, 'secret', algorithm='HS256') And when I went to other API like user I decode token like below: token = request.COOKIES.get('token') payload = jwt.decode(token, 'secret', algorithms=['HS256']) And this is running in my local machine. But when I deploy the thing in server, it gives me an error in other API while decoding. Exception type: DecodeError Exception value: Invalid header padding I couldn't find any way to solve this problem. Now, first I want to know why this is happening? And second how I can solve this? -
Would a queryset be valued as a falsey or truthy?
I was wondering if an empty queryset would be valued as a falsey, while a full queryset would be valued as a truthy. I saw examples of lists and dictionaries, but could find any information regarding querysets. Thank you. -
Django EditForm not loading existing file with custom widget
In my Django application I have created a form using forms.py. When I am editing that form I can not see the existing files of that form, yes I have set the instance for that EditForm and I can see other text fields data, I can not see existing data of file input. If I remove the class I added in the widget, then I can see the data. Why is that? And how can I use both widget and see the existing data? Below is my code: forms.py: class ContentCreateForm(forms.ModelForm): text_instruction = forms.FileField(widget=forms.FileInput(attrs={'accept': '.txt', 'class': 'form-control'})) # If I remove this I can see the existing files course_video = forms.FileField(widget=forms.FileInput(attrs={'accept': 'video/*', 'class': 'form-control'})) # If I remove this I can see the existing files preview_video = forms.FileField(widget=forms.FileInput(attrs={'accept': 'video/*', 'class': 'form-control'}), required=False) # If I remove this I can see the existing files resource_file = forms.FileField(widget=forms.FileInput(attrs={'accept': '.pdf', 'class': 'form-control'})) # If I remove this I can see the existing files class Meta: model = Content fields = '__all__' views.py: def myView(request, id): current_content = Content.objects.get(id=id) form = forms.ContentCreateForm(instance=current_content) context = { 'form': form, } return render(request, 'editForm.html', context) -
My data is not going into post operation in django. How to do the Post call in this function?
I am working on a Django project where I have a form which I want to do POST. but everytime it went to the else part. here's my view: def ATFrun(request,test_case_ID): if request.method == 'POST': print("post") url = 'http://www.google.com' pi = APIDetails.objects.get(pk=test_case_ID) atfParam= list(APIParameter.objects.values('id','parameterName','parameterValue').filter(TC_ID=pi)) fm = APIDetailsReg(request.POST, instance=pi) req = fm.data # req = request.POST req_list = list(dict(req).values()) ATFparams_count = len(req_list) ATFparams = "" if ATFparams_count > 0: for i in range(ATFparams_count-1): ATFparams = ATFparams + req_list[i+1][0] + '=' + req_list[i+1][1] + '&' data = ATFparams[:-1] url = url + data print('paramfinal',url) if fm.is_valid(): fm.save() fm = APIDetailsReg() return HttpResponseRedirect('/TAFDashboard') else: print("not post") pi = APIDetails.objects.get(pk=test_case_ID) fm = APIDetailsReg(instance=pi) atfParam= list(APIParameter.objects.values('id','parameterName','parameterValue').filter(TC_ID=pi)) atf = APIDetails.objects.all() return render(request, 'hello/ATF_Run.html',{'ATF': atf, 'Param': atfParam}) here's my html form <div class="panel panel-info atf-form"> <div class="panel-heading text-center" style="background-color: #660099;"> <h1 class="panel-title" style="color: white;">TAF Integration URL</h1> </div> <form style="margin-top: 10px;"> {% for param in Param %} <div class="form-row"> <div class="form-group col-md-2"> <label for="param">TAF Parameter</label> <input type="text" name="{{param.id}}" class="form-control" id="inputapi_param" value="{{param.parameterName}}" readonly> </div> {% if param.parameterName == 'api' or param.parameterName == 'callback' %} <div class="form-group col-md-4"> <label for="val">TAF Value</label> <input type="text" name="{{param.id}}" class="form-control" id="inputapi_val" value="{{param.parameterValue}}" readonly> </div> {%else%} <div class="form-group col-md-4"> <label for="val">TAF Value</label> <input type="text" name="{{param.id}}" class="form-control" … -
Django - Zip together 2 attributes in Serializer
So I have this serializer below. As you can see it returns separate lists that correspond to each other: image_url and image_uuid connect and video_url and video_uuid connect. I'd like this serializer to return those attributes zipped together so it returns like response.data['image'] would be a list of dict [{image_url: some url, image_uuid: some uuid}]. How can I do this? serializer.py class FullPostDataSerializer(serializers.ModelSerializer): image_url = serializers.SlugRelatedField( source='photo_set', many=True, read_only=True, slug_field='image_url' ) image_uuid = serializers.SlugRelatedField( source='photo_set', many=True, read_only=True, slug_field='uuid' ) video_url = serializers.SlugRelatedField( source='video_set', many=True, read_only=True, slug_field='video_url' ) video_uuid = serializers.SlugRelatedField( source='video_set', many=True, read_only=True, slug_field='uuid' ) goal_uuid = serializers.SlugField() creator_username = serializers.SlugField() reply_count = serializers.IntegerField() cheer_count = serializers.IntegerField() goal_description = serializers.SlugField() class Meta: model = Post fields = ( 'body', 'join_goal', 'created', 'creator_username', 'goal_description', 'reply_count', 'cheer_count', 'image_url', 'uuid', 'type', 'image_uuid', 'creator', 'video_url', 'video_uuid', 'goal_uuid' ) helper.py def full_post_data_serializer(post_query_set: QuerySet): """ Returns post information in news feed form to include: creator username, goal description, reply count, cheer count, photos and video Parameters: post_query_set: Current Post model object query set Returns: serializer containing all data in query set serialized for news feed """ query_set_annotated = post_query_set.annotate( creator_username=F('creator__username'), goal_description=F('join_goal__goal__description'), goal_uuid=F('join_goal__goal__uuid'), reply_count=Count('replypost', distinct=True), cheer_count=Count('cheerpost', distinct=True) ).prefetch_related( Prefetch('photo_set', Photo.objects.order_by('-created')) ) return FullPostDataSerializer(query_set_annotated, many=True) -
Is it possible to leverage a catch exception for a pre_save signal?
I have a simple "before create" lifecycle hook/django signal. class Item(models.Model): title = CharField() slug = CharField(unique=True) @hook(BEFORE_CREATE): def populate_slug(self): slug = slugify(self.title) n = 1 while Item.objects.filter(slug=(f"${slug}-${n}")).exists(): n += 1 self.slug = f"${slug}-${n}" Is it possible to save that additional .exists() query and somehow leverage a IntegrityError exception error (as the slug has unique=True) to update the slug? Something like: @hook(BEFORE_CREATE): def populate_slug(self): for i in range(0,100): slug = slugify(self).title n = 1 while True: try: self.slug = f"${slug}-${n}" # This defeats the purpose of using # a "before create" signal though self.save() except: n += 1 continue break -
Django override CommonPasswordValidator error message
I'm trying to override the error message of CommonPasswordValidator, following the answers from this question i created a class to inherit to an app: #backend.custom_password_validation.py: from django.contrib.auth.password_validation import CommonPasswordValidator from django.core.exceptions import ValidationError from django.utils.translation import ugettext as _ def CustomCommonPasswordValidator(CommonPasswordValidator): def validate(self, password, user=None): if password.lower().strip() in self.passwords: raise ValidationError( _("My custom error message."), code='password_too_common', ) and i override AUTH_PASSWORD_VALIDATORS in the settings file: AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { # 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 'NAME': 'backend.custom_password_validation.CustomCommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] But when i ran my test it returned the following errors: ERROR: test_login_success (backend.tests.test_admin_template.AdminTemplateTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/admin/Documents/git/icts/rbt.api/backend/tests/test_admin_template.py", line 14, in setUp user.save() File "/Users/admin/Library/Caches/pypoetry/virtualenvs/base.django-P4xKG4YN-py3.8/lib/python3.8/site-packages/django/contrib/auth/base_user.py", line 69, in save password_validation.password_changed(self._password, self) File "/Users/admin/Library/Caches/pypoetry/virtualenvs/base.django-P4xKG4YN-py3.8/lib/python3.8/site-packages/django/contrib/auth/password_validation.py", line 60, in password_changed password_validators = get_default_password_validators() File "/Users/admin/Library/Caches/pypoetry/virtualenvs/base.django-P4xKG4YN-py3.8/lib/python3.8/site-packages/django/contrib/auth/password_validation.py", line 19, in get_default_password_validators return get_password_validators(settings.AUTH_PASSWORD_VALIDATORS) File "/Users/admin/Library/Caches/pypoetry/virtualenvs/base.django-P4xKG4YN-py3.8/lib/python3.8/site-packages/django/contrib/auth/password_validation.py", line 30, in get_password_validators validators.append(klass(**validator.get('OPTIONS', {}))) TypeError: CustomCommonPasswordValidator() missing 1 required positional argument: 'CommonPasswordValidator' Am i missing something when i inherit the class? -
Django REST JSONParser - removes line breaks?
I have a small Django REST Framework app, located in my bigger Django app. It provides endpoints, which read back some data from the app's DB, and returns it in JSON for an integrated React Front End. Now, I have lately noticed, that one of the fields in a REST endpoint returns strings from DB, but strips them off any escaped characters (\r, \n etc.), once the string is pushed through Django REST's JSONParser. In my understanding, the information flow is as follows: user ---> urls.py ---> EndpointView ---> DjangoRESTSerializer -*-> JSONParser -**-> user When I was checking shape of data in the spot marked with one * above (Django REST's template for data, before we specify format we want it in), the string in question still had all the escape characters in it. However, after specifying on that web page that I wanted that data returned in JSON (spot with two *'s above), it would reload and return JSON-style view, where the escape characters were gone. Is that an intended Django REST Framework behavior? Is there any way I can prevent JSONParser from removing escape characters? Data presentation on the React app without them is just a wall of … -
How to create form field for multiple models in Django?
Tried to figure this out on my own but stumped - I'm working on a crm project to learn Django and have gotten stuck trying to incorporate activities between a user and client. Specifically, I'm trying to make it possible to record an email interaction and to have the from/to fields reference either a user or client model. So essentially an email can be recorded as either from a user to client or vice versa. The next part would be to allow for multiple clients or users to be tagged in the correct fields of this interaction. I've tried incorporating the to and from fields as models so that they can use the GenericForeignKey class like so: class Activity(models.Model): owner = models.ForeignKey(User, on_delete=models.DO_NOTHING) date = models.DateTimeField() class EmailTo(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type') class EmailFrom(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type') class EmailActivity(Activity): emailto = models.ForeignKey(EmailTo, on_delete=models.DO_NOTHING) emailfrom = models.ForeignKey(EmailFrom, on_delete=models.DO_NOTHING) body = models.TextField(blank=True) but now I'm stuck trying to figure out how to represent that on a form. I thought maybe I could use a union to combine two queries into one field using a ModelMultipleChoiceField: class EmailActivityForm(forms.ModelForm): emailto = … -
Django - Serializer not setting ManyToManyField
For some reason the following code isn't setting the hash_tags attribute under Post. The way I checked was I put a breakpoint at the return Response line in view.py and I checked the newly created Post object and the hash_tags attribute just returned an empty list. Also when I read the serializer.data, hash_tags is an empty list as well. Even though the HashTag table clearly created the hash tag found in the body. What's going on? model.py class Post(AbstractBaseModel): creator = models.ForeignKey( User, on_delete=models.CASCADE, related_name="post_creator") join_goal = models.ForeignKey(JoinGoal, on_delete=models.CASCADE) body = models.CharField(max_length=511, validators=[MinLengthValidator(5)]) hash_tags = models.ManyToManyField(HashTag) type = models.CharField( choices=PostType.choices, max_length=50, ) class HashTag(models.Model): hash_tag = models.CharField(max_length=140, primary_key=True, validators=[ MinLengthValidator(1)]) Serializer.py class HashTagSerializer(serializers.ModelSerializer): class Meta: model = HashTag fields = ['hash_tag'] class PostSerializer(serializers.ModelSerializer): hash_tags = HashTagSerializer(many=True, read_only=True) class Meta: model = Post fields = ('creator', 'join_goal', 'body', 'uuid', 'created', 'type', 'updated_at', 'hash_tags') view.py @api_view(['POST']) def post_create_update_post(request): user_uuid = str(request.user.uuid) request.data['creator'] = user_uuid request.data['type'] = PostType.UPDATE post_text = request.data['body'] hash_tags_list = extract_hashtags(post_text) hash_tags = [HashTag.objects.get_or_create(hash_tag=ht)[0].hash_tag for ht in hash_tags_list] request.data['hash_tags'] = hash_tags try: with transaction.atomic(): serializer = PostSerializer(data=request.data) if serializer.is_valid(raise_exception=True): post_obj = serializer.save() except Exception as e: return Response(dict(error=str(e), user_message=error_message_generic), status=status.HTTP_400_BAD_REQUEST) return Response(serializer.data, status=status.HTTP_201_CREATED) -
Django Channels - URL not found for only one endpoint
Have been using django channels for the first time on a new project, have it setup working great for 5 other apps. I have just come back to it to add a websocket for a new app, but I can't get django to recognize the url, I keep getting 'Not Found: /ws/globallayer/'. I've set it up exactly the same as I did for other apps, I don't know if I'm just forgetting a step to register the urls or something, hoping someone can see something I've missed. consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer class GloballayerConsumer(AsyncWebsocketConsumer): async def connect(self): self.group_name = 'globallayer' await self.channel_layer.group_add( self.group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard( self.group_name, self.channel_name ) async def globallayer_update(self, event): data = event['data'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'data': data })) routing.py from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'^ws/globallayer/$', consumers.GloballayerConsumer.as_asgi()) ] project asgi.ppy file all_websocket_urlpatterns = [ # ... other websocket routes from different apps, *globallayer.routing.websocket_urlpatterns, ] application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( all_websocket_urlpatterns ) ), }) -
Python/Django requests JSONDecodeError: Expecting value: line 1 column 1 (char 0)
I am trying make Microservice warehouse / store. Everything is ok, but when I want to connect celery to my project, I am getting error Expecting value: line 1 column 1 (char 0) when trying to start celery @shared_task def shop_sync(): url = 'http://warehouse:8001/authors/' response_author = requests.get(url=url).json() while 1: for counter, data in enumerate(response_author['results']): Author.objects.get_or_create( id=data['id'], defaults={ 'id': data['id'], 'first_name': data['first_name'], 'last_name': data['last_name'] } ) if response_author['next']: response_author = requests.get(response_author['next']).json() else: break url = 'http://warehouse:8001/genres/' response_genre = requests.get(url).json() while 1: for counter, data in enumerate(response_genre['results']): Genre.objects.get_or_create( id=data['id'], defaults={ 'id': data['id'], 'name': data['name'] } ) if response_genre['next']: response_genre = requests.get( response_genre['next'] ).json() else: break url = 'http://warehouse:8001/books/' response = requests.get(url).json() while 1: for counter, data in enumerate(response['results']): book, created = Book.objects.get_or_create( id=data['id'], defaults={ 'id': data['id'], "title": data['title'], "description": data['description'], "image": data['image'], "language": data['language'], "status": data['status'], "price": data['price'], "isbn": data['isbn'], "pages": data['pages'], "created": data['created'], "available": data['available'], "quantity": data['quantity'], "genre": Genre.objects.get(id=data['genre']) } ) if not created: book.title = data['title'] book.description = data['description'] book.image = data['image'] book.language = data['language'] book.status = data['status'] book.price = data['price'] book.isbn = data['isbn'] book.pages = data['pages'] book.created = data['created'] book.available = data['available'] book.quantity = data['quantity'] book.genre = Genre.objects.get(id=data['genre']) book.save() for i in data['author']: author = Author.objects.get(id=i) book.author.add(author) if response['next']: … -
django models.FileField UnicodeEncodeError
I have this model. class MyModel(models.Model): ... video = models.FileField(upload_to='video/') ... def delete(self, *args, **kwargs): self.video.delete() super().delete(*args, **kwargs) An error happens when I try to delete the video. It writes. UnicodeEncodeError ... 'ascii' codec can't encode character '\u010d' in position 58: ordinal not in range(128) Exception Location: /usr/lib/python3.6/genericpath.py in isdir, line 42 How can I fix this? -
What is the best way to store big data per user?
I just need some advice about what database should I use, and how should I store my data. Namely I need to store big chunk of data per user, I was thinking about storing everything in JSON data, but I thought that I could ask you first. So I am using Django, and for now MySql, I need to store like 1000-2000 table rows per user, with columns like First Name, Last Name, Contact info, and also relate it somehow to the user that created that list. Also I need this to be able to efficiently get data from database. Is there any way of storing this big data per user? Thank you! -
Is it possible to pass the static file to be included as a context variable from the views.py?
in my django base template I have this: {% include vsm_x_win_template with vsm_x_win_body_contents='test_html' %} inside vsm_x_win_template.html is another include which I would like to be able to pass a variable to something like this. {% include {{ vsm_x_win_body_contents }} %} <--I need to dynamically set the value I'm new to Django but it seems something like this might be possible? -
Django - 'Invalid pk - object does not exist' for ManyToMany relation
For some reason at if serializer.is_valid(raise_exception=True) my code is complaining about the list hash_tags, which should be primary keys of the class HashTag that the keys in the list aren't valid, but as you can see I have a line under views.py, which is: hash_tags = [HashTag.objects.get_or_create(hash_tag=ht)[0].hash_tag for ht in hash_tags_list] that should be generate a valid list of primary keys. What is going on? serializer.py class Post(AbstractBaseModel): creator = models.ForeignKey( User, on_delete=models.CASCADE, related_name="post_creator") join_goal = models.ForeignKey(JoinGoal, on_delete=models.CASCADE) body = models.CharField(max_length=511, validators=[MinLengthValidator(5)]) hash_tags = models.ManyToManyField(HashTag) type = models.CharField( choices=PostType.choices, max_length=50, ) class HashTag(models.Model): hash_tag = models.CharField(max_length=140, primary_key=True, validators=[ MinLengthValidator(1)]) # No update added, because cannot be edited. Can only be added and deleted Serializer.py class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ('creator', 'join_goal', 'body', 'uuid', 'created', 'type', 'updated_at', 'hash_tags') view.py @api_view(['POST']) def post_create_update_post(request): """ POST endpoint for current user creating a goal update post """ user_uuid = str(request.user.uuid) request.data['creator'] = user_uuid request.data['type'] = PostType.UPDATE post_text = request.data['body'] hash_tags_list = extract_hashtags(post_text) hash_tags = [HashTag.objects.get_or_create(hash_tag=ht)[0].hash_tag for ht in hash_tags_list] request.data['hash_tags'] = hash_tags try: with transaction.atomic(): serializer = PostSerializer(data=request.data) if serializer.is_valid(raise_exception=True): post_obj = serializer.save() except Exception as e: return Response(dict(error=str(e), user_message=error_message_generic), status=status.HTTP_400_BAD_REQUEST) return Response(serializer.data, status=status.HTTP_201_CREATED) -
Django [UnicodeDecodeError: 'utf-8' codec can't decode byte 0x90 in position 595] when raise exception
In django when i raise exception [for example] if data: raise Exception('error') I always get [UnicodeDecodeError: 'utf-8' codec can't decode byte 0x90 in position 595] this error. i checked that all the files are encoded with utf-8 and there are no packages dependecies problem, there are no code that import file not english or open file. -
Connect Django and React
I have a react application built with dummy data that does stuff. This data is data that should be reached by making a request to my server. My React app is not connected to anything as of now I have to separate folders My folder with my react application My folder with my Django application My Django application is built - small application that has CRUD features. I want to integrate my React app with my Django application so that they work together. What would be the best way for doing this. -
Python Flask - Save data that can be accessed by multiple clients
I am trying to create an app that allows multiple clients to connect and use it as a video conferencing site(like google meets). This is how it would work(the different coloured clients represent different but simultaneous meetings): I am trying to find a way to store the clients video and audio data in a way that would allow other users to access it. I have thought about using file based system where a new file could be created for each meeting and that would store the relevant data but thought this may be quite slow. Another method I have thought about would be to use either a SQLite or MySQL database to store the data. I would appreciate any feedback on the methods I have mentioned above and/or any new method I haven't thought about. Thank you:) -
ValueError: Field 'maca' expected a number but got ''. Django error
I have a model like this class Product(models.Model): class Maca(models.IntegerChoices): Yes = 1, No = 2, maca = models.PositiveSmallIntegerField( db_column='maca', choices=Maca.choices ) and a form like this class ProductForm(forms.ModelForm): maca = forms.ChoiceField(required=False, choices=Product.Maca.choices, widget=forms.RadioSelect()) I have one case that this field will not show on the form. But when it is not in the form, the field 'maca' will submitted as '' (Blankn) and I'm getting an error for this ValueError: Field 'maca' expected a number but got ''. Can someone help me please? How can I send this in database as None value? -
How to use database in Heroku
I am new in web applications and I created first application in django. I decided to deployment my project in Heroku. But I'm so confused about database. I click "Heroku pricing" and I see 4-5 options. Free, Hobby, Standart, etc. And then i see databases options except these options. What is this?? as I said, this is my first applications and I dont know much about web servers. but as far as I know, service providers offer certain packages. These packages include RAM, Storage, Traffic, Database, ... etc. In short, my questions are: Is database included in heroku pricing? I saw "connection 0 of 20" while using the heroku database. Does this mean only 20 users can access the site? When I browsed the Heroku site, I didn't see any storage information in the pricing section. no storage pricing on cloud-based deployments? Can I create a different database outside of the heroku environment and connect it to heroku? every answer given informs and improving me. Thank you -
Django - drf-yasg setting request_body in @swagger_auto_schema to reduced version of serializer on @api_view
Is there a way to set request_body for @swagger_auto_schema to only be part of a Serializer? The reasoning being as you can see below the creator is set by the current user object passed by authenticator to the post_create view, but if I set request_body to the PostSerializer that'll be confusing for others, because they'll assume it needs a creator attribute, even though that's parsed from the user. Is there a way I can set request_body for this endpoint that uses @api_view with some of PostSerializer? view.py @api_view(['POST']) @swagger_auto_schema( operation_description="Create a post object" ) def post_create(request): try: request.data['creator'] = str(request.user.uuid) post_serializer = PostSerializer(data=request.data) if post_serializer.is_valid(raise_exception=True): post_obj = post_serializer.save() except ValidationError as e: return Response(dict(error=str(e), user_message=error_message_generic), status=status.HTTP_400_BAD_REQUEST) return Response(post_serializer.data, status=status.HTTP_201_CREATED) serializer.py class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ('creator', 'body', 'uuid', 'created', 'updated_at') -
Как разделить сервер авторизации и остальную работу с данными на два разных сервера
Я начинаю писать сайт на django-rest-framework и пишу авторизацию с использованием jwt токенов.И я прочитал что сервер авторизации должен быть отделён от остальной логики, но я вообще не могу найти как это сделать. Я видел пример что нужно использовать django aouth toolkit но не могу найти не одного примера работы с ним. По возможности прошу очень подробное объяснение или ссылки на источники. Заранее спасибо) -
How to implement CI/CD pipeline for Django application
I have a Django project and I want to implement CI/CD pipeline for the project but I really don't know how to go about it. Can someone guide me or refer a comprehensive article on that. Am using gitlab