Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cross domain cookie not being sent in the subsequent request even when it is set in the last response
I have my app at app.exampledomain.com which is in reactjs(axios for api call) and it is consuming api from api.exampledomain.com. in the response to an api call the server at api.exampledomain.com is setting the cookie in the response header like: sessionid=fyytiannsv29edvn4zgkr1orfcfscyh3; expires=Sat, 26 Mar 2022 14:02:49 GMT; HttpOnly; Max-Age=604800; Path=/ but in the subsequent requests from app.exampledomain.com the cookie is not being sent in the request header and again set cookie is received in the response header. moreover, the cookie that api sets is not visible in the cookies tab of the browser. I think the browser is rejecting the cookie sent by the server as both the client and server have different subdomains/sites (api.exampledomain.com vs app.exampledomain.com). I want to set cookies having sessionid and this sessionid to be sent in request headers cookies in subsequent requests from app to api. if i make SESSION_COOKIE_DOMAIN = '.example.com' i am able to see the cookie in the browser with domain '.exampledomain.com', still it is not being sent in the subsequent requests and new sessionid is being sent in set cookie in response headers. I tried modifying SESSION_COOKIE_SAMESITE, SESSION_COOKIE_SECURE but it did not help. -
Implementing OAuth Flow with Django+DRF+Vue with JWT
I'm trying to implement Dropbox OAuth Flow on my project, it's working fine without DRF and Vue, when i moved on Vue for my frontend, things get messy. Here are the Django views when only working with Django: (In this scenario all redirect flow happen in same page.) @login_required def dropbox_oauth2_authorize(request): return redirect(DropboxOAuth2Flow( consumer_key=settings.DPX_APP_KEY, redirect_uri=request.build_absolute_uri(reverse('driver:dropbox-callback')), # Belongs to the following view session=request.session, csrf_token_session_key="dropbox-auth-csrf-token", consumer_secret=settings.DPX_APP_SECRET, locale="en", token_access_type="offline").start()) def dropbox_oauth2_callback(request): try: result = DropboxOAuth2Flow( consumer_key=settings.DPX_APP_KEY, redirect_uri=request.build_absolute_uri(reverse('driver:dropbox-callback')), session=request.session, csrf_token_session_key="dropbox-auth-csrf-token", consumer_secret=settings.DPX_APP_SECRET, locale="en", token_access_type="offline").finish( request.GET) cursor = dropbox.Dropbox( oauth2_access_token=result.access_token, oauth2_refresh_token=result.refresh_token, oauth2_access_token_expiration=result.expires_at, app_key=settings.DPX_APP_KEY, app_secret=settings.DPX_APP_SECRET) ... return redirect(reverse('driver:account')) # Redirects account page where authorization started except dropbox.oauth.BadRequestException as e: raise e except dropbox.oauth.BadStateException as e: raise e except dropbox.oauth.CsrfException as e: raise e except dropbox.oauth.NotApprovedException as e: raise e except dropbox.oauth.ProviderException as e: raise e I'm managing authorization in Django with djangorestframework-simplejwt for Vue frontend. Also using axios for DRF. For managing oauth flow on backend (in DRF view), what would you suggest me to do? I tried to get dropbox authorization link via DRF view but it didn't let me open this in new tab, because of CORS headers. Here is the DRF and Vue code: @api_view(['GET']) @permission_classes([permissions.IsAuthenticated & ReadAndWritePermission]) def dropbox_acc_oauth2_authorize(request): return HttpResponseRedirect(DropboxOAuth2Flow( consumer_key=settings.DPX_APP_KEY, redirect_uri=request.build_absolute_uri(reverse('api:user_cloudaccs_dropbox_oauth2_callback', … -
django test a modelform - ValidationError not a valid UUID
I am testing a modelform and getting a ValidationError. My model, view and test are as follows: model class Course(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) course_name = models.CharField(max_length=30) grade_level = models.CharField(max_length=4, default="SEC") view @ method_decorator([login_required, teacher_required], name='dispatch') class CourseUpdateView(PermissionRequiredMixin, UpdateView): raise_exceptions = True permission_required = 'gradebook.change_course' permission_denied_message = "You don't have access to this." model = Course fields = ['course_name', 'grade_level', ] template_name_suffix = '_update' def get_success_url(self, *args, **kwargs): return reverse('gradebook:coursedetail', kwargs={'course_pk': self.object.pk}) form class CourseForm(ModelForm): class Meta: model = Course fields = ('course_name', 'grade_level',) def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.qc = Course.objects.filter(user=user) def clean(self): super(CourseForm, self).clean() course_name = self.cleaned_data.get('course_name') if course_name and self.qc.filter(course_name__iexact=course_name).exists(): raise ValidationError("A course with that name already exists.") if len(course_name) > 20: if len(course_name) > 10: raise ValidationError( "Your course name cannot be longer than 20 characters") return self.cleaned_data Test class CourseUpdateTests(TestCase): @classmethod def setUpTestData(cls): cls.user = CustomUser.objects.create_user( username='tester', email='tester@email.com', password='tester123', is_teacher=True, is_active=True, ) cls.user.save() def test_CourseUpdate_valid(self): request = HttpRequest() request.POST = { 'user': self.user, 'id': '4d192045-07fa-477f-bac2-5a99fe2e7d46', 'course_name': "Science", 'grade_level': "SEC" } form = CourseForm(request.POST) self.assertTrue(form.is_valid()) The error I get: Raise exceptions.ValidationError( django.core.exceptions.ValidationError: ["“{'user': <CustomUser: tester>, 'id': '4d192045-07fa-477f-bac2-5a99fe2e7d46', 'course_name': 'Science', 'grade_level': 'SEC'}” is not a valid UUID."] I have tried … -
JS - function sends 2 POST requests
I have JS function that sends POST request let username = document.querySelector('.fw-user').innerText; if (document.querySelector('.follow')) { let followButton = document.querySelector('.follow'); followButton.addEventListener('click', () => { fetch(`/follow/${username}`, { method: 'POST', }) .then(() => { window.location.reload(); }) }) } urls.py path("follow/<creator>", views.follow, name="follow") views.py @csrf_exempt @login_required def follow(request, creator): if request.method == "POST": get_acc_id = User.objects.get(username=request.user.username) get_creator_name = User.objects.get(username=creator) follow = Followers.objects.create(follower_id=get_acc_id.id, creator=get_creator_name.username) get_creator_name.followers += 1 get_creator_name.save() return HttpResponse(status=204) html <button type="button" class="follow btn btn-outline-light btn-sm">Follow</button> When i press this button, function sends 2 POST requests, instead of 1. Screenshots: Network Console -
Rebuilt indices not showing in elasticsearch
I'm using django-elasticsearch-dsl and recently added a model field to my index but could not get elasticsearch to update the index. So, I deleted the index using CURL: curl -XDELETE localhost:9200/[index] I've rebuilt and repopulated and it looks like everything was deleted, created and indexed: $ python manage.py search_index --rebuild --refresh But I'm getting a 'index_not_found_exception' when running: curl -XGET localhost:9200/[index]/ -
Reuseable form on CreateView
Trying reuse form_class in CreateView i get the error: Field 'id' expected a number but got 'cadastrar-imovel' Where: urls.py urlpatterns = [ #... path('cadastrar-imovel/',ProductCreateView.as_view(),name='product_create'), #... models.py (I use default id field), i suspect the problem is in get_absolute_urlmethod, idk... class Product(models.Model): #...commom fields def __str__(self): return self.slug or '' @property def fn_product_title_seo(self): self.product_title_seo = self.product_goal.capitalize() + " " + self.product_type + " " + self.product_status + " " + self.product_district.title() + " " + self.product_room + " dorms" return self.product_title_seo def get_absolute_url(self): return reverse('product_change', kwargs={'slug': self.slug, 'pk': self.pk}) def save(self, *args, **kwargs): self.product_title_seo = self.fn_product_title_seo self.product_title = self.product_title.capitalize() self.slug = slugify(self.product_title_seo) return super().save(*args, **kwargs) forms.py class ProductForm(ModelForm): #...commom fields definitions class Meta: model = Product fields = [#...fields views.py class ProductCreateView(CreateView): form_class = ProductForm template_name = 'product_create.html' This model and form work in admin when user i logged, but i need use the same combo to create product without login user, and after all fields are filled, i gona signup that new user(is other step). All tips are welcome -
Render DjangoCKEditor in React CKEditor
I would like to know whether it is possible to render RichTextField from Django CKEditor using CKEditor from ckeditor5-react ? As far as I know, we could manually render django field in anyway as long as the name and id is the same as the form field. But I have no idea how do I replicate Django CKEditor using React CKEditor. -
Model.Form Queryset
I have a model.form which I need to apply a queryset to filter the choices available within a select field. class AnswerForm(ModelForm): class Meta: model = ProjectQuestionnaireAnswer fields = ('answer','notes') widgets = { 'answer': forms.Select(choices = Choice.objects.filter(question_id = 1),attrs={'class': 'form-control select2'}), 'notes': forms.Textarea(attrs={'class': 'form-control','placeholder': 'Add notes to question here'}), } class Choice(models.Model): question = models.ForeignKey(ProjectQuestionnaireQuestion, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) def __str__(self): return str(self.choice_text) I'm not sure how to write the query to only return the choices related to the question. I've tested with choices = Choice.objects.filter(question_id = 1) which does return me the choices for question 1, but need it for each question? And then how do I present this in my template? {{ form.answer.choices }} ?? Thanks -
How to get table data (including child table and sub child data) based on id which obtains from another table data? Django
views company = Company.objects.get(id = company_id) # getting input from django urls (<int:company_id>) vehicles = CompanyContainVehicles.objects.filter(company_id=company.id) # Give all rows having same id (company.id) all_vehicles = Vehicle.objects.filter(companies=company) # Gives all row with id provide by company all_vehicles_parts = VehiclePart.objects.filter(__________) # Not Working models class Company(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(blank=True, null=True, unique=True) description = models.TextField() class Vehicle(models.Model): vehicle_number = models.IntegerField() name = models.CharField(max_length=255) slug = models.SlugField(blank=True, null=True, unique=True) companies = models.ManyToManyField( Company, through='CompanyVehicle', related_name='companies' ) class CompanyVehicle(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) class VehiclePart(models.Model): id = models.AutoField(primary_key=True) vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) type = models.ForeignKey(PartType, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True, blank=True) How do I get VehiclePart's with their Vehicle? (I think I will give all the data in a variable and we should divide it and add it with their Vehicle). Also, what can we do to access data if VehiclePart contains a child class named VehiclePartDetail? -
Unable to fetch model data in Django Async conusmers . working in channels and websockets
I am working on a chat application with channels and websockets using async programming. I am unable to get the model data / object in consumers.py but able to create one . As someone in the group sends the message , it is echoed to the whole group but not saved and thus is flushed after the page is refreshed . I want to save the message in the database as the message is sent to the group using websockets . But I am facing problem. This is my consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer from asgiref.sync import sync_to_async from django.contrib.auth.models import User from chat.models import ChatMessage , ChatRoom from channels.db import database_sync_to_async class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.roomId = self.scope['url_route']['kwargs']['roomId'] self.room_group_name = 'chat_group_%s' % self.roomId await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self , close_code): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json["message"] username = text_data_json["username"] roomId = text_data_json["roomId"] roomName = text_data_json["roomName"] await self.save_message(message , username , roomId , roomName) await self.channel_layer.group_send( self.room_group_name, { 'type': 'the_message', 'message': message } ) async def the_message(self, event): message = event['message'] await self.send(text_data=json.dumps({ 'message': message })) @sync_to_async def save_message(self , message , username … -
Not all files called with django static appear
I have index.html file in template file and I have js, css, image, files in my static file. I am writing the codes correctly, but the site does not appear properly. Animations, images and text are not in the correct place. (In fact, the logo of the project I used to work with appears in this project. Both are called "logo.png", I think pycharm is confusing the codes. But I opened my project with Visual Studio Code, and the logo of my old project appeared again. Why is this happening? Do I need to delete something?) settings.py STATIC_URL = 'static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] index.html <!DOCTYPE html> {% load static %} <html lang="en"> <!-- Basic --> <head> <link rel="shortcut icon" href="{% static 'images/favicon.ico' %}" type="image/x-icon"> <link rel="apple-touch-icon" href="{% static 'images/apple-touch-icon.png' %}"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> <!-- Site CSS --> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <!-- Responsive CSS --> <link rel="stylesheet" href="{% static 'css/responsive.css' %}"> <!-- Custom CSS --> <link rel="stylesheet" href="{% static 'css/custom.css' %}"> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <!-- ALL JS FILES --> <script src="{% static 'js/jquery-3.2.1.min.js' %}"></script> <script src="{% static 'js/popper.min.js' %}"></script> <script src="{% static … -
How to make Dropdown with input field in django form
I am a noob to django and python 😥 I have a django form, it needs a dropdown menu with input field to enter the text which is not listed in dropdown. Is there any shortcut method for it? -
Why must I use Function-based views if there is Class-based?
From the Django Documentation In the beginning there was only the view function contract, Django passed your function an HttpRequest and expected back an HttpResponse. This was the extent of what Django provided. Early on it was recognized that there were common idioms and patterns found in view development. Function-based generic views were introduced to abstract these patterns and ease view development for the common cases. The problem with function-based generic views is that while they covered the simple cases well, there was no way to extend or customize them beyond some configuration options, limiting their usefulness in many real-world applications. Class-based generic views were created with the same objective as function-based generic views, to make view development easier. However, the way the solution is implemented, through the use of mixins, provides a toolkit that results in class-based generic views being more extensible and flexible than their function-based counterparts.strong text -
Formset not submitting uploaded picture?
I have a view to allow courses to created by users on my app, which am currently having a challenge uploading a course cover(pic) when users create a new course, when course is created all the fields of the course detail get submitted to the data base except the picture data, why is the picture not being submitted, can some one please help me. as this has been a challenge for me for the past week! This is my view to create a new course!. class OwnerMixin(object): def get_queryset(self): qs = super(OwnerMixin, self).get_queryset() return qs.filter(owner=self.request.user) class OwnerEditMixin(object): def form_valid(self, form): form.instance.owner = self.request.user return super(OwnerEditMixin, self).form_valid(form) class OwnerCourseMixin(OwnerMixin): model = Course fields = ['subject', 'title', 'slug','overview','pic'] success_url = reverse_lazy('courses:manage_course_list') class OwnerCourseEditMixin(OwnerCourseMixin): fields = ['subject', 'title','slug', 'overview','pic'] success_url = reverse_lazy('courses:manage_course_list') template_name = 'manage/module/formset.html' class ManageCourseListView(OwnerCourseMixin,ListView): template_name ='courses/course_list.html' class CourseCreateView(OwnerCourseEditMixin,OwnerEditMixin,CreateView,): pass permission_required = 'courses.add_course' class CourseModuleUpdateView(TemplateResponseMixin, View): template_name = 'manage/module/formset.html' course = None def get_formset(self, data=None,): return ModuleFormSet(instance=self.course,data=data,) def get_form(self, data=None): return RequirementFormset(instance=self.course,data=data) def get_forms(self, data=None): return WhatYouWillLearnFormset(instance=self.course,data=data) def dispatch(self, request, pk): self.course = get_object_or_404(Course,id=pk,owner=request.user) return super(CourseModuleUpdateView, self).dispatch(request, pk) def get(self, request, *args, **kwargs): formset = self.get_formset() form = self.get_form() forms = self.get_forms() return self.render_to_response({'course':self.course, 'formset':formset,'form':form,'forms':forms,}) def post(self, request, *args, **kwargs): formset … -
Update in Nested serializer. not turning off validators. E: this slug already exists
I've made a nested serializers which has slugs in both models. Now I learn that in order to be able to do the update on (unique=True) I need to turn off the validator. But somehow I can't seem to turn it off and it'S still throwing the same error. Any way I should be approaching on this problem? serializers.py from rest_framework import serializers from .models import Question, Answer class AnswerSerializer(serializers.ModelSerializer): """Serialize Answer model""" class Meta: model = Answer fields = ('title', 'body', 'slug', 'author', 'question') # https://stackoverflow.com/questions/57249850/overwriting-nested-serializers-create-method-throws-typeerror-create-got-mul read_only_fields = ('question',) lookup_field = 'slug' # https://stackoverflow.com/questions/55031552/how-to-access-child-entire-record-in-parent-model-in-django-rest-framework class QuestionSerializer(serializers.ModelSerializer): """Serialize Question model""" #This answer variable and the fields 'answer' you refer to has to be the SAME but #These can change exp: 'aaa' answer = AnswerSerializer(read_only=False, source='answers', many=True,) class Meta: model = Question fields = ('title', 'body', 'slug', 'author', 'category', 'answer',) lookup_field = 'slug' def create(self, validated_data): answers_data = validated_data.pop('answers') question = Question.objects.create(**validated_data) for answer_data in answers_data: #The above stackoverflow link at the answer serializers is realted to this Answer.objects.create(question=question, **answer_data) return question def update(self, instance, validated_data): instance.title = validated_data.get('title', instance.title) instance.body = validated_data.get('body', instance.body) instance.slug = validated_data.get('slug', instance.slug) instance.author = validated_data.get('author', instance.author) instance.category = validated_data.get('category', instance.category) instance.save() # https://django.cowhite.com/blog/create-and-update-django-rest-framework-nested-serializers/ answers_data = … -
django celery with multi Q and autoscale
i am try to run celery container in production with autoscale and multi Q as the container entry point as follow **entrypoint.sh** celery -A app worker --autoscale=100,3 -Q mails,index,mixed --loglevel=info but not scaling over 2 workers and only first Q receiving tasks .Also clouds watch log does not shows any logs -
Displaying data from a column of my dataframe in a web page
I want to display the rows of a column of my dataframe in a web page. I get an error on the following line: return render(requete, 'analyse/index.html', context={'data': df['EXTERNAL_DATA2'].tolist()}) below is the error that is displayed: TypeError: list indices must be integers or slices, not str thank you in advance for your help -
How can I get profile picture?
The profile picture is uploading in the database but I can't get the profile picture in the template. How can get the profile picture? Profile Picture View: def change_profile_picture(request): if request.user.is_authenticated: if request.method == "POST": profile_picture = request.FILES['profile_picture'] if 'profile_picture' in request.FILES else None user = get_object_or_404(User, pk=request.user.pk) if request.user.pk != user.pk: messages.success(request,f"{request.user.first_name}, Your profile picture not updated") return redirect("/") Profile_picture.objects.create( Profile_picture = profile_picture, USer = request.user, ) messages.success(request,f"{request.user.first_name}, Your profile picture updated") return redirect("/") return render(request,'0_index.html') Model: class Profile_picture(models.Model): USer = models.ForeignKey(User,default=None,on_delete=models.CASCADE) Profile_picture = models.ImageField(upload_to="3_profile_picture/",null=True, blank=True) def __str__(self): return str(self.pk)+ str(".") + str(self.USer) Template: <form action="change_profile_picture/" method="POST" class="" enctype="multipart/form-data"> {% csrf_token %} <img src="{{ request.user.3_profile_picture }}" alt="" width="100" class="img-fluid rounded-circle mb-3 img-thumbnail shadow-sm"> <input type="file" required name="profile_picture" class="profile_picture_upload"> <button class="btn profile_picture_submit_btn" type="submit">submit</button> </form> -
Unable to create process using 'C:\Users\ibsof\AppData\Local\Microsoft\WindowsApps\python.exe manage.py runserver'
I'm trying to use runserver command over pycharm code terminal. But now it is giving me the error. " Unable to create process using Unable to create process using 'C:\Users\ibsof\AppData\Local\Microsoft\WindowsApps\python.exe manage.py runserver' . But I have the python interpreter in my environment path. Also, I have my virtual environment which I created while initiating the project but still and using the interpreter in my environment I was getting the same error.. -
Why I am getting a single array object instead of all array values in Django rest framework?
I am using Django rest framework for API and pandas to parse excel file. But my Django model takes only the last row of excel file and returns it. I want all rows to be posted and returned. Here is my code. models.py class BusinessImpact(models.Model, ModelWithCreateFromDict): client = models.ForeignKey( accounts_models.Client, on_delete=models.CASCADE) business_process = models.ForeignKey( BusinessProcess, on_delete=models.CASCADE) hierarchy = models.CharField(max_length=255) business_assets = models.CharField(max_length=255) asset_name = models.CharField(max_length=255) vendors = models.CharField(max_length=255) product = models.CharField(max_length=255) version = models.CharField(max_length=10) cpe = models.CharField(max_length=255) asset_type = models.CharField(max_length=10) asset_categorization = models.CharField(max_length=255) asset_risk = models.CharField(max_length=50) _regulations = models.TextField(blank=True) _geolocation = models.TextField(blank=True) def __str__(self) -> str: return self.hierarchy + " - " + self.business_assets @property def regulations(self) -> List[str]: return self._regulations.split(",") @property def geolocation(self) -> List[str]: return self._geolocation.split(",") excel_titles = { "hierarchy": "Hierarchy", "business_assets": "Business Assets", "asset_name": "Asset Name", "vendors": "Vendors", "product": "Product", "version": "Version", "cpe": "CPE", "asset_type": "Asset Type", "asset_categorization": "Asset Categorization", "asset_risk": "Asset Risk", "_regulations": "Regulations", "_geolocation": "GeoLocation", } important_fields = ["hierarchy", "business_assets", "asset_name"] views.py class UploadBusinessImpactExcelByClientAdmin(APIView, ExcelHandlingView): def post(self, request): self.can_model_handle_ExcelHandlingView(models.BusinessImpact) serializer = serializers.ExcelFileAndBusinessProcessUploader( data=request.data) if serializer.is_valid(): data = serializer.validated_data file = data.get("file") client = request.user.client business_process_id = data.get("business_process") try: business_process = get_business_process_by_client( client, business_process_id ) except ( models.BusinessProcess.DoesNotExist, accountModels.Client.DoesNotExist, ) as e: return Response( "business process … -
Specifying a namespace in include() without providing an app_name ' django.core.exceptions.ImproperlyConfigured: Specifying a namespace
I'm a beginner in Django, this is my code: from django.contrib import admin from django.urls import path from django.urls import include, re_path app_name="myproject" urlpatterns = [ path('admin/', admin.site.urls), re_path(r'', include('learning_logs.urls', namespace='learning_logs')) ] I need you guys help!!! I'm having this error....please help me.... 'Specifying a namespace in include() without providing an app_name ' django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. -
django multiple image upload
Hi I am pretty new to Django and trying to let the user upload multiple images per project. The Django Documentation enter link description here shows how to do it in generell but I think I am rendering my form differently than they are doing it. So I don´t know how to add the 'multiple' attribute in my input field. In addition they have an extra class in their views.py and inside of that the function. Thanks for your help. views.py def createProject(request): form = ProjectForm() if request.method == 'POST': form = ProjectForm(request.POST, request.FILES) if form.is_valid(): project = form.save(commit=False) project.save() context = {'form':form} return render(request, 'projects/project_form.html', context) models.py class Project(models.Model): title = models.CharField(max_length=200) featured_images = models.ImageField(null=True, blank=True, default="default.jpg") forms.py class ProjectForm(ModelForm): class Meta: model = Project fields = ['title', 'featured_images'] project_form.html <form class="form" method="POST" enctype="multipart/form-data"> {% csrf_token %} {% for field in form %} <div class="form__field"> <label for="formInput#text">{{field.label}}</label> {{field}} </div> {% endfor %} </form> -
Using a local Django app without packaging it
I'm planning to write an add-on app for an existing django app. The primary app is running smoothly via docker-compose, and I've remoted into the container via the vscode remote-containers extension. Add-ons are installed like most any other django app, pip install APPNAME, append to INSTALLED_APPS, migrate, collectstatic, restart server. I can create a directory anywhere in the container, where the add-on will exist and be developed, but I'm looking for a way to make the app visible from that directory so I can include it in the primary app's INSTALLED_APPS list. Is this possible, or would I have to create the app inside the primary package's site-packages directory alongside its own sub-apps for this to work? -
expected bytes or bytearray, but got 'NoneType' in Django
I recieve a response from a payment gateway(paystack) and am trying to verify that events originate from Paystack to avoid delivering value based on a countefeit event. I have the error below anytime i get the respone from them raise TypeError("key: expected bytes or bytearray, but got %r" % type(key).__name__) TypeError: key: expected bytes or bytearray, but got 'NoneType' Views.py @require_POST @csrf_exempt def webhook(request): secret = getattr( settings, ' PAYSTACK_PRIVATE_KEY', None ) webhook_data = request.body hash = hmac.new(secret, webhook_data, digestmod=hashlib.sha512).hexdigest() if hash != request.headers["HTTP_X_PAYSTACK_SIGNATURE"]: raise ValidationError("MAC authentication failed") response_data = json.loads(request.body) return HttpResponse(status=200) You can take a look at the paysatck API webhook doc here: https://paystack.com/docs/payments/webhooks/#verifying-events -
Restricting view by model permissions fails in django
Very basically I have a model member and want to restrict searching members to allowed users. I use the following in the corresponding view if request.user.has_perm('view_member'): context['user_list'] = get_user(q) Sadly this does not work even if a) I give a user this permission via the admin interface b) in my tests that look a bit like the following def test_user_search_view(self): self.client.login(username='testuser0', password='12345') # this is a user that was given the permission (see below) response = self.client.post(reverse('library:search'), data={'q': "Müller"}) # Check our user is logged in self.assertEqual(str(response.context['user']), 'testuser0') # Works self.assertContains(response, "Max") # Fails, but max shouls be there For further tests I used the debugging mode of PyCharm to go into the test. In the console I then executed the following >>> permission_view_user = Permission.objects.get(codename='view_member') >>> test_user0.user_permissions.add(permission_view_user) >>> test_user0.save() # For good luck >>> user = get_object_or_404(User, pk=test_user0.pk) >>> user.has_perm(permission_view_user) False I would expect true here.