Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django rest api - searching a method field with the search filter
im trying to filter search a rest api page and want to use a method field as one of the search fields, however when I do this I get an error stating the field is not valid and it then lists the field in my model as the only valid source serialiser: class SubnetDetailsSerializer(QueryFieldsMixin, serializers.HyperlinkedModelSerializer): subnet = serializers.SerializerMethodField() device = serializers.ReadOnlyField( source='device.hostname', ) circuit_name = serializers.ReadOnlyField( source='circuit.name', ) subnet_name = serializers.ReadOnlyField( source='subnet.description', ) safe_subnet = serializers.SerializerMethodField() def get_safe_subnet(self, obj): return '{}{}'.format(obj.subnet.subnet, obj.subnet.mask.replace('/','_')) def get_subnet(self, obj): return '{}{}'.format(obj.subnet.subnet, obj.subnet.mask) class Meta: model = DeviceCircuitSubnets fields = ('id','device_id','subnet_id','circuit_id','subnet','safe_subnet','subnet_name','device','circuit_name') views: class SubnetDetailsSet(viewsets.ReadOnlyModelViewSet): queryset = DeviceCircuitSubnets.objects.all().select_related('circuit','subnet','device') serializer_class = SubnetDetailsSerializer permission_classes = (IsAdminUser,) filter_class = DeviceCircuitSubnets filter_backends = (filters.SearchFilter,) search_fields = ( 'device__hostname', 'circuit__name', 'subnet__subnet', 'safe_subnet' ) how can include the safe_subnet in the search fields? Thanks -
how to create child page of parent class in django
I have Blockchain page and i need child page of blockchain like below in django: It can have multiple child page and how to check that this is last child page of parent class Blockchain #parent page childpage 1 childchildpage 1 and so on # child page of childpage 1 childpage 2 -
how to speed up file uploading at Django?
I have a form which sent to the server by ajax request. This form has a field for file uploading. How can to speed up file uploading? Mostly files such as images and text documents will be uploading. But there are no upload restrictions, so even large-size movies can be will be uploading. js var frm = $('#contact_form'); frm.submit(function (e) { e.preventDefault(); $.each($("div[class^='contact_form_']"), function(ind, value){ $(value).hide(); $(value).prev().css('border', 'none') }) var form_data = new FormData($('#contact_form')[0]); $.ajax({ type: frm.attr('method'), headers:{ "X-CSRFToken": $('input[name="csrfmiddlewaretoken"').val() }, url: '', data: form_data, processData: false, contentType: false, success: function(data) { console.log(data) if (data.result == 'error'){ $.each(data.response, function(key, value) { $('.contact_form_' + key).css('display', 'block') $('.contact_form_' + key).prev().css("border", 'solid #FD7900') $('.contact_form_' + key).text(value) }) } else { location.reload(); } } }); return false; }); view def post(self, request, *args, **kwargs): print(self.request.POST, self.request.FILES) contact_form = ContactFormForm(request.POST, request.FILES) if contact_form.is_valid(): contact_form.save() return JsonResponse({}) else: response = {} for k in contact_form.errors: response[k] = contact_form.errors[k][0] return JsonResponse({'response': response, 'result': 'error'}) -
Django Function Base View Search Form By Primary Key
The code sample as novice of Django, is it right practice to achieve page load per ID as shown below? View.py def testidbasesearch(request,id=None): if request.method == "GET": print ('Inside IF GET') if not id: form = MtiForiegnForm() else: instance = Mt_Issue_foriegn.objects.get(id=id) form = MtiForiegnForm(request.POST or None, instance=instance) else: print ('Inside Else GET') id=request.POST.get('pkid') instance = Mt_Issue_foriegn.objects.get(id=id) form = MtiForiegnForm(request.POST , instance=instance) return redirect(reverse('tepo1', kwargs={"id": id})) return render(request,'testingpost.html',{'form':form}) url.py path('testidbasesearch',testidbasesearch,name='testidbasesearch'), path('testidbasesearch/<int:id>',testidbasesearch,name='testidbasesearch'), testingpost.html {% extends 'base.html' %} {% block content %} <form id="postform1" method="post" action=""> {% csrf_token %} <input type="text" name="pkid" /> <input type="submit" id="submit-form" /> {% for form1 in form %} <fieldset disabled="disabled"> {{ form1 }} </fieldset> {% endfor %} </form> {% endblock %} First of all my functionality is working as expected , I just need review is it right code practice, I purposely avoid AJAX/jquery ( i.e. js) pure django /python code to load form based on id submitted. -
Navigate to Django URL from Angular
I am using Angular guard to block the pages when a user isn't logged in, the logging in is done with Django. If they're not logged in, I want them to be redirected to the Django login template. I initially had issues with Angular removing the trailing slash needed for the Django URL, this was done by adding a . after the slash I wanted to keep. This has the correct URL but it won't show the Django page unless I refresh the page, just shows my Angular 404. This is what I am using to reroute: this.router.navigate(['/accounts/login/.']); I expect the Django loging page to be shown when a user that isn't logged in tries to access any of the other pages before logging in. I am only given an Angular 404 which means the site is still accessible. -
Invalide Cursor Name
I am using Pycharm for a Django project with psycopg2 and I do some unit test. But I got a problem. Indeed, I am facing to this error : psycopg2.errors.InvalidCursorName: ERROR: the cursor « _django_curs_139677874173696_53 » does not exist Do you have any ideas to solve this problem ? I precise I am using a postgre database with pgadmin. -
Is anyone implemented django celery worker as docker container it only runs when task assigned
I am able to successfully deploy Django Celery worker as a docker container in AWS ECS service using FARGET as computing. But my concern is that celery container is running 24/7. If I can run container only when task is assigned, I can save lot of money as per AWS FARGET billing methodology. -
How to redirect in a Generic View
I am using a generic view to render my blog post item: class PostUpdateView(UpdateView, LoginRequiredMixin): model = Post # etc I have a model method on the Post model that results in a boolean True or False: @property def can_edit(self): return self.displays_set.count() == 0 If can_edit is False for the Post object, how can I refactor the view to redirect from my UpdateView to a different DetailView? -
i don't understand the error in these fie
i have facing these issue while creating template in django as i am creating template while adding template attribute in setting.py its showing the error syntax is invalid TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [[os.path.join(BASE_DIR,'templates')], 'APP_DIRS':True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] 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 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 724, in exec_module File "<frozen importlib._bootstrap_external>", line 860, in get_code File "<frozen importlib._bootstrap_external>", line 791, in source_to_code File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "F:\myweb\myweb\settings.py", line 59 'APP_DIRS': True, ^ SyntaxError: invalid syntax MPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [[os.path.join(BASE_DIR ,'templates')], 'APP_DIRS':True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'myweb.wsgi.application' i am creating a html file under ajango template but when i am trying to run it o browser it shows the error file doesnot exists from django.apps import AppConfig class NewappConfig(AppConfig): name = 'newapp' its have to show hello there!!! on browser -
A function present in views.py file need to access the images stored in my pc
I need to include some image processing code in django. For that I want to access images stored in my pc (or in static folder in django ) through function in views.py. How can I do that? -
How to make Django views require a user login?
I have a Django project with a login screen; when I enter my username and password I get directed to the home page. This works fine! But nothing is secure, I can just go to the view at /allstudyplans without logging in and see all the information there. My Question is how do I make it so it's not possible to go /allstudyplans without logging in first? Form User = get_user_model() class UserLoginForm(forms.Form): username = forms.CharField(label='', widget=forms.TextInput( attrs={ 'class': 'form-control', 'autofocus': '', 'placeholder': 'Användarnamn', } ), ) password = forms.CharField(label='', widget=forms.PasswordInput( attrs={ 'class': 'form-control mt-1', 'placeholder': 'Lösenord', } ), ) # https://docs.djangoproject.com/en/2.1/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other def clean(self): cleaned_data = super().clean() username = cleaned_data.get('username') password = cleaned_data.get('password') if username and password: user = authenticate(username=username, password=password) if not user: raise forms.ValidationError( 'Oh! I can\'t find that user - create user first!') elif not user.check_password(password): raise forms.ValidationError( 'Oh! That password is incorrect - try again!') elif not user.is_active: raise forms.ValidationError( 'Oh! That user is not active in the database!') Views def home(request): next = (request.GET.get('next')) form = UserLoginForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) login(request, user) if next: return redirect(next) return redirect('/') context = { 'form': form, } … -
How to set a model boolean field based on conditional logic of other field values
I have a Template model with a 1:many FK with a Post model: class Template(model.Models): #foo class Post(model.Models): template = models.ForeignKey( Template, null=True, on_delete=models.SET_NULL) I want to create an 'automatic' boolean field that flags if there is one or more posts using the template (if True I will lock the template for editing). What's the best way to do this? Is it via a @property decorator on the Template model??: @property def can_edit(self): if self.object.post_set.all() >= 1: self._can_edit = True return self._can_edit else: self._can_edit = False return self._can_edit Then I would call this via {{ template.can_edit }} to display the flag status and {% if template.can_edit() %} to run conditional logic, but this does not work. -
Take the data of one table and make the field for another table
Models.py class Designation(models.Model): Name = models.CharField(max_length=50) department = models.ForeignKey(Department, on_delete=models.CASCADE) def __str__(self): return self.Name class Meta: db_table = 'desingnation' all the data should create as field to another table -
Watching for file changes with StatReloader Exception in thread django-main-thread:
**Don't know what the problem is. I am not able to run any of my Django servers. Every time gets the same error. And don't have any idea about this. Tried reinstalling windows, python and all. But still gets same error. ** Don't know what the problem is. I am not able to run any of my Django servers. Every time gets the same error. And don't have any idea about this. Tried reinstalling windows, python and all. But still gets same error. C:\Users\JamesBond\Desktop\ONLINE WEBSITES\vishwatradelink_>manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\JamesBond\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 926, in _bootstrap_inner self.run() File "C:\Users\JamesBond\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\JamesBond\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\JamesBond\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\JamesBond\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 77, in raise_last_exception raise _exception[1] File "C:\Users\JamesBond\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "C:\Users\JamesBond\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\JamesBond\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\JamesBond\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\JamesBond\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\JamesBond\AppData\Local\Programs\Python\Python37-32\lib\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 … -
Problem with Django foreign key field with to_field attribute
I have my model of User object which is related to Group object (example). So user has something like: group_name = models.ForeignKey(Group, to_field="group_name", ...) (of course the group_name is defined as unique as it's not a primary key in Group object) But when I'm trying to change the group_name value for some Group object (regardless it's via Admin interface or within the code by updating the selected object) it raises the Integrity error: FOREIGN KEY constraint failed I know there is a mandatory parameter on_delete for the foreign key filed but I've tried all potential pre-defined values (models.SET_DEFAULT, models.CASCADE, etc.) but without any change. It seems to me I need something what to do on_update, but that's not possible attribute ;-) Thanks -
Side bar menu should load based on role based login django
Based on the Designation, Menu should load while the Employee login to the application. Its like a role based login or Access control permision -
django ORM problem - Annotate and aggregate return inconsistent values
I found a setup where aggregate() and annotate() do NOT return the same values... I am really confused. I have the following models: class Invoice(models.Model): pass class InvoiceItem(models.Model): invoice = models.ForeignKey(Invoice, related_name="items") amount = models.PositiveIntegerField(null=False, blank=False, default=1) price = models.DecimalField(max_digits=10, decimal_places=2, null=False, blank=False, default=0) begin = models.DateField(null=True, blank=True) When I want to get the total revenue over a timespan, I have the following query: revenue = Invoice.objects.annotate( first_date=Min('items__begin')).filter( first_date__range=[start_date, end_date]).aggregate( revenue=Sum(F('items__amount') * F('items__price'), output_field=FloatField()))['revenue'] I tried to do the same with annotate() just to verify the results: revenue_list = Invoice.objects.annotate( first_date=Min('items__begin')).filter( first_date__range=[start_date, end_date]).annotate( revenue=Sum(F('items__amount') * F('items__price'), output_field=FloatField())) When I now loop over the elements and manually sum up revenue I get a different value than revenue. Any ideas? Unfortunately after an aggregation you cannot check the raw query anymore... Thanks! -
Generate PDF in Django Python with customize header/footer and different header/footer in different pages in a single pdf
I want to generate pdf using django python. Pdf will have customize headers and footers and different headers and footers on different pages in a single pdf file. I have already tried WKHTML but it doesn't give option of different headers and footers in a single file. WKHTML Library Expecting: Different headers and footers on different pages in a single pdf file. -
How to retrive data from related table in djnago
Hey I want retrieve all staff information with there respective Operating Hours please help me, Here is my models class Staff(models.Model): vendor = models.ForeignKey(Vendor,on_delete=models.DO_NOTHING,blank = True) name = models.CharField(max_length=100) last_name = models.CharField(max_length = 100) gender = models.IntegerField(choices=GENDER_TYPE, default=0) class OperatingHours_staff(models.Model): staff = models.ForeignKey(Staff,related_name='days',on_delete = models.CASCADE) day = models.IntegerField(choices = constants.DAYS) start_time = models.TimeField() end_time = models.TimeField() Thanks in Advance -
Where does ArrayField create SimpleArrayField in Django?
I want to review the code and maybe override it for my needs, where SimpleArrayField is created for ArrayField in Django. Unfortunately I can't find or don't understand where it happens. I've searched through ArrayField and only place where SimpleArrayField is mentioned is this method. Since method returns super().formfield(...'form_class': SimpleArrayField...), I've searched for formfield() in inherited classes (CheckFieldDefaultMixin, Field), but found nothing. -
DRF loading binary files sending from React app
I made a standard API for downloading files to AWS S3. Using the standard DRF interface, the files are loaded correctly into the repository. models.py class Documents(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) upload = models.FileField(storage=PrivateMediaStorage()) filename = models.CharField(_('documents name'), max_length=64) datafile = models.FileField() created = models.DateTimeField(auto_now_add=True) type = models.ForeignKey(Doctype, on_delete=models.CASCADE, blank=True) views.py class DocumentsListView(AwsUrlMixin, viewsets.ViewSetMixin, generics.ListCreateAPIView): queryset = Documents.objects.all() serializer_class = DocumentsSerializer permission_classes = (IsAuthenticated, LifeLinePermissions) pagination_class = None def perform_create(self, serializer): serializer.save(author=self.request.user) Problems begin when the download is done through the user interface and the file is transferred using React. The file comes in binary form, and django does not accept this format by saying datafile: ["No file was submitted."] An error occurs in the django console HTTP POST /api/v1/files/ 400 [0.02, 127.0.0.1:33916] In the browser debugger -
How to implement upload image via url in django
Basically I am creating a website where you can upload images of different websites using url. How to implement it. How to validate if it is an image and how to fetch it and store in your database -
how to remove or delete django project
screenshot image1 I use visual studio code and create a django project(python-training).Q1:I can't use 'open with live server' to see html file, instead the file in python-training directory. what I can do to remove or delete django project? Q2:why the python-training directory don't have the following files: setting.py, manage.py thank you all for give me a hand screenshot image2 screenshot image3 -
Memcached reflecting changes automatically from the built in User model, how?
I am using memcached in my code to represent some lists in web. I am doing something like this, from django.core.cache import cache #inside view cache_key='somekey' cache_time=sometime data=cache.get(cache_key) if not data: #some code cache.set(cache_key,data,cache_time) return render(...) It is working perfectly. Cache is serving the pages. But here I am observing that, any changes in the database in the build in User model is getting reflected in the cache automatically. how is this happening? And my 2nd question is, what is the best way to reflect the database changes in the memcached. I already tried to maintain, flags in the database using a trigger. It is working, but it is not possible to maintain different flags for every cache in the db as some urls has in them. Any help will be appreciated.. -
Any Suggestions please
I am building a website for image hosting. People can upload via url or images directly from their device. Trying to implement it on python / Django but not getting the proper tutorials. Any suggestions? Should I use aws s3 for storage and ec2 for server. Any suggestions? I am lost.