Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django. OneToOneField. Reverse relation by related_name raise AttributeError
I have model class ClientBid(models.Model): bid = models.OneToOneField(Bid, verbose_name=_('Bid'), on_delete=models.CASCADE, related_name='client_bid') ... When I do the next, I am getting error: bid = Bid.objects.first() bid.client_bid # or bid.clientbid, does not matter ... AttributeError: 'Bid' object has no attribute 'client_bid' Buuuut, when I do something like that: ClientBid.objects.all() bid = Bid.objects.first() bid.client_bid <ClientBid: ClientBid object (1)> All works fine. Why? and how to fix this ? -
how to allow f() to take decimal values
Firstly, I need to sum the student mark before converting it to a percentage. So Ive managed to sum up their mark and somehow managed to convert it to percentage thru this method. students = MarkAtt.objects.values('studName__VMSAcc').annotate(mark=Sum('attendance'), percentage=(F('mark')/1100) * 100) However, I realised that the F() does not take decimal value. It only takes the integer value. This would cause an error to my percentage calculation if the value 'mark' is less than 100. For example: 600/1100 = 0.54545 then it will only take 0 to multiple with 100. And output '0' instead of 54%. How do I allow the function take decimal value? -
django html - require help in POST method from html template to views.py in json format
I want help in knowing who can I pass a values in array from html template to views.py below is my template snapshot <input type="hidden" name="parameter_name" value="{% parameter_list %}" /> parameter_list is a array(list) which I want to pass it to views.py In the current situation, it is been passed as a string. Which is creating issues in my future requirement of that field. I want this to be passed as array(list). I tried JSON.stringfy() but it didn't work. Request someone to help me in this. -
How to get a variable value to populate dropdown in Django
How to get the value of a variable in a Django view. I would like to select the value of an option and use it as a foreign key in another model. However, I can't get the value, just the text of the #prova variable. views.py def getQuestao(request): if request.method == 'GET' and request.is_ajax(): idProva = request.GET.get('prova', None) print("ajax idProva ", idProva) result_set = [] todas_questoes = [] answer = str(idProva) print('answer = ', answer) questoes_selecionadas = Questao.objects.get(idProva=answer) print("cities are: ", questoes_selecionadas) todas_questoes = questoes_selecionadas.questoes.all() print("cities are: ", todas_questoes) for questao in questoes_selecionadas: print("questao name", questao.idQuestao) result_set.append({'name': questao.idQuestao}) return HttpResponse(simplejson.dumps(result_set), content_type='application/json') # return JsonResponse(result_set,status = 200) else: return redirect('/') index.html <select id="prova" class="form-control" name="prova"> <option value='' selected>Prova</option> {% for prova in provas %} <option value="{{ prova.idProva }}">{{ prova.tipoProva }} {{prova.anoProva}}</option> {% endfor %} </select> <select id="questao" class="form-control" name="questao"> <option value='' selected>Questão</option> </select> <script>$(document).ready(function(){ $('select#prova').change(function () { var optionSelected = $(this).find("option:selected"); var idProva = optionSelected.val(); data = {'prova.form-control.val()' : idProva }; $.ajax({ type:"GET", url:'/getCity', // data:JSON.stringify(data), data:data, success:function(result){ console.log(result); $("#questao.form-control option").remove(); for (var i = result.length - 1; i >= 0; i--) { $("#questao.form-control").append('<option>'+ result[i].idQuestao +'</option>'); }; }, }); }); </script> -
How to implement many to many field django api filter in React Js?
Here i am trying to get data from django backend api and here i have many to many field filter like user=1,2 S how i will implement this is react js i am also attaching code here it is api working localhost link http://localhost:8000/api/1/deliveries/report/?user=1,2 like this working in backend and i am trying to select 2 user from multiple select field but i am getting output of only one field And here is React Js Code getData = async e => { try { const idd = e.target.elements.idd.value; e.preventDefault(); const res = await fetch( `http://localhost:8000/api/1/deliveries/report/?user=${idd}` ); const movies = await res.json(); console.log(movies); this.setState({ movies: movies.results }); } catch (e) { console.log(e); } }; and here is select from where i select user <label>Select Walk</label> <select multiple className="form-control btn-block" id="exampleFormControlSelect2 btn-block" style={{ width: "200px", color: "rgba(19, 183, 96, 1.0)" }} name="idd" > {this.state.movies.map(c => ( <option value={c.user}>{c.user1}</option> ))} </select> -
Pass a model from a view to form's inner Meta class
I want to pass a specific model from my view to my form's inner Meta class: view: @login_required def product_create_view(request): if request.method == 'POST': create_product_form = CreateProductForm(request.POST, request=request, model=model) if create_product_form.is_valid(): create_product_form.save() else: create_product_form = CreateProductForm(request=request, model=model) return render(request, 'products/product_create.html', {'form': create_product_form}) form: class CreateProductForm(ModelForm): class Meta: model = CreateProductForm.model fields = ( 'title', 'description', 'price', 'stock', 'category' ) def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') self.model = kwargs.pop('model') super().__init__(*args, **kwargs) Is that possible? -
How to use model clean method in django and iterate over fields
I asked a question and, as I have read a little, I now can better express what I need: How to do model level custom field validation in django? I have this model: class StudentIelts(Model): SCORE_CHOICES = [(i/2, i/2) for i in range(0, 19)] student = OneToOneField(Student, on_delete=CASCADE) has_ielts = BooleanField(default=False,) ielts_listening = FloatField(choices=SCORE_CHOICES, null=True, blank=True, ) ielts_reading = FloatField(choices=SCORE_CHOICES, null=True, blank=True, ) ielts_writing = FloatField(choices=SCORE_CHOICES, null=True, blank=True, ) ielts_speaking = FloatField(choices=SCORE_CHOICES, null=True, blank=True, ) and have this model form: class StudentIeltsForm(ModelForm): class Meta: model = StudentIelts exclude = ('student') def clean(self): cleaned_data = super().clean() has_ielts = cleaned_data.get("has_ielts") if has_ielts: msg = "Please enter your score." for field in self.fields: if not self.cleaned_data.get(str(field)): self.add_error(str(field), msg) else: for field in self.fields: self.cleaned_data[str(field)] = None self.cleaned_data['has_ielts'] = False return cleaned_data What I am doing here is that checking if has_ielts is True, then all other fields should be filled. If has_ielts`` isTrueand even one field is not filled, I get an error. Ifhas_ielts`` is False, an object with has_ielts=False and all other fields Null should be saved. I now want to do it on the model level: class StudentIelts(Model): SCORE_CHOICES = [(i/2, i/2) for i in range(0, 19)] student = OneToOneField(Student, on_delete=CASCADE) … -
Finding difference of count of records using aggregation
I'm given a task to write this code into one query using aggregation/annotation. I tried using the count and stuff but I don't have any idea how this works upvotes = UserVote.objects.filter(blog=self, vote_type='U').count() downvotes = UserVote.objects.filter(blog=self, vote_type='D').count() return upvotes - downvotes -
How to get List From aettings.py to view in python?
I try to get list from settings.py to in view. but i got error 'Settings' object has no attribute 'DEFAULT_ROLES' but i define as you see settings.py variable. anyone know whats issue ? settings.py ---------------- DEFAULT_ROLES = ["ROLE_MANAGE_ALL_CONTACT", "ROLE_MANAGE_ALL_CALENDAR"] Views ----------- from django.conf import settings def register(request): util = Utils() print(settings.DEFAULT_ROLES) -
How to send end-user ip address with the youtube-dl request and get video download link. or there is another way to not get blocked by youtube
currently working on a youtube video downloader . using youtube-dl,Django and hosting my project on Pythonanywhere,i almost completed my project but when i send request more then 15-20 youtube block my pythonanywhere server ip. SO i want to ask that how can i solve this blocking problem. free proxies takes too much time to respond. please give me a solution.thanks in advance -
django model.objects.filter for loop doesn't loop through all records
this weird thing happened to me, I'm trying to loop through a bunch of records I got from database, the value of print(next_ghanoons.count()) is 190 but the thing printed in for loop is 0 1 2,... and i goes till 106 and never reaches 190 records what's wrong with my code @staticmethod def get_next(obj): current_section = obj.id_section current_id_book = obj.id_section.id_book.id_book next_order = obj.order + 1 try: next_ghanoons = Ghanon.objects.filter(order=next_order) except ObjectDoesNotExist: return None print(next_ghanoons.count()) i = 0 for ghanoon in next_ghanoons: i = i + 1 print(i) -
logged out and then hit back button and i am able to see the previous page
logged out and then hit back button and i am able to see the previous page Here is my code from django.views.decorators.cache import cache_control @cache_control(no_cache=True, must_revalidate=True, no_store=True) def logout_user(request): logout(request) return HttpResponseRedirect('/login') @login_required(login_url='/login/') def index(request): return render(request, 'index.html') -
Serving a different ModelForm based on selected category
I am making a page for adding products to the webshop by the user, and I have made chained dependent combobox selection, where you start with one combobox for main product category and once you select a main category, another <select> appears for selecting a subcategory, and so on until the innermost (most specific) subcategory is selected. This currently works as follows: whenever a value in a combobox is changed, two AJAX requests are fired. First one calls a view that renders another <select> if a category has children, otherwise returns an HttpResponse which stops attaching the listener. Second one calls a view that renders a different ModelForm if selected category is root node (main category), otherwise returns an HttpResponse which says not to render another ModelForm. I want to serve a different ModelForm based on selected main category. So, say if there are two main categories, Books and Shoes, if you select Books, BookModelForm should appear and the product should be saved as a Book. I have serving the different ModelForm part implemented, however the problem is product_create_view itself and saving the product to the database. This is my views.py: mappings = { '1': BookProductForm, '2': ShoesProductForm } def … -
Django: Form submit wrong value when using inputs with same name?
I'm using custom form: <form method="POST" action="." id="utf_add_comment" class="utf_add_comment"> {% csrf_token %} <div id="utf_add_review" class="utf_add_review-box"> <h3 class="utf_listing_headline_part margin-bottom-20">Add Your Review</h3> <span class="utf_leave_rating_title">Your email address will not be published.</span> <div class="row"> <div class="col-md-6 col-sm-6 col-xs-12"> <div class="clearfix"></div> <div class="utf_leave_rating margin-bottom-30"> <input type="radio" name="rating" id="rating-1" value="1"> <label for="rating-1" class="fa fa-star"></label> <input type="radio" name="rating" id="rating-2" value="2"> <label for="rating-2" class="fa fa-star"></label> <input type="radio" name="rating" id="rating-3" value="3"> <label for="rating-3" class="fa fa-star"></label> <input type="radio" name="rating" id="rating-4" value="4"> <label for="rating-4" class="fa fa-star"></label> <input type="radio" name="rating" id="rating-5" value="5"> <label for="rating-5" class="fa fa-star"></label> </div> <div class="clearfix"></div> </div> </div> <button type="submit" class="button">Submit Review</button> <div class="clearfix"></div> </div> </form> views.py: if request.method == 'POST': print(request.POST) How these inputs looks: So if I submit form, like picture (with 2 marked stars) it returns me 4. If I marked only one star, it returns me 5, 4 = 2 etc.. I'm not quite sure, that this is problem from code above or it comes from js plugin. -
How to get many to many fields filter in django rest-framework?
I want to filter my data like localhost:8000/api/1/deliveries/report/?user=1,2 Many to many field not like only one field i am trying to do but i could not please help me Here is Views.py class ReportView(generics.ListCreateAPIView): queryset = Delivery.objects.all() serializer_class = serializers.DeliverySerializer filter_backends = [DjangoFilterBackend] filter_fields = { 'too': ['lte'], 'fromm': ['gte'], 'electric_bike': ['exact'], 'mode': ['exact'], 'user': ['exact'], } And here is Serializer.py class ReportSerializer(serializers.ModelSerializer): class Meta: model = Delivery fields = '__all__' I am only getting only one user filter http://localhost:8000/api/1/deliveries/report/?user=1 like this -
Request body is not being passed from axios get call to back end
I have an issue while sending get request with a body in axios. It does not pass the body of the request to the backend. Axios code looks like below const FunctionName = (environment, page_num) => { axios.get(API_URL, { params: { environment, page_num }, }).then(res => { console.log(res); }).catch(err => { console.log(err.response.data); }); } I'm using Django as my backend and I'm receiving empty body i.e {} which causes bad request sent to the backend. I went through several stack overflow questions but none of them helped me. Can anyone please help me with this. Update My django code looks like below class TestView(APIView); def get(self, request): environment = request.data['environment'] page_num = request.data['page_num'] ... ... Here when I'm unable to get the environment or page_num data. The same request when I send from postman with the get call and content in the request of the body, it accepts and sends the response back. -
Django 'runserver' command is producing an error
the following error is produced when I use the 'runserver' command: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 60, in execute super().execute(*args, **options) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 67, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/conf/__init__.py", line 79, in __getattr__ self._setup(name) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/conf/__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/conf/__init__.py", line 157, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'blog' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 336, in run_from_argv connections.close_all() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/utils.py", line 219, in close_all for alias … -
django problem with shared memcache nodes
i have two django instances running on two servers and i am using memcached to cache some data in my applicationa. each server have it's own memcached installed, i want to both of my applications have access to both caches but i cant't. when i set a values from one application in cache other application cant access it my memcached instances are running as root, also i have tried memcache and other users but it didn't fix the problem. for testing i used django shell, import cache class: from django.core.cache import cache set a value in cache : cache.set('foo', 'bar', 3000) and tried to get value from my other dajngo instance : cache.get('foo') but it returns nothing! here is my settings.py file : CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache', 'LOCATION': [ 'first app server ip:port', 'second app server ip:port'] } } and my memcached.conf(comments deletede): -d logfile /var/log/memcache/memcached.log # -v -vv -m 512 -p 11211 -u root -l 192.168.174.160 # -c 1024 # -k # -M # -r -P /var/run/memcached/memcached.pid -
Django MultiValueKeyDictError in forms.py while filtering queryset
I am trying to filter a queryset in forms.py such that a specific author (1:1 relationship with the built in django User) can only view characters 'owned' by them. When I try to filter by anything other than the author, everything works fine. When I filter by author, the form initially loads correctly but upon POST I get a MultiValueKeyDictError. Here's the error text: MultiValueDictKeyError at /rmi/1/post/new 'cur_author' Request Method: POST Request URL: http://127.0.0.1:8000/rmi/1/post/new Django Version: 3.0.dev20190323160439 Exception Type: MultiValueDictKeyError Exception Value: 'cur_author' Exception Location: c:\users\user\desktop\learnpython\django\django\utils\datastructures.py in __getitem__, line 78 Python Executable: C:\.virtualenvs\djangodev\Scripts\python.exe Python Version: 3.7.2 Python Path: ['C:\\Users\\USER\\Desktop\\rmi', 'C:\\Users\\USER\\AppData\\Local\\Programs\\Python\\Python37\\python37.zip', 'C:\\Users\\USER\\AppData\\Local\\Programs\\Python\\Python37\\DLLs', 'C:\\Users\\USER\\AppData\\Local\\Programs\\Python\\Python37\\lib', 'C:\\Users\\USER\\AppData\\Local\\Programs\\Python\\Python37', 'C:\\.virtualenvs\\djangodev', 'C:\\.virtualenvs\\djangodev\\lib\\site-packages', 'c:\\users\\user\\desktop\\learnpython\\django'] views.py @login_required def create_thread(request, board_id): board_style = 'css/board' + str(board_id) + '.css' cur_author = get_object_or_404(Author, user=request.user) if request.method == "POST": form = CreatePost(request.POST) if form.is_valid(): post = form.save(commit = False) post.board = get_object_or_404(Board, pk=board_id) post.created_at = timezone.now() post.parent = None post.save() return redirect('board', board_id) else: data ={ 'cur_author': cur_author, } form = CreatePost(data) context ={ 'form': form, 'board_id': board_id, 'board_style': board_style, } return render(request, 'rmi/create_post.html', context) and this is forms.py: class CreatePost(forms.ModelForm): class Meta: model = Post fields = ['character', 'title', 'content', 'parent'] widgets = {'parent': forms.HiddenInput()} def __init__(self,cur_author): super(CreatePost, self).__init__(cur_author) self.fields['character'].queryset = Character.objects.filter(author=cur_author['cur_author']) … -
Django 404: No object instance found matching the query
I'm trying to create a detail view for specific car instances in my project. I've just created a slug that passes each car's unique UUID into the url, but Django raises a 404 Error. It can't find the specific instance, but the urls are accurate and the url accurately matches the id. Also, I'm clicking in from the ListView which works fine. Error screenshot in browser ID confirmation from object admin page models.py class CarInstance(models.Model): .... id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="Unique ID for this car") ... class Meta: ordering = ['date_added'] def __str__(self): return f'{self.manufacturer} {self.car_model}' def get_absolute_url(self): return reverse('showroom:car-detail', args=[str(self.pk)]) urls.py urlpatterns = [ ... path('car/<slug:car_detail>/', views.CarDetailView.as_view(), name='car-detail') ] views.py class CarDetailView(generic.DetailView): model = CarInstance template_name = 'car_detail' slug_field = 'car_model' slug_url_kwarg = 'car_detail' def get_queryset(self): return CarInstance.objects.all() -
TokenAuthentication object has no attribute 'get_user'
I'm trying to authenticate a user with an Authorization header containing a token generated by django-rest-knox. I also have two other authentication backends. To do this, I call the authenticate() method defined in knox.auth. However, it returns this error and fails to authenticate the user: WrappedAttributeError at /login/ 'TokenAuthentication' object has no attribute 'get_user' I need to define a get_user method to fix this. Is there something I can fix so that I don't have to implement a custom TokenAuthetication class with a get_user method? views.py from django.contrib.auth.models import User from rest_framework.response import Response from knox.views import LoginView as KnoxLoginView from knox.auth import TokenAuthentication class GetAuthToken(KnoxLoginView): permission_classes = [AllowAny] def post(self, request,*args, **kwargs): user = TokenAuthentication().authenticate(request=request) if user: return Response(status=200) else: requestToken = request.data.get('requestToken') if not requestToken: return Response({'result': 'error'}) user = User.objects.all().first() if user is None: return super().post(request, format=None) else: login(request, user, backend='knox.auth.TokenAuthentication') return super().post(request, format=None) return super().post(request, format=None) settings.py 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'adminutil', 'advisory', 'knox', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'knox.auth.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication' ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES' : [ 'knox.auth.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication' ] } These are the server logs: Traceback (most recent call last): … -
Unable to understand errors when i run the command 'python manage.py migrate'
I have been following Django girls tutorial to learn Django web framework. https://tutorial-extensions.djangogirls.org/en/optional_postgresql_installation/ I have reached this part of the tutorial. Now I am completely stuck when I run the command python manage.py migrate. I cannot even run my server on the local host anymore, runserver brings the same error. All these errors started coming up since I changed my settings.py file to accommodate the Postgres database. I am in dire need of some help. I had postgres installed from before(version 11.4). Seeing these errors I removed it, and then downloaded it again, following the directions of the aforementioned tutorial. It was a useless effort, as the same problem came up. Traceback (most recent call last): File "/home/jpsofficedev/Documents/coding_for_girls/djangogirls/myvenv/lib64/python3.7/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection self.connect() File "/home/jpsofficedev/Documents/coding_for_girls/djangogirls/myvenv/lib64/python3.7/site-packages/django/db/backends/base/base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "/home/jpsofficedev/Documents/coding_for_girls/djangogirls/myvenv/lib64/python3.7/site-packages/django/db/backends/postgresql/base.py", line 168, in get_new_connection connection = Database.connect(**conn_params) File "/home/jpsofficedev/Documents/coding_for_girls/djangogirls/myvenv/lib64/python3.7/site-packages/psycopg2/__init__.py", line 126, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: FATAL: Ident authentication failed for user "jpsofficedev" My experience in Postgres is null. Suggestions for some tutorial, documentation will also be appreciated. -
How to do model level custom field validation in django?
I have this model: class StudentIelts(Model): SCORE_CHOICES = [(i/2, i/2) for i in range(0, 19)] student = OneToOneField(Student, on_delete=CASCADE) has_ielts = BooleanField(default=False,) ielts_listening = FloatField(choices=SCORE_CHOICES, null=True, blank=True, ) ielts_reading = FloatField(choices=SCORE_CHOICES, null=True, blank=True, ) ielts_writing = FloatField(choices=SCORE_CHOICES, null=True, blank=True, ) ielts_speaking = FloatField(choices=SCORE_CHOICES, null=True, blank=True, ) and have this model form: class StudentIeltsForm(ModelForm): class Meta: model = StudentIelts exclude = ('student') def clean(self): cleaned_data = super().clean() has_ielts = cleaned_data.get("has_ielts") if has_ielts: msg = "Please enter your score." for field in self.fields: if not self.cleaned_data.get(str(field)): self.add_error(str(field), msg) else: for field in self.fields: self.cleaned_data[str(field)] = None self.cleaned_data['has_ielts'] = False return cleaned_data As you see, if a student has ielts, then he/she has to specify his/her scores in the model form. I now want to do this on the database level. So I need to customize my model save method, I guess. How should I do this? Will my StudentIeltsForm behavior be the same as before if I change it as below? class StudentIeltsForm(ModelForm): class Meta: model = StudentIelts exclude = ('student') I read this: https://docs.djangoproject.com/en/2.2/ref/models/instances/#validating-objects and this: https://kite.com/python/docs/django.db.models.Model.clean and I know that to iterate over model field I have to use for field in self._meta.fields: But I have not yet reached to … -
Why can't I get images from my S3 bucket when all public access blocked? 403 Forbidden
My Django website allows users to upload photos. When the s3 bucket is on public the media content loads fine on the site. However once i block all public access the content no longer loads and a 403 forbidden error is shown. In my code I have added the values needed to allow for authenticate requests. There are no bucket policy's or any CORS configurations. I have tried several different suggestions from blogs and tutorials but nothing seems to work. I have a user which has programmatic access and set the secret variables in the heroku environment and still get 403 error. I have tried hard setting the secret variables and still no success. settings.py 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 = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } MEDIA_LOCATION = 'MediaStorage' MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIA_LOCATION) MEDIA_FILE_STORAGE = 'MediaStorage' STATIC_ROOT = os.path.join(BASE_DIR, "static") STATIC_LOCATION = 'static' STATICFILES_LOCATION = 'StaticStorage' STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, STATIC_LOCATION) django_heroku.settings(locals()) storage_backends.py from storages.backends.s3boto3 import S3Boto3Storage from django.conf import settings class StaticStorage(S3Boto3Storage): location = settings.STATICFILES_LOCATION class MediaStorage(S3Boto3Storage): location = settings.MEDIA_FILE_STORAGE file_overwrite = False I expect the files to load when displaying them in the view web page. … -
Django Haystack - No module named 'haystack.backends.elasticsearch5_backend'
Im following the install instructions as per the haystack documentation http://docs.haystacksearch.org/en/master/tutorial.html#installation and the search engine installation https://django-haystack.readthedocs.io/en/master/installing_search_engines.html#elasticsearch I have installed Elasticsearch 5.1.16 which is listed as compatible and have put the settings in, the installation guide only has examples for Elasticsearch versions 1 and 2 but states that 5 is supported. so I changed to version 5 in the settings 'default': { 'ENGINE': 'haystack.backends.elasticsearch5_backend.Elasticsearch5SearchEngine', 'URL': 'http://127.0.0.1:9200/', 'INDEX_NAME': 'haystack', }, } I have also gone through the repo and can see that version 5 is in there but when I start my server I receive the error: return _bootstrap._gcd_import(name[level:], package, level) ModuleNotFoundError: No module named 'haystack.backends.elasticsearch5_backend' but then when I traverse the folder structure it hasn't installed the version 5 files root@4c1197e002e8:/myapp/# ls /usr/local/lib/python3.6/site-packages/haystack/backends/ __init__.py __pycache__/ elasticsearch2_backend.py elasticsearch_backend.py simple_backend.py solr_backend.py whoosh_backend.py and im using the same version as the git repo that has the 5 backend in it? root@4c1197e002e8:/myapp/# pip freeze | grep hay django-haystack==2.8.1 anyone help me out whats missing here? Thanks