Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"Uncaught RangeError: Maximum call stack size exceeded at Dt (jquery.min.js:2)"
I am new to programming with django and now I am stuck at this stage, where I have to move data from the js variable to Django view or something. But at the moment if I try to pass the data from js to Django using ajax post function it says uncaught range error. I am not sure where I am making the mistake but it would be really helpful if anyone can help me. Really indeed of help PLS!!! Error message: Uncaught RangeError: Maximum call stack size exceeded at Dt (jquery.min.js:2) Script code <script> var URL = "{% url 'textFromInputFile' %}"; var textOfFile = document.getElementById('fileinput'); textOfFile.addEventListener('change', function(){ var fr = new FileReader(); fr.onload = function(){ document.getElementById("textarea").value = fr.result; }; fr.readAsText(this.files[0]); }); function getText(){ $.ajax({ type: "POST", url: "/textFromInputFile", data: {"textOfFile":textOfFile}, dataType: "String", success: function(data){ alert("ok") }, failure:function(){ alert("failed") } },);} $('button').click(function(){ getText(); }); </script> views.py def textFromInputFile(request): if request.method == 'POST': if 'textOfFile' in request.POST: textOfFile = request.POST['textOfFile'] #need to do something here return HttpResponse('success') #if everything is o.k else: return HttpResponse('failed!!') urls.py urlpatterns = [ path('', views.index, name='index'), path('signin.html', views.signin, name='signin'), path('index.html', views.index, name='index'), path('home.html', views.home, name='home'), path('logoutPage.html', views.logout, name='logout'), path('home.html', views.textFromInputFile, name='textFromInputFile'), ] -
Django Rest Framework: drf-renderer-xlsx -- How to create the second sheet in file the for return a Response
following code create xlsx file with a single sheet but I want to create a second sheet in the same file with different Model data or suggest me another way to work with Serializer. drf-renderer-xlsx doc https://pypi.org/project/drf-renderer-xlsx/ from rest_framework.viewsets import ReadOnlyModelViewSet from drf_renderer_xlsx.mixins import XLSXFileMixin from drf_renderer_xlsx.renderers import XLSXRenderer from .models import MyExampleModel from .serializers import MyExampleSerializer class MyExampleViewSet(XLSXFileMixin, ReadOnlyModelViewSet): queryset = MyExampleModel.objects.all() serializer_class = MyExampleSerializer renderer_classes = (XLSXRenderer,) filename = 'my_export.xlsx' -
Django cloudinary image how to add onClick event in tag?
I am successfully creating a Cloudinary image as follows: {% cloudinary photo.filename width='300' crop='fill' class='item_photo' id=photo.filename %} Which results in html img tag: <img class="item_photo" id="xxxxxx" width="300" src="https://res.cloudinary.com/xxx/image/upload/c_fill,w_300/vxxx/xxx.jpg"> However, I want to add an onClick event to the img, but am not able to figure out the correct syntax or perhaps even if it is possible. I would like html tag to look like: <img class="item_photo" id="xxxxxx" width="300" onClick=imageClick('xxxxxx') <=== event variable is same as `id` value src="https://res.cloudinary.com/xxx/image/upload/c_fill,w_300/vxxx/xxx.jpg"> The id and imageClick variable are themselves populated by Django template tag value photo.filename. Some things I've tried: onClick='photoClick(photo.filename)' %} {% with add:'onClick=photoClick('{{ photo.filename }}|add:') as onclick %}{{ onclick }}{% endwith %} |add:'onClick=photoClick('{{ photo.filename }}|add:')' %} How can I construct the onClick=photoClick(xxx) part of this template tag? -
ValueError: Field 'id' expected a number but got 'liked'
hello everyone hope you are fine.I am struggling with this error, ValueError: Field 'id' expected a number but got 'liked'. this is views.py function def like_unlike_post(request): user = request.user if request.method == 'POST': post_id = request.POST.get('post_id') post_obj = Post.objects.get(id=post_id) profile = Profile.objects.get(user=user) if profile in post_obj.liked.all(): post_obj.liked.remove(profile) else: post_obj.liked.add(profile) like, created = Like.objects.get_or_create(user=profile, post_id=post_id) if not created: if like.value=='Like': like.value='Unlike' else: like.value='Like' else: like.value='Like' post_obj.save() like.save() return redirect('posts:main-post-view') and this is my urls.py path('menu/Sharing-daily/daily/posts/',post_comment_create_and_list_view, name="main-post-view"), path('menu/Sharing-daily/daily/posts/liked/',like_unlike_post, name='like-post-view'), what might be the problem, because I don't understand why it was before working but now this error . -
ChangeEmailView() got an unexpected keyword argument 'token'
I'm trying to make an url with an value from the views in it path('settings/email/changeemail/<str:token>', views.ChangeEmailView , name="changeemail"), but this error appears if i enter the page: Internal Server Error: /settings/email/changeemail/0fdb9ef1-ce86-482e-a8ef-3fc202438ba9 Traceback (most recent call last): File "C:\Users\Finn\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Finn\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Finn\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) TypeError: ChangeEmailView() got an unexpected keyword argument 'token' this is my views.py @login_required(login_url='home:login') def ChangeEmailView(request): if request.method == 'POST': objects = User.objects.get(email = request.user.email) form = EmailChangingForm(request.POST, instance=objects) packet = get_object_or_404(TempUrl, user=request.user) token = packet.uid if form.is_valid(): form.save() return redirect('home:profilesettings') else: objects = User.objects.get(email = request.user.email) form = EmailChangingForm(request.POST, instance=objects) packet = get_object_or_404(TempUrl, user=request.user) token = packet.uid context = {'form': form, 'token': token} return render(request, 'home/email_settings.html', context) in the end I want to have an unique url from which the token is saved in the db heres the other view where the uuid is generated and put to the db def load_url(request): token = uuid.uuid4() objects = TempUrl.objects.update_or_create(user = request.user, uid=token, used=False) print("Das ist der Token:" + str(token)) context = {'token': token} return render(request, 'home/changeemail_pre.html', context) -
What are the risks of not cycling session keys in Django?
Django cycles the session key upon login. The rationale (that I don't understand) is in this pull request: When logging in, change the session key whilst preserving any existing sesssion. This means the user will see their session preserved across a login boundary, but somebody snooping the anonymous session key won't be able to view the authenticated session data. Cycling the session key is awkward if you wish to easily associate unauth behavior with a later logged-in user. This answer suggests simply disabling cycle_key. What risks are there in disabling cycle_key? (Related to the comment above, or others.) -
How convert miles km in geodjango
I have this view that works fine but I am finding difficult to display the result in km. I calculated the distance between two points but I get the results in meters but I want it in kilometers. vews.py from django.contrib.gis.db.models.functions import Distance class SearchResultsView(generic.TemplateView): template_name = "search.html" def get_context_data(self, **kwargs): context = super(SearchResultsView, self).get_context_data(**kwargs) query = self.request.GET.get('q', default='') location_ = self.request.GET.get('location') geolocator = Nominatim(user_agent="geo", timeout=10000) location = geolocator.geocode(location_) print(location) new = Point(location.latitude, location.longitude, srid=4326) context.update({ 'job_listing': JobListing.objects.annotate( distance=Distance("location_on_the_map", new) ).filter(Q(job_title__icontains=query)).order_by("distance") }) return context -
Django API and Reactjs 401 Forbidden
I have set up a Django backend that receives calls from a react js frontend. They are deployed on two separate servers. My users can log in and be assigned a token which I can see clearly being stored on the browser properly. This functionality works just fine. Yet when I am making calls (other than to login) to the backend I receive error 401 unauthorized. In order to test the functionality, I set up a basic request that looks as such in ReactJS. //Axios variables required to call the predict API let headers = { 'Authorization': `Token ${props.token}` }; let url = settings.API_SERVER + '/api/test/predict/'; let method = 'post'; let config = { headers, method, url, data: irisFormData }; //Axios predict API call axios(config).then( res => {setPrediction(res.data["Predicted Iris Species"]) }).catch( error => {alert(error)}) Note: setPrediction() is just a react state. This is the related view on the backend. class IRIS_Model_Predict(APIView): authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] def post(self, request, format=None): data = request.data keys = [] values = [] for key in data: keys.append(key) values.append(data[key]) X = pd.Series(values).to_numpy().reshape(1, -1) loaded_mlmodel = PredictionConfig.mlmodel y_pred = loaded_mlmodel.predict(X) y_pred = pd.Series(y_pred) target_map = {0: 'setosa', 1: 'versicolor', 2: 'virginica'} y_pred = y_pred.map(target_map).to_numpy() … -
How do I pass kwargs from view into models.querset then into as_manager()?
I am trying to filter across Django apps (same db). I have events which staff members have been assigned to work, different roles worked at times by the staff (usually one role per event), each role with different pay rates. Here are the models in question: class Event(models.Model): event_type = ForeignKey(EventType, on_delete=models.DO_NOTHING, default=1) event_name = models.CharField(max_length=200) event_date = models.DateField(default=datetime.now) event_time = models.TimeField(default='07:00 pm') event_length_in_hours = models.DecimalField(max_digits=4, decimal_places=2, default=2.0) is_this_tax_exempt = models.BooleanField(null=False, default=False) painting_with_a_purpose = models.BooleanField(null=False, default=False) paint_pour_event = models.BooleanField(null=False, default=False) prepaint_product_used = ForeignKey(Product, on_delete=models.DO_NOTHING, related_name='prepaint_product_used', default=1, limit_choices_to={'product_active': True, 'product_type': '1'}) prepaint_product_qty = models.IntegerField(default=0) stage_product_used = ForeignKey(Product, on_delete=models.DO_NOTHING, related_name='stage_product_used', default=2, limit_choices_to={'product_active': True, 'product_type': '1'}) stage_product_qty = models.IntegerField(default=1) credit_card_tip_received = models.BooleanField(null=False, default=False) credit_card_tip_amount = models.DecimalField(max_digits=5, decimal_places=2, default=0.00) credit_card_tip_percent_shared_from_stage = models.DecimalField(max_digits=3, decimal_places=2, default=0.30) event_ad_fees = models.DecimalField(max_digits=5, decimal_places=2, default=0.00) event_discounts = models.DecimalField(max_digits=6, decimal_places=2, default=0.00) event_extra_expense = models.DecimalField(max_digits=6, decimal_places=2, default=0.00) event_extra_income = models.DecimalField(max_digits=6, decimal_places=2, default=0.00) class EventWorker(models.Model): staff_member = models.ForeignKey(Staff, on_delete=models.DO_NOTHING, limit_choices_to={'is_active_staff': True}) role_worked = models.ForeignKey(EventRole, default=1, on_delete=models.DO_NOTHING) event_id = models.ForeignKey(Event, on_delete=models.CASCADE) hours_worked = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) class EventRole(models.Model): role_name = models.CharField(max_length=100) def __str__(self): return self.role_name Then in a different app inside the same Django deployment I have the following: class Staff(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE, default=1, related_name='member') full_name = models.CharField(max_length=200) phone = models.CharField(max_length=200) … -
Django with aws s3 Restricted media files only visible to owner
I have a model which basically saves files/images for each particular user and only that user will be able to view his/her file, other users cannot view other's private files/images. def user_id_directory(instance, file): return f"{instance.id}/{file}" class PrivateFile(models.Model): owner = models.ForeignKey(to=UserModel, on_delete=models.CASCADE) image = models.ImageField(upload_to=user_id_directory) created = models.DateTimeField(auto_now_add=True) I am using s3 to save media files, but using s3 will leave a link that can be accessed by any other user Suppose there's a file called FILE1 which has an id 1, and I have created an API that returns the following JSON schema. { "id": 1, "user": 1, "image": "example.aws.com/Media/File/1/image.png?AccessID=...." "created": "2021-09-09 09:09:09.25555", } If I give this link to anyone, even an unauthorized user will be able to view that file using that link, How can I restrict it to only the user who is the owner of the file, only he/she will be able to view it via the link. -
Starting Django with docker unexpected character
I'm trying to start up this Project on my Mac https://github.com/realsuayip/django-sozluk It works on my Windows machine, but I got this Error on my Mac: unexpected character "." in variable name near "127.0.0.1 192.168.2.253\nDJANGO_SETTINGS_MODULE=djdict.settings_prod\n\n\nSQL_ENGINE=django.db.backends.postgresql\nSQL_PORT=5432\nDATABASE=postgres\nSQL_HOST=db\n\nSQL_DATABASE=db_dictionary\nSQL_USER=db_dictionary_user\nSQL_PASSWORD=db_dictionary_password\n\n\nEMAIL_HOST=eh\nEMAIL_PORT=587\nEMAIL_HOST_USER=eh_usr\nEMAIL_HOST_PASSWORD=pw" furkan@MacBook-Air-von-Furkan gs % Any help would be much appreciated! -
Django rest framework simple jwt: decode() got an unexpected keyword argument 'verify'
now I have this error from django rest framework, and I don't know why. All was fonctionnal before. File "/home/mathieu/.local/share/virtualenvs/back-aSs_Rzmq/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/mathieu/.local/share/virtualenvs/back-aSs_Rzmq/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/mathieu/.local/share/virtualenvs/back-aSs_Rzmq/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/mathieu/.local/share/virtualenvs/back-aSs_Rzmq/lib/python3.8/site-packages/django/views/generic/base.py", line 69, in view return self.dispatch(request, *args, **kwargs) File "/home/mathieu/.local/share/virtualenvs/back-aSs_Rzmq/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/home/mathieu/.local/share/virtualenvs/back-aSs_Rzmq/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/home/mathieu/.local/share/virtualenvs/back-aSs_Rzmq/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/home/mathieu/.local/share/virtualenvs/back-aSs_Rzmq/lib/python3.8/site-packages/rest_framework/views.py", line 497, in dispatch self.initial(request, *args, **kwargs) File "/home/mathieu/.local/share/virtualenvs/back-aSs_Rzmq/lib/python3.8/site-packages/rest_framework/views.py", line 414, in initial self.perform_authentication(request) File "/home/mathieu/.local/share/virtualenvs/back-aSs_Rzmq/lib/python3.8/site-packages/rest_framework/views.py", line 324, in perform_authentication request.user File "/home/mathieu/.local/share/virtualenvs/back-aSs_Rzmq/lib/python3.8/site-packages/rest_framework/request.py", line 227, in user self._authenticate() File "/home/mathieu/.local/share/virtualenvs/back-aSs_Rzmq/lib/python3.8/site-packages/rest_framework/request.py", line 380, in _authenticate user_auth_tuple = authenticator.authenticate(self) File "/home/mathieu/.local/share/virtualenvs/back-aSs_Rzmq/lib/python3.8/site-packages/rest_framework_simplejwt/authentication.py", line 40, in authenticate validated_token = self.get_validated_token(raw_token) File "/home/mathieu/.local/share/virtualenvs/back-aSs_Rzmq/lib/python3.8/site-packages/rest_framework_simplejwt/authentication.py", line 94, in get_validated_token return AuthToken(raw_token) File "/home/mathieu/.local/share/virtualenvs/back-aSs_Rzmq/lib/python3.8/site-packages/rest_framework_simplejwt/tokens.py", line 43, in __init__ self.payload = token_backend.decode(token, verify=verify) File "/home/mathieu/.local/share/virtualenvs/back-aSs_Rzmq/lib/python3.8/site-packages/rest_framework_simplejwt/backends.py", line 90, in decode return jwt.decode( TypeError: decode() got an unexpected keyword argument 'verify' I follow the simple dango rest simple jwt example. My settings.py REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework_simplejwt.authentication.JWTAuthentication", ], } And my views.py from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.permissions import IsAuthenticated from .models import … -
How to access a serializer attribute from a method with no 'attrs' argument
Im trying to access the participants attribute in my conversation serializer from inside my 'get_other_user' method. My participants attribute returns a list of user dictionaries. However, when I run the code I get model has no attribute 'participants'. Im assuming I have to pass in a, 'attrs' argument in to the 'get_other_user' method, (one similar to the 'def validate(self, attrs) method), then use attrs.get('participants). However, I do not know how to fill in the attrs parameter when calling this method in my get_other_username method. Any advice would be appreciates. Thanks! class ConversationSerializer(serializers.ModelSerializer): other_username = serializers.SerializerMethodField(method_name='get_other_username', read_only=True) other_user_email = serializers.SerializerMethodField(method_name='get_other_user_email', read_only=True) # latest_message = serializers.SerializerMethodField(method_name='get_latest_message', read_only=True) participants = UsersSerializer(many=True, read_only=True) class Meta: model = Conversation fields = ['conversation_id' ,'participants','other_username', 'other_user_email'] def get_current_user_id(self): user_id = self.context['current_user'].id return user_id def get_other_user(self): current_user_id = self.get_current_user_id() for participant in self.participants: if participant['id'] != current_user_id: return participant def get_other_username(self, obj): other_user = self.get_other_user() return other_user['username'] def get_other_user_email(self, obj): other_user = self.get_other_user() return other_user.email -
'Poll' object has no attribute 'get_absolute_url'
When I followed django cms 3.9.0 documentation of part 8. Content creation wizards. I got this error. Is there anyone know that how to fix it? I will really appreciate your advices. AttributeError at /zh/cms_wizard/create/ 'Poll' object has no attribute 'get_absolute_url' Request Method: POST Request URL: http://127.0.0.1:8000/en/cms_wizard/create/ Django Version: 3.1.13 Exception Type: AttributeError Exception Value: -
Can't handle Crispy Forms with helper with ModelForm and Base View (UpdateView)
i know how to render and use with success a form with Crispy whatever the view type but only with templates.html (not forms.py). But seing that all my forms were vertical, i searched a way to customize them. For example being able to display 3 checkboxes or other fields on the same row. I spent several days trying to do it with Django native forms classes but couldn't obtain what i wanted with CSS. I also tried a long time to do it with Crispy and Helper witch seem to me the easiest way but it still doesn't work. Without success. I'm blocked at the very start of my test especially because i have to manage with a / URL parameter Whatever i try to do, a never-ending error raises : init() got an unexpected keyword argument 'pk' forms.py, line 9, in init --> super(SupplierDetailForm, self).init(*args, **kwargs) If i remove this constructor, same error raises deeply in Django -> site-packages/django/core/handlers/base.py, line 181, in _get_response First question : during all my searches, i saw that Model used or Fields were declared either in VIEW or in FORM class in its META. What method should i use ? 2nd question : i … -
Why doesnt PyJwt recognize the positional argument "algorithm" when using "ES256" signing method?
I'm using PyJwt to generate and encode a JWT for apple application notification service token authentication which requires the ES256 signing algorithm as noted here . self.server = settings.APNS_SERVER self.algorithm = 'ES256' PRIVATE_KEY = settings.APNS_PRIVATE_KEY encoded_jwt = jwt.encode( {'iss': settings.TEAM_ID, 'iat': time.time()}, PRIVATE_KEY, algorithm=self.algorithm, headers={'alg': self.algorithm, 'kid': settings.APNS_KEY_ID}, ) When passed this way, I get the following error: encoded_jwt = jwt.encode( File "/usr/local/lib/python3.9/site-packages/jwt/api_jwt.py", line 63, in encode return api_jws.encode(json_payload, key, algorithm, headers, json_encoder) File "/usr/local/lib/python3.9/site-packages/jwt/api_jws.py", line 114, in encode signature = alg_obj.sign(signing_input, key) File "/usr/local/lib/python3.9/site-packages/jwt/algorithms.py", line 423, in sign der_sig = key.sign(msg, ec.ECDSA(self.hash_alg())) TypeError: sign() missing 1 required positional argument: 'algorithm' This doesn't happen when I use the RS256 or HS256 signing algorithm. Why is this happening? -
Getting all products from Many2Many field Django
My User model looks like this: class User(AbstractBaseUser, PermissionsMixin): id = models.UUIDField(primary_key=True) #other user informations, f.e. color, size, name followed = models.ManyToManyField( Product, related_name="followed_products", blank=True) objects = CustomAccountManager() object = models.Manager() def __str__(self): return self.email I am storing an user followed products inside followed = models.ManyToManyField(Product, related_name="followed_products", blank=True). I am adding products by this FollowView: def FollowView(request, pk): if request.COOKIES.get('refresh_token'): refresh = jwt.decode(request.COOKIES.get( 'refresh_token'), SECRET_KEY, algorithms=["HS256"]) user = User.objects.filter(id=refresh['user_id']).first() product = Product.object.filter(id=pk).first() user.followed.add(product) return Response({}, status=status.HTTP_200_OK) My Product model looks like this: class Product(models.Model): class ProductObjects(models.Manager): def get_queryset(self): return super().get_queryset().filter(status='published') id = models.UUIDField(primary_key=True) owner = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) #other Product informations object = models.Manager() productobjects = ProductObjects() def __str__(self): return self.name Now my question is, how can I GET all the products with details (f.e. name, color, size) and send them to frontend? I tried to GET them like this: user.followed.get(owner=refresh['user_id']) but it returns me an error: get() returned more than one Product -- it returned 2! (the 2 here is strange, because when I do user.followed.count() it shows me 3) -
How to detect user from token?
I have Django for my backend and vue for my frontend. I am using dj-rest-auth for authentication, and a token key is generated on each login. I could save this to vuex, but I am not really sure how to identify the user? I am building a blog, and editing of certain blog posts must be allowed only for the author? How should I get to generate the username from the token so that only the author can edit it? -
how to show tick mark on the values that are saved in databse for update form in Django
Let us consider soil_type selected while creating a item, while creating a item we can choose multiple choices of soil_type for example let us consider a tree_name = Hibiscus when can be grown in multiple soil_type like clay soil, red soil, acidic soil,.. (where these are choices of soil_type and is a multiple choice field in create form ) if suppose the user selected soil_type for Hibiscus as both clay soil and acidic soil while update form it should show ticked let us consider my forms.py as SOIL_TYPE_CHOICES = ( ('Acidic','Acidic'), ('Alkaline','Alkaline'), ('Chalk','Chalk'), ('Clay','Clay'), ('Damp','Damp'), ) class HorticlutureUpdateForm(BetterModelForm): soil_type = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, choices=SOIL_TYPE_CHOICES, ) .... ..... class Meta: model = TreeDetails exclude = ('created_by', 'client', 'is_deleted') fieldsets = [ ["main", { "fields": ['tree_name', 'common_name','description', 'part_number', 'unit_price'], "legend": "Main details", }], ["extra", { "fields": [ 'quantity', 'height' 'soil_type', ], "legend": "Additional details", }], ] here is my index.html <form class="form-horizontal" method="post" enctype="multipart/form-data"> {% csrf_token %} {% for field in form.hidden_fields %}{{ field }}{% endfor %} <fieldset class="add"> <legend class="main">{{ form.fieldsets.main.legend }}</legend> <fieldset id="edit-contact-fields" class="edit-contact"> {% for field in form.fieldsets.main %} <div class="control-group" id="{{ field.name }}_wrapper"> <label class="control-label pull-left" for="{{ field.auto_id }}">{{ field.label }} {% if field.field.required %}<span class="text-error">*</span>{% endif %}</label> … -
save values of foreign key django
I want savevalues of foreign key model in view fuctions, this my models, forms, and views. models.py: enter image description here Forms.py: enter image description here View.py enter image description here -
AWS EB container commands - collectstatic failed
Currently, I'm trying to push all static files to S3 in django project, but deployment is failed because of the ERROR below : 2021/10/07 14:55:55.675229 [ERROR] An error occurred during execution of command [app-deploy] - [PostBuildEbExtension]. Stop running the command. Error: Container commands build failed. Please refer to /var/log/cfn-init.log for more details. 2021/10/07 14:55:55.675250 [INFO] Executing cleanup logic 2021/10/07 14:55:55.675339 [INFO] CommandService Response: {"status":"FAILURE","api_version":"1.0","results":[{"status":"FAILURE","msg":"Engine execution has encountered an error.","returncode":1,"events":[{"msg":"Instance deployment successfully generated a 'Procfile'.","timestamp":1633618548,"severity":"INFO"},{"msg":"Instance deployment failed. For details, see 'eb-engine.log'.","timestamp":1633618555,"severity":"ERROR"}]}]} FYI, when I do 'python manage.py collectstatic' on my computer, the command perfectly works and all static files uploaded to S3. However, on ElasticBeanstalk, the container command does not work. So the deployment is failed as well. EB environment : Python 3.8 running on 64bit Amazon Linux 2/3.3.6 Just in case, as I use pipenv, which is known compatibility issue with AWS EB CLI, I used 'pipenv_to_requirement -f' to create requirements.txt Among the packages checked by the pipenv graph command, those not in requirements.txt were manually added. settying.py DEFAULT_FILE_STORAGE = "config.custom_storages.UploadStorage" STATICFILES_STORAGE = "config.custom_storages.StaticStorage" AWS_ACCESS_KEY_ID = os.environ.get("AWS_ACCESS_KEY_ID") AWS_SECRET_ACCESS_KEY = os.environ.get("AWS_SECRET_ACCESS_KEY") AWS_STORAGE_BUCKET_NAME = "mybucket_202110" AWS_DEFAULT_ACL = "public-read" AWS_S3_CUSTOM_DOMAIN = f"{AWS_STORAGE_BUCKET_NAME}.s3.ap-northeast-2.amazonaws.com" STATIC_URL = f"https://{AWS_S3_CUSTOM_DOMAIN}/static/" django.config container_commands: 01_migrate: command: "source /var/app/venv/*/bin/activate && python3 … -
Django LogEntry model out of the admin
I am having some struggles how does exactly django.admin.LogEntry objects are created. The question is: django docs are not very descriptive on how does LogEntry works and I can not find the best way. Where I can put logic to save records? Signal/Form save override/Model Save override which will be simple and elegent way? Does anybody got any experience with such scenarios and can share thoughts about it? -
Django filter a model with it's related models fields
i have a Product model with multiple related models: Currency Category Material in the view i'm filtering according to a search query how can i get the result with every related model data. views.py : def product_autocomplete(request): query = request.POST.get("query") if len(query) > 2: products = Product.objects.filter( Q(name__contains=query) | Q(material__name__contains=query) | Q(identifier__contains=query) | Q(barcode__contains=query) ) products = serializers.serialize("json", products) result = {"result": products} return JsonResponse(result) models.py: class Product(models.Model): name = models.CharField(max_length=30, unique=True) stock_price = models.FloatField() price = models.FloatField() special = models.FloatField() expire = models.DateField(null=True, blank=False) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) seller = models.ForeignKey(Seller, on_delete=models.SET_NULL, null=True) material = models.ManyToManyField(Material) quantity_type = models.ForeignKey(QuantityType, on_delete=models.SET_NULL, null=True) quantity = models.FloatField() extra_quantity = models.FloatField(null=True, default=0) barcode = models.CharField(null=True, max_length=30, blank=False) identifier = models.CharField(null=True, max_length=30, blank=False) location = models.CharField(null=True, max_length=30, blank=False) alert_if_lower_than = models.IntegerField(null=True) image = models.CharField(max_length=100, blank=False, null=True) def __str__(self): return self.name class Category(models.Model): name = models.CharField(max_length=30, unique=True) desc = models.CharField(max_length=300, null=True, blank=False) def __str__(self): return self.name class Currency(models.Model): name = models.CharField(max_length=30, unique=True) value = models.FloatField() rate = models.FloatField() def __str__(self): return self.name class Material(models.Model): name = models.CharField(max_length=30, unique=True) desc = models.CharField(max_length=300, null=True, blank=False) def __str__(self): return self.name for now the result only returns the primary key of the related model. how to return the … -
How to add multiple records for foreign key in a single request in DRF?
There is a model named as UserSkill. It contains User and Skills ForeignKeys I want to create multiple skills for one user in single post request and i want to store data like this [{'user': 1, 'skills': 1,2,3,4}]. The problem is how can i write create method for that? I do not want to use ManyToMany field for that class UserSkill(models.Model): user = ForeignKey(User, on_delete=models.CASCADE) skills = ForeignKey(Skills, on_delete=models.CASCADE) class UserSkillSerializer(ModelSerializer): class Meta: model = UserSkill fields = "__all__" class UserSkillList(ListCreateAPIView): serializer_class = UserSkillSerializer queryset = UserSkill.objects.all() def create(self, validated_data): ... -
Using Django to process data without using persistent models
I am new to Django, and my question must be straightforward to answer: How can I use Django to process data without persistent models? I want to make a POST request that receives an incoming object, processes it, and returns an object with a dictionary attribute - no persistence of any kind. I am using the REST framework package for ViewSets, Models and Serializers, but I cannot figure out how to use these classes without persistence.