Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
create Django form class with dynamic number of CharFields
I'm having problem of creating a dynamic class form that contains a list of CharFields. I'm able to create a normal class with dynamic keys values as below. but when I change the values to be a CharFields. it doesn't work. What's wrong with the form? =========Normal class=========== class DynamicClass(forms.Form): def __init__ (self, data): self.data =data for key in self.data.keys(): self.__setattr__(key, self.data[key]) my_class = DynamicClass({"HOSTNAME": 'Router_Hostname: ', "IP": 'IP_ADDRESS:'}) print (my_class.HOSTNAME) output --> Router_Hostname: print (my_class.IP) output--> IP_ADDRESS: =========Form class=========== class DynamicForm(forms.Form): def __init__ (self, data): self.data =data for key in self.data.keys(): self.__setattr__(key, forms.CharField(label = self.data[key])) my_form = DynamicForm ({"HOSTNAME": 'Router_Hostname: ', "IP": 'IP_ADDRESS:'}) print (my_form.as_table) error output--> Traceback (most recent call last): File "", line 1, in File "~/automation/lib/python3.8/site-packages/django/forms/forms.py", line 137, in repr if self._errors is None: AttributeError: 'DynamicForm' object has no attribute '_errors' -
PYTHON: I'm trying to read different values from XML files and send to Django Html template
I have already read the xml values but i think that the way which i'm using to store the data is wrong. I'need to store a list, or a dict or list of dict some values and then send to the HTML Template and render an HTML Table with all the values: this should be the result and the following code is how i'm actual reading the values from XML for files in file_in_path: fileP = os.path.join(path,files) tree = ET.parse(fileP) roots = tree.getroot() for x in roots.findall('DatiGeneraliDocumento'): //node of xml file that i need to read tipdoc = x.find('TipoDocumento').text //all the data numdoc = x.find('Numero').text datadoc = x.find('Data').text mydict = {"tipdoc":item,"numdoc":numdoc,"datadoc":datadoc} //then i'm trying to save in dict liste.append(mydict)//and append all to a list context = {"data":liste} return(response, "page.html", context) when i'm in my html page and trying to print the result with django format language "{{ data }}" he print out one value and not all of of them, but if in python file i print out my list he print out all list. which is the best way to store all the values in all the xml files and then print out in a html table? -
I have uploaded my 1st django application to AWS but it is not working [closed]
I Followed this document https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html i am using Windows there wan no error in my powershell but when i launch website in browser it shows. i tried checking logs but cant understand the problem. -
WebSocket connection to 'ws:/' failed: Error during WebSocket handshake: Unexpected response code: 200
I am using Django-channels to connect to the server, but it always show the error like this: reconnectwebsockets.js WebSocket connection to 'ws:xxx' failed: Error during WebSocket handshake: Unexpected response code: 200 Any ideas what could be possibly wrong? -
Error creating A Django Timetable Generator
I am trying to create an app that generates a timetable for each class in a school. The timetable is supposed to prevent classes and teachers clashing with a specific number of periods in a week. The problem is it keeps generating a different number of timetables every time. My View where the timetable is generated: def GenerateTimetable(request): if request.method == 'POST': idf = request.POST["timetable_class_id"] classs = ClassRegistration.objects.get(id=idf) subjects = list(Class_Subjects.objects.filter(subject__select_class=classs)) class_periods = list(Period.objects.filter(section=classs.section).order_by('start_time')) break_time = Breaks.objects.get(section=classs.section) before_break = Period.objects.filter(start_time__lte=break_time.start_time).count() if Timetable.objects.filter(school_class__id=idf).count() != 0: Timetable.objects.filter(school_class__id=idf).delete() for subject in subjects: DupNum = 0 y = 0 m = 0 j = 0 if DupNum > len(class_periods): messages.info(request, "Couldn't create Timetable") redirect('home') while y < subject.no_of_times_a_week: if DupNum > len(class_periods)+ 3: break if DupNum < 3: if subject.is_morning and m < 3: i = random.randint(0, before_break) else: i = random.randint(0, len(class_periods)-1) else: if j < len(class_periods): i = j j += 1 start_conflict = Timetable.objects.filter(period__day=class_periods[i].day, period__start_time__range=(class_periods[i].start_time, class_periods[i].end_time)) end_conflict = Timetable.objects.filter(period__day=class_periods[i].day, period__end_time__range=(class_periods[i].start_time, class_periods[i].end_time)) during_conflict = Timetable.objects.filter(period__day=class_periods[i].day, period__start_time__gte=class_periods[i].start_time, period__end_time__lte=class_periods[i].end_time) teacher_conflict = Timetable.objects.filter(period__day=class_periods[i].day, period__start_time__gte=class_periods[i].start_time, period__end_time__lte=class_periods[i].end_time) subject_conflict = Timetable.objects.filter(period__day=class_periods[i].day, subject=subject) if start_conflict.count() == 0 and end_conflict.count() == 0 and during_conflict.count() == 0 and teacher_conflict.count() == 0 and subject_conflict.count() == 0: Timetable.objects.create(school_class=classs, subject=subject, period=class_periods[i]) DupNum = 0 … -
from django.db import models in models.py but in command prompt i got NameError: name 'model' is not defined
i got an this error: File "C:\Users\jiri.svab\Documents\Pipenv\Django\DennisIvy\ecommerce\store\models.py", line 15, in class Product(models.Model): File "C:\Users\jiri.svab\Documents\Pipenv\Django\DennisIvy\ecommerce\store\models.py", line 16, in Product name = model.CharField(max_length=200, null=True) NameError: name 'model' is not defined But in my "models.py" in the first line i have imported the model: from django.db import models from django.contrib.auth.models import User # Create your models here. class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) def __str__(self): return self.name Any clue what i should look for please? Thank you -
pip install weasyprint on windows
I get this error when i use pip install WeasyPrint pip install WeasyPrint Collecting WeasyPrint Using cached WeasyPrint-51-py3-none-any.whl (359 kB) Collecting Pyphen>=0.9.1 Using cached Pyphen-0.9.5-py2.py3-none-any.whl (3.0 MB) Collecting tinycss2>=1.0.0 Using cached tinycss2-1.0.2-py3-none-any.whl (61 kB) Collecting cssselect2>=0.1 Downloading cssselect2-0.3.0-py3-none-any.whl (31 kB) Collecting cairocffi>=0.9.0 Using cached cairocffi-1.1.0.tar.gz (68 kB) ERROR: Command errored out with exit status 1: command: 'd:\myshop\virtual\scripts\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\USER\\AppData\\Local\\Temp\\pip-install-qwm3sa11\\cairocffi\\setup.py'"'"'; __file__='"'"'C:\\Users\\USER\\AppData\\Local\\Temp\\pip-install-qwm3sa11\\cairocffi\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\USER\AppData\Local\Temp\pip-pip-egg-info-tqlmdfuq' cwd: C:\Users\USER\AppData\Local\Temp\pip-install-qwm3sa11\cairocffi\ Complete output (107 lines): Traceback (most recent call last): File "d:\myshop\virtual\lib\site-packages\setuptools\msvc.py", line 489, in _find_latest_available_vc_ver return self.find_available_vc_vers()[-1] IndexError: list index out of range During handling of the above exception, another exception occurred: Traceback (most recent call last): File "d:\myshop\virtual\lib\site-packages\setuptools\sandbox.py", line 154, in save_modules yield saved File "d:\myshop\virtual\lib\site-packages\setuptools\sandbox.py", line 195, in setup_context yield File "d:\myshop\virtual\lib\site-packages\setuptools\sandbox.py", line 250, in run_setup _execfile(setup_script, ns) File "d:\myshop\virtual\lib\site-packages\setuptools\sandbox.py", line 45, in _execfile exec(code, globals, locals) File "C:\Users\USER\AppData\Local\Temp\easy_install-_u06tvni\cffi-1.14.3\setup.py", line 131, in <module> File "C:\Users\USER\AppData\Local\Temp\easy_install-_u06tvni\cffi-1.14.3\setup.py", line 109, in uses_msvc File "C:\Users\USER\AppData\Local\Programs\Python\Python38-32\lib\distutils\command\config.py", line 225, in try_compile self._compile(body, headers, include_dirs, lang) File "C:\Users\USER\AppData\Local\Programs\Python\Python38-32\lib\distutils\command\config.py", line 132, in _compile self.compiler.compile([src], include_dirs=include_dirs) File "C:\Users\USER\AppData\Local\Programs\Python\Python38-32\lib\distutils\_msvccompiler.py", line 360, in compile self.initialize() File "C:\Users\USER\AppData\Local\Programs\Python\Python38-32\lib\distutils\_msvccompiler.py", line 253, in initialize vc_env = _get_vc_env(plat_spec) File "d:\myshop\virtual\lib\site-packages\setuptools\msvc.py", line 185, in msvc14_get_vc_env return EnvironmentInfo(plat_spec, vc_min_ver=14.0).return_env() … -
How to "pip install" latest versions of modules from requirements.txt neglecting the old versions written in REQUIREMENTs.TXT?
I am working in Django. I want to install all the python modules which are the latest. What should in HAVE to do to update all the latest versions of modules? How to "pip install" the latest versions of modules from requirements.txt neglecting the old versions written in REQUIREMENTs.TXT? Let's say, Inside requirements.txt is: asn1crypto==1.0.1 astroid==2.3.1 so I want to install the latest version of: asn1crypto and asn1crypto -
How to iterate over a list in django template
I want to iterate over a list which is passed in template in a tuple. I want to show some descriptions in their relative places. I have all the descriptions(7-8) in a list. Here is views.py file looks like: from django.shortcuts import render import requests from bs4 import BeautifulSoup from .functions import get_descriptions def index(request): url = requests.get('https://thehackernews.com/') soup = BeautifulSoup(url.content, 'html.parser') post_container = soup.find(class_='blog-posts') post_body = post_container.find_all(class_='body-post') total_news = range(0, len(post_body)) descs = get_descriptions(post_body=post_body) # a list of descriptions final_postings = [] for link in post_body: post_link = link.find(class_='story-link').attrs lnk_lst = str(post_link['href']) # print(lst) images = link.find(class_='home-img-src').attrs src_lst = str(images['data-src']) # print(src_lst) titles = link.find(class_='home-title').get_text() post_dates = link.find(class_='item-label').get_text() final_postings.append((lnk_lst, src_lst, titles, descs)) front_end_stuff = {'final_postings': final_postings, 'news': total_news} return render(request, 'mainapp/index.html', context=front_end_stuff) And the template mainapp/index.html looks like: {% extends 'mainapp/main.html' %} {% block content %} {% for post in final_postings %} <div class="card hoverable"> <div class="card-content"> <div class="row"> <div class="col s12 l4"> <div class="card-image"> <img src="{{ post.1 }}" alt="news" class="responsive-img"> </div> </div> <div class="col s12 l7 offset-l1"> <a href="{{ post.0 }}" class="black-text"><div class="title">{{ post.2 }}</div></a> <p class="truncate">{{ post.3 }}</p> </div> </div> </div> </div> {% endfor %} {% endblock content %} I want to show the relative description to … -
STATIC(CSS AND JS) FILES ARE NOT WORKING AFTER UPLOADING WEBSITE ON HEROKU
I have just uploaded my website on heroku, the css and javascript files works perfectly on localhost but doesn't work after deploying. I also made sure to run this command python manage.py collectstatic which i did both in the production and development environment but doesn't still solve the problem. I have included the necessary codes that would be useful, i have also included the images of both instances and my project directory Settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles/') STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py from django.conf.urls.static import static from django.conf import settings urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) This is the image on localhost This is the image on heroku And this is the the project directory structure -
Django TypeError: expected string or bytes-like object
I don't know why am receiving this error in the first place check the whole code thrice I am calling out a signal from Django View to create an object in the model for analytical purpose. models.py RECEIVER_REQUEST_TYPE = ( ('ABOX', 'Android Bounding Box'), ('ENTR', 'Web Bounding Box'), ) class BaseAnalytics(models.Model): """Common filds for all the tables""" ip_address = models.CharField(max_length=220, blank=True, null=True) content_type = models.ForeignKey( "contenttypes.ContentType", on_delete=models.CASCADE, blank=True, null=True) timestamp = models.DateTimeField(auto_now_add=True) # status = models.IntegerField(blank=True, null=True) execution_time = models.TimeField(verbose_name='Time Taken for each qeury to execute') class ReceiverAnalytics(BaseAnalytics): """reciever analytics""" longitude = models.FloatField(blank=True, null=True) latitude = models.FloatField(blank=True, null=True) request_type = models.CharField(max_length=4, choices = RECEIVER_REQUEST_TYPE) def __str__(self): return str(self.id) class Meta: verbose_name = 'Receiver Analytics' verbose_name_plural = 'Receiver Analytics' # SIGNAL def receiverAnalyticsSignal(sender, request, request_type, time, longitude, latitude ,*args, **kwargs): pdb.set_trace() c_type = ContentType.objects.get_for_model(sender) new_call_obj = ReceiverAnalytics.objects.create( ip_address = get_client_ip(request), content_type = c_type, request_type = request_type, longitude = longitude, latitude = latitude, execution_time = time, ) print(new_call_obj) object_viewed_signal.connect(receiverAnalyticsSignal) Signal.py from django.dispatch import Signal object_viewed_signal = Signal(providing_args=['request']) Views.py object_viewed_signal.send( Receive, request_type='NRBY', longitude=longitude, latitude=latitude, time=total_time, request=request ) Here are types of fields --------------- Receive > model_name mark NRBY > String enum longitude, latitude, time > … -
Django 2.2 - how to express a constraint between two fields
I have a couple of models that look like this: class AlarmStatus(Enum): UNDEFINED = "Undefined" PENDING = "Pending" CUSTOMER_PENDING = "Customer Pending" @classmethod def choices(cls): return tuple((i.name, i.value) for i in cls) class Alarm(models.Model): managed = models.BooleanField(default=False, blank=False, verbose_name="Managed ?") status = models.CharField( max_length=20, default=AlarmStatus.UNDEFINED.name, choices=AlarmStatus.choices() ) class Meta: constraints = [ models.CheckConstraint( check=Q(managed=False) & Q(status=AlarmStatus.UNDEFINED.name), name="if_managed_is_False_status_must_be_UNDEFINED") ] I would like to enforce at the db level the following invariant: if an alarm managed field is False, then its status field MUST be "UNDEFINED". I.e. I want to declare illegal the following state/combination: managed == False AND status == (PENDING | CUSTOMER_PENDING) How can I enforce this? I tried with the above constraint but it is clearly wrong, because it is enforcing that every row managed field must be False AND every row status must be UNDEFINED. Thanks -
How can I prerun my APIs from my Django Restful API dashboard
I currently have this Django Swagger API dashboard and I want to run the APIs that I've already ran, I want to try loading the APIs into a text file and run the text file. -
Django Python form , dynamic value
I am new to Django Framework, so please be kind if my question is basic. I just want to upload a file, thus I have the following: #view.py def upload_file(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file(request.FILES['file']) return HttpResponseRedirect('/success/url/') else: form = UploadFileForm() return render(request, 'flows/upload.html', {'form': form}) #forms.py from django import forms class UploadFileForm(forms.Form): file = forms.FileField() name = forms.CharField( max_length=50,required=False) #upload.html <html> <head>File Uploads</head> <body> <form enctype="multipart/form-data" action="" method="post"> <!-- Do not forget to add: enctype="multipart/form-data" --> {% csrf_token %} <p> <label for="Name">Name: {{ form.name }}</p> <p>{{ form.file }}</p> <input type="submit" value="Updload"> </form> </body> </html> So basically, I have a form with a input field, and a upload file button. I want to link the input field, with the file name selected after the user select the file to upload. Starting from that I do not know where should I go. Thank you, -
got this error in django (command prompt)
Exception happened during processing of request from ('127.0.0.1', 52633) Traceback (most recent call last): File "c:\users\sonu sharma\appdata\local\programs\python\python38\lib\socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "c:\users\sonu sharma\appdata\local\programs\python\python38\lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "c:\users\sonu sharma\appdata\local\programs\python\python38\lib\socketserver.py", line 720, in init self.handle() File "C:\Users\sonu sharma\Desktop\myenv\lib\site-packages\django\core\servers\basehttp.py", line 174, in handle self.handle_one_request() File "C:\Users\sonu sharma\Desktop\myenv\lib\site-packages\django\core\servers\basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "c:\users\sonu sharma\appdata\local\programs\python\python38\lib\socket.py", line 669, in readinto return self._sock.recv_into(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine -
Download file after payment with Django (digital product)
I am building a digital ecommerce platform with Django. I want my users to get automatically a file after payment. So when they complete a payment they get automatically the file downloaded. thanks -
Django query related objects by there content_type
I have a Hit table at my Django project that stores view-counts for multiple object_types e.g. Post, Products & Profile models ... What I do not understand is how I can pull out object out of my Hit table that belong to a specific content_type or in other words, how to build the query correctly. Take the following query(s) as an example where I want to get all objects by there content_type out of my Hit Table: def recently_viewed_proposals(): hit = Hit.objects.all() queryset_p = Hit.objects.filter(pk__in=hit.filter(content_type=12).values_list('id', flat=True)) queryset_psm = Hit.objects.filter(pk__in=hit.filter(content_type=15).values_list('id', flat=True)) queryset_pso = Hit.objects.filter(pk__in=hit.filter(content_type=20).values_list('id', flat=True)) hit_elements = chain( queryset_p.random(len(queryset_p)), queryset_psm.random(len(queryset_psm)), queryset_pso.random(len(queryset_pso)) ) post_elements_list = list(hit_elements) print(post_elements_list) n_proposals = min(len(post_elements_list), config.MAX_RECENTLY_VIEWED_PROPOSALS) recently_viewed_proposals = random.sample(post_elements_list, n_proposals) return recently_viewed_proposals 12 = content_type id of Post model This is how my Hit table look like: class Hit(models.Model): objects = RandomManager() content_type = models.ForeignKey(ContentType, limit_choices_to=hit_models, on_delete=models.CASCADE) object_id = models.CharField(max_length=36) content_object = GenericForeignKey('content_type', 'object_id') viewer = models.ForeignKey(User, verbose_name="Viewer", on_delete=models.CASCADE) date_added = models.DateTimeField(auto_now=True) But I just get back the pk of the Hit model and not the pk's of the Post objects I stored at the Hit table. How can I access the pk's of my Post objects? -
pass attrs to BoundField.as_widget() django
I want to pass html attributes with BoundField.as_widget() by passing them to attrs in the method. Django doc says BoundField.as_widget(widget=None, attrs=None, only_initial=False)¶ Renders the field by rendering the passed widget, adding any HTML attributes passed as attrs. If no widget is specified, then the field’s default widget will be used. So I tried passing attributes like this: BoundField.as_widget(attrs={'class': 'container'}), which didn't work. forms.py class HiddenForm(forms.Form): testfield = forms.CharField(max_length=100, widget=forms.HiddenInput(attrs={'class': 'container'})) class BlahForm(forms.ModelForm): class Meta: model = Blah views.py. Model Blah is OneToOneField relationship to Model A. def myview(request, arg): a = get_object_or_404(A, somefieldname=arg) initial = {'blah': a} form = BlahForm(request.POST or None, initial=initial) # ModelForm from Model Blah value = a.pk hidden_input = HiddenForm(request.POST or None) hidden_input['testfield'].as_widget(attrs={'value': value }) # This is the reason I want to pass attrs with as_widget. I want to pass value to the hidden input form, so that the hidden form can handle submitting disabled form value, which I did on purpose to keep user from changing the value. if form.is_valid(): form.save() return redirect('somewhere', someparameter=arg) context = { 'form': form, 'value': value, 'hidden_input': hidden_input } return render(request, 'someapp/sometemplate.html', context) sometemplate.html <form method="post"> {% csrf_token %} {{ form|crispy }} {# disabled input data not submitted, so … -
How to check if BinaryField in Django is empty
I have a model which includes a BinaryField. E.g.: class AccountDetails(models.Model): logo = models.BinaryField() Now I want to check if that field is empty or not. Currently I use this: account_details = AccountDetails.object.get(id=1) if account_details.logo is b'': pass Is there a better way to do this than check against b''? -
How to choose between empty values or NULLs in a Django model with a UniqueConstraint based on two fields where one of them is optionnal?
I have a Django model with a Uniqueconstraint based on two fields values, one of them is mandatory the latter being optionnal. What is the best pratice here for the "optionnal" field (and why) to store "no value" between: No value = empty No value = NULL models.py class Foos(models.Model): name = models.CharField(max_length=50, blank=False, null=False) # Optionnal field alias = models.CharField(max_length=100, blank=True, null=True) class Meta: managed = True db_table = 'foos' def __str__(self): constraints = [models.UniqueConstraint(fields=['name', 'alias'], name='unique_foo')] object_name = self.name return object_name Note that I need to insert a bunch of values from an external source file, value for 'alias' could be equals to None and data is not inserted through a form. -
Django want to not show models class
i have one models in Models are some object for example Aries , Taurus and etc . In object are some fields image , title and etc . i want to not show some fields (image, title) in Django admin site ,because this fields is not static it's default. it's is possible ? Model.py from django.db import models class SignsList(models.Model): Title = models.TextField(blank=True, null=True) Image = models.TextField(blank=True, null=True) Date = models.TextField(blank=True, null=True) Daily = models.TextField(blank=True, null=True) Love = models.TextField(blank=True, null=True) Finance = models.TextField(blank=True, null=True) Views.py def singCategory(request,slug,cat): sign = SignsList.objects.get(Title=slug) args = {'sign':sign, 'cat':cat, 'slug':slug,'daily':daily} return render(request,'base3.html',args) Html.file <div class="full_descr"> {%if cat == 'Daily' %} {{ sign.Daily }} {% elif cat == 'Love' %} {{ sign.Love }} {% elif cat == 'Finance' %} {{ sign.Finance }} {% endif %} </div> -
How can a delete request be redirected to a specific url in django rest framework?
Currently, I have made a "Like" model and have implemented "Like" and "Uike" by post and delete requests, respectively. So after implementing Like, I want to implement Unlike, and I know that in order to implement it, I have to select the pk of that Like object, map it to url, and then send a delete request to that url. However, this method requires both url called "/post_id/like/like_id" and "/post_id/like_id", which I do not do, but try to redirect from views to "/post_id/like/like_id" when a delete request is sent to url called "/post_id/like/like". How can I make logic to proceed with the code as I think? Here's my code. views.py class CreateReadLikeView (ModelViewSet) : serializer_class = LikeSerializer permission_classes = [IsAuthenticated] queryset = Like.objects.all() is_saved = False def get_queryset (self) : return super().get_queryset().filter(post=self.kwargs.get('post_id')) def perform_create (self, serializer) : postId = self.kwargs.get('post_id') post = Post.objects.get(pk=postId) try : like = self.queryset.get(post=post, liked_people=self.request.user) except Like.DoesNotExist : serializer.save(liked_people=self.request.user, post=post) self.is_saved = True def create (self, request, *args, **kwargs) : super().create(request, *args, **kwargs) if self.is_saved is True : self.is_saved = False return Response({'success': '해당 게시물을 좋아요 했습니다.'}, status=200) return Response({'message': ['이미 해당 게시물을 좋아요 하였습니다.']}, status=400) def list (self, request, *args, **kwargs) : postId = self.kwargs.get('post_id') … -
Django Search Page with Query Pagination
Hello i have implemented a simple search form and search view to show search result. Now i want to paginate them. But there is a problem with the page in the url. My search url looks like ../search?q=Bla Now if i try to add pagination like: ../search?q=Bla?page=2 (at least thats how i understand it would work) it takes the whole string after q= to my database filter. I took a look at how stackoverflow handles searching and pagination and found out using '&' here is the view code: def search(request): # get query search parameters page = request.GET.get('page', 1) query = request.GET.get('q', '') # query none or empty if query is None or query == '': return redirect('home') # query valid else: # icontains make sure to ignore character sensitivity post_list = Post.objects.filter(title__icontains=query) paginator = Paginator(post_list, 5) try: posts_l = paginator.page(page) except PageNotAnInteger: posts_l = paginator.page(1) except EmptyPage: posts_l = paginator.page(paginator.num_pages) return render(request, 'search.html', {'post_list': posts_l, 'query': query}) and here the HTML Snippet: {% if post_list.paginator.num_pages > 1 %} <div class="pagination"> <span class="step-links mb-5 mx-auto"> {% if post_list.has_previous %} <a class="mr-3" href="?page={{ post_list.previous_page_number }}&q={{ query }}">zurück</a> {% endif %} <span>Seite {{ post_list.number }} von {{ post_list.paginator.num_pages }}</span> {% if post_list.has_next … -
Customize request made by Django drf-yasg
I want to change the request drf-yasg generates and executes in the 'Try it out' editor. My API endpoint accepts a request with query params like query_params = { data: [1, 2], field: "string_value" } <url>?data[]=1&data[]=2&field=string_value but when I have annotated my endpoint with @swagger_auto_schema( method="GET", manual_parameters=[ Parameter("data", IN_QUERY, type=TYPE_ARRAY, items=Items(type=TYPE_STRING)), Parameter("field", IN_QUERY, type=TYPE_STRING), ], ) the 'Try it Out' editor generates the request as <url>?data=1,2&field=string_value Is there any way I can cganhe the way drf-yasg generates the request for a specific type? -
Getting "Incorrect type. Expected pk value, received str." error with Django REST Framework when trying to POST data
While I am aware that there are several topics with the same general problem, I haven't been able to fix my problem using the solutions recommended in them. Most likely due to my total inexperience with Django REST, but nonetheless I am desperate for an answer at this point. I'm creating an application using TypeScript + React in the front and SQLite + Django + DRF on the back. In practice I am creating a questionnaire in which an user goes through questions and answers them. In the end I am trying to send the users answers to my server to be saved in my database. To this end I have an AnswerSet model that contains an array of Answer objects. Here are the models: class AnswerSet(models.Model): questionnaire = models.ForeignKey( Questionnaire, related_name='answer_set', on_delete=models.SET_NULL, blank=True, null=True ) class Answer(models.Model): value = models.CharField(max_length=1000, null=True, blank=True) answerSet = models.ForeignKey( AnswerSet, related_name='answers', on_delete=models.SET_NULL, blank=True, null=True ) question = models.ForeignKey( Question, related_name='answer', on_delete=models.SET_NULL, blank=True, null=True ) As you can see the AnswerSet also has a relation to one Questionnaire and the Answers have a relation to the AnswerSet they belong to as well as the Question they belong to (that's what I'm trying to do …