Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Login to Django admin with firebase token - what is the most secure way?
I'm building an app with Django (Wagtail) backend for REST API and firebase frontend for auth and firestore. The backend runs on api.domain.com, while the frontend runs on domain.com. I want to give my firebase users the ability to login into Django (Wagtail) admin. I'm trying to implement it in two ways: Easy: I get firebase token on the frontend and send my user to api.domain.com/<<firebase token>> The backend than does all the job to log the user in. The approach works just fine, but I don't like it, since I expose the token in my url. Hard: I make an api GET request from my frontend to backend with firebase token in Authorization Header: axios.get('http://localhost:8000', { withCredentials: true, headers: { Authorization: <<firebase token>> } })... On my backend I respond with the sessionid cookie for the api.domain.com and than redirect the user to my django admin backend. The approach seems to be feasible in theory but I struggle with setting cross-domain cookies via API call. I already tried CORS_ALLOW_HEADERS = list(default_headers) + [ "accept", "accept-encoding", "authorization", "content-type", "dnt", "origin", "user-agent", "x-csrftoken", "x-requested-with" ] CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", "http://127.0.0.1:3000", "http://localhost:8000", "http://127.0.0.1:8000", "http://127.0.0.1", "http://localhost", "http://test.com:8000", "http://test.com" ] CORS_ALLOW_METHODS … -
Django: User vs UserProfile
I'm building a site where we ask users several personal details (birth date, phone number, address, marital status etc. many more). Option 1: User model only. Put these personal fields in class User(AbstractUser) model class User(AbstractUser): birth_date = ... phone_number = ... Option 2: User + UserProfile models: separate login-related data (User) from personal data (UserProfile) like: class User(AbstractUser): pass class UserProfile(models.Model): user = models.OneToOneField( User, to_field="id", primary_key=True, on_delete=models.CASCADE, related_name="user_profile", ) birth_date = ... phone_number = ... Which one is the best practice? -
update django template without reloading and without javascript
so if I have this code in django template {% for item in items %} <p>{{ item.name }}</p> <hr> {% endfor %} can I update it without refreshing? and wothout javascript? is it possible? -
Django Rest Framework (DRF) how to get value of GenericRelation field?
at my models.py I have a "Movies" model with the following field setup: video_stream_relation = GenericRelation(VideoStreamInfo, related_query_name='video_stream_relation') This GenericRelation field points to the following model class: class VideoStreamInfo(models.Model): objects = RandomManager() id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) content_type = models.ForeignKey(ContentType, limit_choices_to=referential_stream_models, on_delete=models.CASCADE, verbose_name=_("Content Type")) object_id = models.CharField(max_length=36, verbose_name=_("Object ID")) content_object = GenericForeignKey('content_type', 'object_id') index = models.IntegerField(verbose_name=_("Stream Index"), blank=False) bit_rate = models.IntegerField(verbose_name=_("Bitrate (bps)"), blank=True, null=True, editable=False) codec_name = models.CharField(verbose_name=_("Codec Name"), blank=True, null=True, editable=False, max_length=255) width = models.IntegerField(verbose_name=_("Width"), blank=True, null=True, editable=False) height = models.IntegerField(verbose_name=_("Height"), blank=True, null=True, editable=False) date_added = models.DateTimeField(auto_now_add=True, verbose_name=_("Date Added")) Now the Question is how can I get video_stream_relation.codec_name value in a ModelSerializer like this: class MovieSerializer(serializers.ModelSerializer): id = serializers.PrimaryKeyRelatedField(queryset=Movies.objects.all()) class Meta: model = Movies fields = ('id', ...) I want to be able to display the codec_name as a API JsonResponse. If needed, this is how my API view currently looks like: @api_view(['GET',]) @authentication_classes([JSONWebTokenAuthentication]) @permission_classes([AllowAny]) def movies(request): if request.method == 'GET': obj = Movies.objects.all() serializer = MovieSerializer(obj, many=True) return JsonResponse(serializer.data, safe=False) If I try to add the video_stream_relation field to my MovieSerializer I get back the following error: TypeError: Object of type GenericRelatedObjectManager is not JSON serializable Thanks in advance. -
how to pass the username to the member who fill a form?
i have a form, and i want to pass the user to it to see which logged in user filled it. this is my forms.py from .models import UserInfo from django import forms class InfoForm(forms.ModelForm): class Meta: model = UserInfo fields = ('name', 'age', 'male', 'female', 'height', 'weight', 'BMI', 'BFP', 'phone', 'r_g_weight', 'physical_ready', 'fitness', 'workour_sports', 'others', 'goal_expression', 'body_change', 'noob','low_pro','semi_pro','pro','motivation_level','goal_block', 'change_time','past_sports','injury','work','work_time','wakeup_time', 'work_start_time','sleep_time','daily','hard_to_wake','ready_to_work', 'life_situation','weight_feel','daily_jobs','health_ready','workout_period', 'what_sport','where_sport','home_sport','weekly_time','sport_dislike','daily_food', 'food_quantity','hunger','vitamins','rejims','vegetables','goal_rec', 'stop','rec','heart','chest','chest_month','dizzy','bones','blood','other_reason') and this is my view, i asked for the user with request.user , but the field in db always is empty for username. def userForm(request): if request.method == "POST": form = InfoForm(request.POST) if form.is_valid(): form.user = request.user form.save() return redirect('profile') else: form = InfoForm() context = { 'form':form } return render(request, 'fitness/user_form.html', context) so i have user in my models which has foreign key to my account user = models.ForeignKey(Account,on_delete=models.CASCADE, null=True, blank=True) and this is my template: <div class="container"> <form action="{% url 'user-form' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{form.as_p}} <input type="submit" value="submit"> </form> </div> -
Test for removed permission implemented in form_valid() in Django
I cannot understand why my test doesn't pass. I used RequestFactory as mentioned in this answer which, unfortunately, proved useless for me. from io import BytesIO, StringIO from django.contrib.auth.models import User, Permission from django.test import TestCase, RequestFactory from graph.views import NewRecord class NewRecordViewTests(TestCase): def setUp(self): # Every test needs access to the request factory. self.factory = RequestFactory() self.user = User.objects.create_user( username='jacob', email='jacob@example.com', password='top_secret') permissions = [Permission.objects.get_by_natural_key('add_record', 'graph', 'record'), Permission.objects.get_by_natural_key('add_extend', 'graph', 'extend')] self.user.user_permissions.set(permissions) def test_user_permissions(self): """Tests that a user has been denied permission to add a record.""" for i in range(2): img = BytesIO(b'mybinarydata') fp = StringIO('Auxillary info') img.name = 'myimage.jpg' data = {'name': 'New Record', 'description': 'A new record', 'picture': img, 'content': 'Content', 'files': fp, 'author': self.user} request = self.factory.post('/cascades/add', data=data) request.user = self.user response = NewRecord.as_view()(request) self.assertEqual(response.status_code, 403, "Access should be denied") self.assertFalse(self.user.has_perm('graph.add_record'), "Permission remains") self.assertTrue(self.user.has_perm('graph.add_extend'), "No permission to extend a record") The output: ====================================================================== FAIL: test_user_permissions (graph.tests.NewRecordViewTests) Tests that a user has been denied permission to add a record. ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\pavel\Documents\repos\Artcascade\graph\tests.py", line 34, in test_user_permissions self.assertEqual(response.status_code, 403, "Access should be denied") AssertionError: 200 != 403 : Access should be denied views.py: class NewRecord(LoginRequiredMixin, PermissionRequiredMixin, SuccessMessageMixin, generic.CreateView): model = Record fields = ['name', … -
What are the best practices for getting data through http headers?
I have a backend application where one user can belong to more than one 'organization' and manage these organizations (organization's users' settings vs). I decided to create a middleware where I can catch the organization the user wants to manage and set this organization on the user object. I want to get active organization per request, "request. user. organization". I thought that the react client could send me an HTTP header, and I could get this and make validation. If the user is authorized for this organization, I can set it as an active user organization. What do you think about this approach? -
net::ERR_BLOCKED_BY_RESPONSE.NotSameOriginAfterDefaultedToSameOriginByCoep
I really do not know what exactly I am doing wrong but I need help. My web application works correctly on my localhost but when in production, All external links hosted on AWS are blocked for some reason and I have tweaked everything possible but still no solution. All search, has yielded no results. Failed to load resource MIDDLEWARE MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", 'oauth2_provider.middleware.OAuth2TokenMiddleware', 'core.middleware.SessionTimeoutMiddleware', "django.middleware.http.ConditionalGetMiddleware", "django.middleware.gzip.GZipMiddleware", "django.middleware.locale.LocaleMiddleware", # "core.middleware.SecurityHeadersMiddleware", "django.middleware.security.SecurityMiddleware", "django_permissions_policy.PermissionsPolicyMiddleware", # "core.middleware.ReportUriMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", # "django.middleware.clickjacking.XFrameOptionsMiddleware", "simple_history.middleware.HistoryRequestMiddleware", "django.contrib.admindocs.middleware.XViewMiddleware", 'htmlmin.middleware.HtmlMinifyMiddleware', 'htmlmin.middleware.MarkRequestMiddleware', "django_user_agents.middleware.UserAgentMiddleware", 'waffle.middleware.WaffleMiddleware', ] SETTINGS.PY SESSION_COOKIE_SAMESITE = "Lax" ALLOWED_HOSTS = ["*"] CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', 'HEAD' ] CORS_ALLOW_HEADERS = list(default_headers) + [ 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', 'In', 'access-control-allow-origin' ] CORS CONFIGURATION OF BUCKET [ { "AllowedHeaders": [ "*" ], "AllowedMethods": [ "GET", "HEAD" ], "AllowedOrigins": [ "*" ], "ExposeHeaders": [], "MaxAgeSeconds": 3000 } ] -
Modal Trigger not working after submitting Django Form
I am trying to show a Modal after a Django Form is submitted. I have followed this answer but it did not work the form was successfully submitted but the modal did not appear. I have added the context of successful_submit in the views so that it can be triggered after submitting the form Here is part of the HTML Template: <div class="text-center"> <button class="btn btn-primary mt-5" onclick="stepper1.previous()" > Previous </button> <button type="submit" class="btn btn-success mt-5"> Submit </button> <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true" > <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel"> Modal title </h5> <button type="button" class="btn-close" data-mdb-dismiss="modal" aria-label="Close" ></button> </div> <div class="modal-body">...</div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-mdb-dismiss="modal" > Close </button> <button type="button" class="btn btn-primary"> Save changes </button> </div> </div> </div> </div> {% if successful_submit %} <script type="text/javascript"> $(document).ready(function(){ $("#exampleModal").modal('show'); }); </script> {% endif %} </div> Here is the views.py def add_plan(request): if request.method == 'POST': form = infoForm(request.POST) if form.is_valid(): form.save() name = form.cleaned_data.get('Name') messages.success(request, f'PDF created for {name}!') return render(request, 'plan/plan.html', {'successful_submit': True}) else: form = infoForm() print(form.errors) return render(request, 'plan/plan.html', {'form': form}) -
Django crispy-form FormHelper Field() won't accept 'password' as HTML attr type
I am trying to omit writing a widget attr dict for a password field to set the input type="password" (which BTW works). But I'm trying to set the said attr using FormHelper() and Field() functions. However Field() seems to be taking type as a **kwarg but nothing happens when I pass the "password" value but, e.g. "hidden" works. I have been referencing the docs and looked under the hood but can not seem to wrap my head around this... What am I missing here? Disclaimer, I am new to Django. -
Forms for multiple nested related models in Django
I am developing a website for schoolchildren on a voluntary basis, there are several nested models, that is: I have a Question associated with it 1to1 Comment, and a ForeignKey CoImage associated with Comment (I need the ability to add many illustrations to Comment). To edit the entire Question on one page, I use inlineformset_factory. PROBLEM: when uploading files, for some reason, all images are added to QuImage (these are illustrations to the question that are processed in the same form), even those that were uploaded to CoImage. My forms: from .models import Question, QuImage, Comment, CoImage, CoFile from django.forms import ModelForm, inlineformset_factory class QuestionForm(ModelForm): class Meta: model = Question fields = [ 'year', 'stage', 'grade', 'part', 'number', 'text', 'tags', 'topics', 'flag', 'type'] QuImageFormSet = inlineformset_factory(Question, QuImage, extra = 5, fields=['file', 'label']) CommentFormSet = inlineformset_factory(Question, Comment, extra = 1, fields=['text']) CoImageFormSet = inlineformset_factory(Comment, CoImage, extra = 3, fields=['file', 'label']) My views: def add(request): if request.method == 'POST': addform = QuestionForm(request.POST) question = quicksave(addform) if question: quimageform = QuImageFormSet(request.POST, request.FILES, instance=question) quicksave(quimageform) commentform = CommentFormSet(request.POST, instance=question) comment = quicksave(commentform) if comment: coimageform = CoImageFormSet(request.POST, request.FILES, instance=comment) quicksave(coimageform) return redirect('problems') addform = QuestionForm() quimage = QuImageFormSet() comment = CommentFormSet() coimage = CoImageFormSet() … -
A Simple Calculator using Django
I want to create a website where the user is asked to type a given number to get the square number and the square root. This is from index.html: <div class="d-flex typeW"> <form action="add"> Enter a number : <input type="text" name="num1"> <input type="submit"> </form> </div> This is from the result page (where you can see the result): <div class="d-flex title2"> <h2> {% block content %} {{result}} {% endblock %} <br><br> This is from view: def add(request): num1 = int(request.GET["num1"]) return render(request, 'result.html' , {result2: num1 * num1}) Now I want to take the square root of that number but I'm not sure how. How do I take one input and then do two calculations by using two functions? help much appreciated -
Mounting a virtual environment via SSHFS on local machine using it's Python3 file not working
So I have mounted a part of a development server which hold a virtual environment that is used for development testing. The reason for this is to get access to the installed packages such as Django-rest-framework and Django itself and not having it set up locally (to be sure to use the same version as the development server has). I know that it's perhaps better to use Docker for this, but that's not the case right now. The way I've done it is installing SSHFS via an external brew (as it's no longer supported in the brew core) - via this link https://github.com/gromgit/homebrew-fuse After that I've run this command in the terminal to via SSH mount the specific part of the development server that holds the virtual enviornment: sshfs -o ssh_command='ssh -i /Users/myusername/.ssh/id_rsa' myusername@servername:/home/myusername/projectname/env/bin ~/mnt/projectname It works fine and I have it mounted on my local disk in mnt/projectname. Now I go into VSCode and go into the folder and select the file called "python3" as my interpreter (which I should, right?). However, this file is just an alias, being 16 bytes in size. I suspect something is wrong here, but I'm not sure on how to fix it. Can … -
"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 …