Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django changing models field into views
I everyone, I have a problem with a django's view. My goal is to change the 'execute' field into 'True' if newOrder is buy and there is some other sell order with a inferior price. And reverse for sell newOrders. I want to change the 'execute' field for the newOrder and also for the other order (in pairs). That's my code: views.py def order(request): form = OrderForm() if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): new_order = form.save() if new_order.buy is True: sellOrder = Order.objects.filter(sell=True, execute=False, price__lte=new_order.price).first().update(execute=True) new_order.execute = True sellOrder.save() else: buyOrder = Order.objects.filter(buy=True, execute=False,price__gte=new_order.price).first().update(execute=True) new_order.execute = True buyOrder.save() new_order.profile = request.user new_order.save() return redirect('home') else: form = OrderForm() contex = {'form': form} return render(request, 'app/new_order.html', contex) models.py class Profile(models.Model): _id = ObjectIdField() user = models.ForeignKey(User, on_delete=models.CASCADE) wallet = models.FloatField() class Order(models.Model): _id = ObjectIdField() profile = models.ForeignKey(User, on_delete=models.CASCADE) datetime = models.DateTimeField(auto_now_add=True) buy = models.BooleanField(blank=True) sell = models.BooleanField(blank=True) price = models.FloatField() quantity = models.FloatField() execute = models.BooleanField(blank=True) But something goes wrong. This is the error: AttributeError at /new_order/ 'NoneType' object has no attribute 'update' -
Hello could someone please tell me what I'm doing wrong the path is not being detected
path('product-accordion.html/< slug>/', ProductDetailView.as_view(), name='prod') - I think there is a syntax error here could someone help -
Django channels update event status on fullcalendar
I am searching if is possible to update status on events in fullcalendar Javascript plug in with Django channels in real time, I don't find anything about this, I am lost in this task, can you point me in the right direction? Thanks. -
Pagination with variable page and size Django
I tried to create a pagination api without a html file (only for the backend) and woth size and page as variables. urls.py urlpatterns= [path('api/units?page=<int:page>&size=<int:size>/', ListingsView.as_view()),] views.py class ListingsView(self,request): http_method_names = ['get'] permission_classes = (permissions.IsAuthenticated,) serializer_class = ListingsSerializers def get(request, page_num=1, units_perPpage=16): units = Unit.objects.all() units_per_page = request.GET.get('size') unit_paginator = Paginator(units, units_per_page) page_num = request.GET.get('page') page = unit_paginator.get_page(page_num) return JsonResponse({ 'totalPages': unit_paginator.count(), 'itemsCount': units.count(), 'units': page, }, status=200) However the url doesn't even get resolved. Any suggestions? -
Application error while deploying on heroku
I'm following django for beginners by william vincent and i followed every step carefully and in the end while deploying my pages app on heroku, i see this application error. Please guide me, I'm a beginner in programming.here in the image you can see application error -
Template does not exist in django 3.1.3 version
Am using django 3.1.3 version and am quite to this framework. On running the server am getting template does not exist, i tried all the possible solutions provided by statckoverflow but to no avail. -
how to download records into .xls file from according to Change in django filter
I have a Django web app where users can see table data and I am using django_filters to see data according to shift Time(Morning/Evening/General). It is working fine and just wanted to know how to implement download functionality into .xls format for the filter result(now I am downloading all records). filter.py import django_filters class ShiftChangeFilter(django_filters.FilterSet): id = django_filters.NumberFilter(label="DSID") class Meta: model = ShiftChange fields = ['ConnectID', 'EmailID','id','SerialNumber','Project_name','Shift_timing'] My code to download all records(which I want it to work based on filter e.g if user select General shift then all filtered result should get downloaded). views.py from django.utils import timezone now_aware = timezone.now() import xlwt,openpyxl def exportgenesys_data(request): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="Genesys_ShiftTiming.xls"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('GenesysShiftChange Data') # this will make a sheet named Users Data # Sheet header, first row row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['id','ConnectID','Shift_timing','EmailID','Vendor_Company','Project_name','SerialNumber','Reason','last_updated_time'] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # at 0 row 0 column # Sheet body, remaining rows font_style = xlwt.XFStyle() rows = ShiftChange.objects.all().values_list('id','ConnectID','Shift_timing','EmailID','Vendor_Company','Project_name','SerialNumber','Reason','last_updated_time') for row in rows: row_num += 1 for col_num in range(len(row)): ws.write(row_num, col_num, row[col_num], font_style) wb.save(response) return response One thing which I have tried is as below but I … -
Search Serialized for table using django and javascript
I want to extract the data from the serialized data into my table in my webpage using ajax and javascript. But my data are not being pulled to the table. how should I pull the two array in a serialized data into my table. Sample look of the output: column1 column2 column3 column4 column5 column6 column7 column8 column9 12-abc sal 113 113 113 113 113 113 113 tree 113 113 113 113 113 113 113 pal 113 113 113 113 113 113 113 tot 113 113 113 113 113 113 113 14-xyz ...n . . . n views.py: @api_view(['GET']) def get_processedoutputs(request): major_cd = request.query_params.get('major_cd', None) processedoutputs = ProcessedOutputs.objects.all() p_majors = ProcessedOutputs.objects.only('major_cd') majors = Major.objects.only('description').filter(major_cd__in=p_majors.values_list('major_cd', flat=True)).distinct().order_by("pk") if major_cd: processedoutputs = processedoutputs.filter(major_cd=major_cd) majors = majors.filter(major_cd=major_cd) if processedoutputs: serialized_p = ProcessedOutputsSerializer(processedoutputs, many=True) serialized_m = MajorSerializer(majors, many=True) newdict={ 'serialized_p': serialized_p.data, 'serialized_m': serialized_m.data, } return Response(newdict) else: return Response({}) processedoutputs.js: $.ajax({ method: 'GET', url: 'api/get_processedoutputs', beforeSend: function() { console.log('before send'); }, success: function(result) { update_table(result); console.log('after send'); }, error: function() { console.log('error'); } }); function find_majorcd() { let majorcd = document.getElementById('major_cd').value; let param = 'major_cd=' + majorcd; send_request(param); } function send_request(param) { $.ajax({ method: 'GET', url: 'api/get_processedoutputs?' + param, beforeSend: function() { console.log('before send'); }, … -
customize simple JWT functionality in DRF
I'm using JWT in my DRF project for authentication. I want to implement a logout view and I want to store user refresh token in my Redis DB for one day but my problem is that I don't know how simple jwt, generate a new access token using the refresh token. because I want to check the user refresh token before generating a new access token for the user. -
Django with Docker stuck on "Watching for file changes with StatReloader"
This is my code https://imgur.com/A49j4Dd When I run "python manage.py runserver 0.0.0.0:8000" it works perfectly fine. But when I use docker with "make compose-start" it doesnt work. Im trying to follow a python tutorial and cannot progress without fixing this. It just hangs there. https://imgur.com/fiujufu What do I do? Is something wrong? Anything else I could screenshot to help? -
TypeError: string indices must be integers error while uploading images
Here I have an array of image which I want to get in the django view and create each image object with every image. But I encounter this error TypeError: string indices must be integer view formdata = request.POST files = base64.decodestring(json.dumps(formdata)['files']) print('files',files) for file in files: Image.objects.create(img=file) template I have this array of files ["data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEASABIAAD…/qGldWDfsQAKCg/5nKrPVXMM0eq6v/DigKQAKCg//AIr/AP/Z", "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD…QF9qQZ7Hiiii4h2Tjrz796YSQQCaKKXUbEyc0oAx1NFFMR//Z", "data:image/jpeg;base64,/9j/4AAQSkZJRgABAgEAYABgAAD…tQEbmJcBs9Uxg8LzjFaQlGpdr5dv+HO3E0amEdndbfd1Z/9k="] "files -
How to indexing JSONField inside NestedField in Django using django_elasticsearch_dsl?
I have user model and comment, I am using django_elasticsearch_dsl to index in ElasticSearch # models.py class Comment(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) reply_type = models.JSONField(default=dict) Indexing to elastic I am doing it like this # documents.py @registry.register_document class UserDocument(Document): email = fields.TextField() username = fields.TextField() first_name = fields.TextField() ... ... ... comment = fields.NestedField(properties={ # other fields... 'some_field': fields.TextField(), 'reply_type': fields.ObjectField(), }) class Index: name = 'user' settings = { 'number_of_shards': 1, 'number_of_replicas': 0 } class Django: model = User The problem is that when I do the indexing the reply_type is empty "reply_type": [ { }, { } ] Any suggestion? -
new post gets inserted with other Post.. when i post, a separate box should be formed automatically for that perticular post. in django,html,css
1. css <style> li{ list-style-type: none; } </style> <style> *{ padding: 0; margin: 0; } h1{ font-size: 4vw; color: aqua; font-family: 'Lobster', cursive; position: relative; top: .8vw; left: .5vw; } h1 span{ color: yellow; } ul li a{ text-decoration: none; color: aqua; padding: .3vw; font-family: 'Hammersmith One', sans-serif; font-size: 2vw; } ul li a:hover{ color: yellow; } .nav li{ display: inline-block; position: relative; left: 65vw; bottom: 2.5vw; } .navbar{ background-color: #141526; height: 7.2vw; border-bottom: .5vw aqua solid; } body{ background-color:#090c12; } .main_body{ border: .5vw yellow solid; height: auto; width: 70vw; border-radius: 2vw; margin-left: 2vw; padding: 3.5vw; padding-top: 12vw; padding-bottom: 5vw; overflow: hidden; } .main_body ul li{ color: white; font-family: 'Poppins', sans-serif; position: relative; bottom: 6vw; font-size: 3vw; } #title{ font-size: 4vw; position: relative; bottom: 9vw; color: red; text-decoration: underline; font-family: 'Poppins', sans-serif; } #author{ font-size: 5vw; position: relative; bottom: 10vw; font-family: 'Poppins', sans-serif; color: white; } #delete{ position: relative; top: -3vw; text-decoration: none; background: red; color: black; font-size: 3vw; border-radius: .8vw; padding: .2vw; border: .2vw red solid; font-family: 'Hammersmith One', sans-serif; } #update{ position: relative; top: -3vw; left: .5vw; text-decoration: none; background: greenyellow; color: black; font-size: 3vw; border-radius: .8vw; padding: .2vw; border: .2vw greenyellow solid; font-family: 'Hammersmith One', sans-serif; } … -
Django: Is it possible to initialize an empty form (from formset) in template with a set prefix (other than __prefix__)?
I am using a model formset and adding new forms dynamically to it with {{ formset.empty_form }}. The thing is that I am also using django-ckeditor's RichTextField for one of the fields and, when I add a new form, the editor is not initialized for it. I can type in the text area, but I can't do anything with the editor. I have been told that django-ckeditor is not activated for new forms that are initialized with __prefix__ instead of a new form index. I can change the prefix after I get the new form, but it has already been initialized with __prefix__. The documentation doesn't seem to say much about this. I have also been told that I can change some javascript so django-ckeditor is activated for these newly added forms with __prefix__, but I'm a bit lost there and don't know which or where. So, if I can change this, I think I'll get the editor activated for these forms. -
How to get the latest file of an S3 bucket using Boto3?
I'm trying to get last added file in S3 specific folder. and I refer this(How to download the latest file of an S3 bucket using Boto3?) post and try. @api_view(("GET",)) def get_protocol(request, pk): union = Union.objects.get(pk=pk) s3 = get_s3_client() filepath = "media/private/" + str(pk) + "/certificate/docx" get_last_modified = lambda obj: int(obj["LastModified"].strftime("%s")) objs = s3.list_objects_v2( Bucket="unifolio", Prefix=filepath + "/" + "Union" + str(pk) + "_" + "certificate" + "3", ) last_added = [obj["Key"] for obj in sorted(objs, key=get_last_modified)][0] url = s3.generate_presigned_url( ClientMethod="get_object", Params={"Bucket": "unifolio", "Key": last_added}, # url 생성 후 60초가 지나면 접근 불가 ExpiresIn=60, ) return Response() but the error occur like below: File "/Users/kimdoehoon/project/unifolio/unions/api_views.py", line 199, in get_protocol objs_sorted = [obj["Key"] for obj in sorted(objs, key=get_last_modified)] File "/Users/kimdoehoon/project/unifolio/unions/api_views.py", line 194, in <lambda> get_last_modified = lambda obj: int(obj["LastModified"].strftime("%s")) TypeError: string indices must be integers I don't recognize why indices must be integer error. Could anybody kindly help me? -
Implement Apache2 + Django + Vuejs into one platform
I am stuck with the Integration of Django and vuejs with apache2 into one single application. Basically python manage.py runserver can run the django. Instead of running python manage.py runserver apache2 can do the job. So what I need to do is; need to integrate the apache2 to run both Django (BackEnd)+ vuejs(FrontEnd). I couldn't find a solution for this. Please help me to solve the problem. Currently Django is working along with apache2. But vuejs has no solution. To load vuejs application (FrontEnd), basically we need to run it separately in the terminal npm run serve. What I want to do is; when I run this code service apache2 reload. Backend (Django) and Frontend (vuejs) should load simultaneously. -
Login redirect url in django
I am building a website that have customer and merchant. Each of them have different login. what i want is each user to login to his own view. models.py class User(AbstractUser): is_customer=models.BooleanField(default=False) is_merchant=models.BooleanField(default=False) class Customer(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE, primary_key=True) class Merchant(models.Model): #user = models.ForeignKey(User, on_delete=models.CASCADE) user=models.OneToOneField(User,on_delete=models.CASCADE, primary_key=True) views.py #merchant view def users_homepage(request): product = Product.objects.filter(merchant=request.user.merchant).order_by('date_added') itemsordered=OrderItem.objects.filter(merchant=request.user.merchant) #customer view def index(request): listing=Category.objects.all() product=Product.objects.all()[:8] setings.py LOGIN_REDIRECT_URL='/users' please show me how i can do it. thanks beforehand. -
Implement one-to-many relation with one-to-one relation without circular dependency
I have two model, User & Company where a company may have multiple users and a single owner(which is also a user). A user can be associated with only one company. Now my question is, how am I supposed to maintain the Owner of any company? Because if I use any one-to-one relation field in Company model then it will give me circular-dependency error as I have foreign-key relation field in my User model. Models are given below: User model class User(BaseMixin, AbstractUser, BlameableMixin): """Extends django user with extra optional fields.""" role = models.ManyToManyField(Role) company = models.ForeignKey( Company, related_name='user_company_map', on_delete=models.SET_NULL, null=True, ) designation = models.CharField(max_length=max_length_medium, blank=True, unique=False) mobile_no = models.CharField(max_length=max_length_medium, blank=False, unique=False) organization = models.CharField(max_length=max_length_medium, blank=False, unique=False) Company model class Company(BaseMixin, BlameableMixin): """Company detail.""" name = models.CharField(max_length=max_length_large, blank=True, unique=False) code_name = models.CharField(max_length=max_length_large, blank=True, unique=True) domain = models.CharField(max_length=max_length_large, blank=True) As shown on the code above I have a foreign key field on User model that connects my User model to Company model. Now I would like to have a field that will help me to keep track of a user who is the owner of any specific company. It will be also very helpful if you provide the django-orm queries for … -
Dynamically redirecting in django
I am trying to dynamically redirect from one dynamic page to another. Think about being on an IMDB movie page (dynamic) and then following the link to the writer/director/actor page(dynamic). These are the urls: urlpatterns = [ path('', views.index, name="index"), path('writer/<int:id>', views.writer, name="writer"), path('title/<int:id>', views.title, name="title"), path('creator/', views.creator, name="creator"), ] This is the index.html: {% for pilots in pilot %} <div> <p>Title: <a href="title/{{ pilots.id }}">{{ pilots.title }}</a></p> {% for writers in pilots.creators.all %} <p>Writer: <a href="writer/{{ writers.id }}">{{ writers.writer }}</a></p> {% endfor %} </div> {% endfor %} This is the title.html (which the dynamic ahref isn't working): {% for title in titles %} <p>{{title.title}}</p> <p>{{title.count}}</p> <p>{{title.year}}</p> <p>{{title.description}}</p> {% for creators in title.creators.all %} <a href="creator/">{{creators.writer}}</a> {% endfor %} {% endfor %} And this is the views.py: def title(request, id): titles = Pilot.objects.filter(id=id) context = { 'titles': titles, } return render(request, 'title.html', context) def creator(request): return redirect(f'writer/{id}') -
Filter many-to-many field DRF
I need to filter my API response of document using a many-to-many category field. This is my model: class Document(models.Model): name = models.CharField(max_length = 100, blank = True) file = models.FileField(null = True, upload_to='documents/', validators=[FileExtensionValidator(allowed_extensions=['pdf'])]) date_created = models.DateTimeField(auto_now_add = True, null = True) category = models.ManyToManyField(Category) company = models.ForeignKey(Company, null = True, on_delete = models.SET_NULL) author = models.ForeignKey(Employee, null = True, on_delete = models.SET_NULL) The serializer for this models is: class DocumentSerializer(serializers.ModelSerializer): class Meta: model = Document fields = "__all__" And I'm trying to filter it with this: class DocumentFilter(filters.FilterSet): # having_category = filters.Filter(name = 'category', lookup_type = 'in') class Meta: model = Document fields = { 'company': ['exact'], 'author': ['exact'], # 'category': ['in'] } I tried using this solution as you can see in the code but wasn't successful. filtering with company and author are working, and I'm facing an issue only with category. How should I create the filter? -
Django validate_unique restricts update/patch
I have this model which is serialized via DRF class Orders(models.Model): accession = models.CharField(max_length=20) testcode = models.ForeignKey(TestCodes, on_delete=models.CASCADE, related_name='tcodes') # testName = models.ForeignKey(TestCodes, on_delete=models.CASCADE, to_field='testname', related_name='tnames') method = models.CharField(max_length=50, blank=True, null=True, default='NGS') custName = models.CharField(max_length=50) testSite = models.CharField(max_length=50) procedure = models.ForeignKey(Workflows, on_delete=models.CASCADE, blank=True, null=True) where I'm trying to make the accession and testcode fields combination unique to prevent user from creating the same accession with the same testcode def validate_unique(self, exclude=None): qs = Orders.objects.filter(accession=self.accession) if qs.filter(testcode=self.testcode).exists(): raise ValidationError('Accession must be unique per testcode') it works well but if I try to patch or update other fields it raises the validation error 'Accession must be unique per testcode' is there a workaround for this issue -
How to get all the appended sinlge input files?
Here user selects only one image at once and the selected image gets appended inside the ul tag. There is max limit to 5 images inside the ul tag but I am being unable to get all the files selected in my django view. I want to send those all the images inside the ul tag to the backend . Right now only the last image selected is passing. What I have to do for this ? js var prew = true; function readURL(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function(e) { var thumbnail = e.target.result; img = ` <li> <div class="image"> <img src="${e.target.result}" width="100" height="100"/> <div class="close"><div class="ic-close" id="img-remove"></div> </div></li> ` if (prew) { $("#thumbnail").attr('src', thumbnail); prew = false; } $('#blah').append(img); if ($('ul#blah li').length > 5) { $("#blah li:last-child").remove(); alert("You can't upload more than 5 images."); } } reader.readAsDataURL(input.files[0]); $('ul#blah').on('click', '.ic-close', function(e) { console.log('k'); $(this).closest('li').remove(); }); } } $("#imgInp").change(function() { readURL(this); //var files = $('#imgInp').prop('files'); //console.log(files) }); html <ul class="list list-inline list--image" id="blah"> <li class="thumbnail"> <div class="image"> <img id="thumbnail" src="" width="100" height="100" /> <p>Thumbnail</p> </div> </li> <div class="files--upload"><input class="d-none imgUpload" name="image" type="file" id="imgInp" placeholder="" /><label class="upload-label" for="imgInp"> <div class="ic-add"></div> <div class="mt-2">Add Photo</div> … -
Django: How to redirect UpdateView in the get request
I have a use-case in which if a drop-down changes, the view should be redirected to another view. In the update view, I am using built-in class-based view, UpdateView. How do I redirect if the redirect is needed before submitting the form. I take it that get_success_url() works for when the form is submitted -
How to solve local variable referenced before assignment and return form data in template correctly?
I want to return the item code and item number entered in the form in the template. This is a very simple application. views.py def index(request): csv_form = '' if request.method == 'POST': csv_form = CsvForm(request.POST, request.FILES) if csv_form.is_valid(): csv_itemcode= csv_form.cleaned_data['item_code'] csv_itemnumber= csv_form.cleaned_data['item_number'] else: csv_form = CsvForm() context = {'csv_itemcode': csv_itemcode, 'csv_itemnumber': csv_itemnumber,'csv_form':csv_form} return render(request,'colorlib-regform-6/submit.html',context) submit.html <html> <body> <h4>{{ csv_itemcode }}</h4> <h4>{{ csv_itemnumber }}</h4> </body> </html> I got local variable csv_itemcode referenced before assignment. Any suggestions towards this. -
When I create a single form, 2 forms appear. Why is that happening ? Thanks
Hello everyone i got a problem and i tried hard to fix it but i cant solve. When i add my form to my template (only using {{ form.dept }}) it happens 2 form on my site. My Models.py > class Kaydol(models.Model): name=models.CharField(max_length=40) surname=models.CharField(max_length=40) email=models.EmailField(max_length=100) DEPARTMENTS=[ ('BK', 'Hiç Birisi'), ('KK', 'Kredi Kartı ile Ödeme'), ('Çek', 'Çek ile Ödeme') ] dept=models.CharField(max_length=3, choices=DEPARTMENTS, default='BK') my forms.py > class KaydolForm(forms.ModelForm): class Meta: model = Kaydol fields = ['name', 'surname', 'email','dept'] widgets = { 'name': forms.TextInput(attrs={'placeholder':"Adınız"}), 'surname': forms.TextInput(attrs={'placeholder': "Soyadınız"}), 'email': forms.TextInput(attrs={'placeholder': "Email"}) views.py def kaydol(request): if request.method == 'POST': form = KaydolForm(request.POST) if form.is_valid(): form.save() form = KaydolForm() else: form = KaydolForm() form=KaydolForm() context = { 'form':form } return render(request,'index.html',context) and my html > <div class="col-sm-12"> <b>Alternatif Ödeme Kanalı</b> {{ form.dept }}