Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Custom 500 error page does not take the correct number of arguments - Django
I'm trying to prepare custom 404 and 500 error pages for a production. The 404 works fine, but I'm not able to run the 500. In my urls.py file: from client_interface.views.errors.server_error_view import ServerErrorView handler500 = ServerErrorView.as_view() views/errors/server_error_view.py: from django.shortcuts import render from django.views import View class ServerErrorView(View): def get(self, request): return render(request, "client_interface/errors/500.html") I'm getting ?: (urls.E007) The custom handler500 view 'client_interface.views.errors.server_error_view.ServerErrorView' does not take the correct number of arguments (request). error all the time. I tried to change the arguments of the get method to get(request) but it didn't help. -
Return QuerySet based on User group/permissions
I'm trying to figure out what's the "best practice" to limit QuerySets based on Users permissions. For example, there is a table of invoices on the dashboard. User that has Group called Admin can see all invoices but User that has group Broker can see only their own invoices. That means only invoices that have user = .... My idea is to create two permissions can_see_all_invoices and can_see_own_invoices. Now when I call the QuerySet using Django Rest Framework, I'll check for the permissions and return the filtered QuerySet. Or should I filter the QuerySet on the frontend and if Broker asks for all invoices I would raise PermissionError? Which of these approaches are being used or is there a different approach? -
why django default search gives error when we put in search box *?
DataError at invalid regular expression quantifier operand invalid I'm trying to create a very simple search function which would filter by a key word given into search form.why django default search gives error when we put in search box *? -
SAVE MULTIPLE CHECKBOX STATE AFTER RELOAD
I'm working on a django project that manages projects. Each project (bootstrap card) has a button that opens a modal with the project's detail. The modal contains a list of checkboxes. I want to store the state of the checkbox after the page reload. This is the code of the list of checkboxes: <p class="bold-elements">TASKS:</p> <ul class="list-group list-group-flush lista-tasks"> <div id="checkbox-container"> <div class="form-check"> <input name="dett1" store="checkbox1" class="form-check-input box" type="checkbox" value="" id="flexCheckDefault"> <label class="form-check-label" for="flexCheckDefault"> {{progetto.descrizione}} </label> <br><br> {% if progetto.task1 != "" %} <input name="dett2" store="checkbox2" class="form-check-input box" type="checkbox" value="" id="check1"> <label class="form-check-label" for="check1"> {{progetto.task1}} </label> <br><br> {% endif%} {% if progetto.task2 != "" %} <input name="dett3" store="checkbox3" class="form-check-input box" type="checkbox" value="" id="check2"> <label class="form-check-label" for="check2"> {{progetto.task2}} </label> <br><br> {% endif%} {% if progetto.task3 != "" %} <input name="dett4" store="checkbox4" class="form-check-input box" type="checkbox" value="" id="check3"> <label class="form-check-label" for="check3"> {{progetto.task3}} </label> <br><br> {% endif%} {% if progetto.task4 != "" %} <input name="dett5" store="checkbox5" class="form-check-input box" type="checkbox" value="" id="check4"> <label class="form-check-label" for="check4"> {{progetto.task4}} </label> </div> </div> </ul> I've found this javascript code to store the state: var boxes = document.querySelectorAll("input[type='checkbox']"); for (var i = 0; i < boxes.length; i++) { var box = boxes[i]; if (box.hasAttribute("store")) { setupBox(box); } } function setupBox(box) … -
how to make a comment post api in django related to the single blogpost detail?
I have a page where a blog post detail is displayed. Under the post, there is a section where user can comment after inputing thier name subject and text in a comment box. Now i have to make an api for this. I want to make a post api such that that comment is stored/associated to that particular blogpost detail. That means i need blogpost id to pass while posting comment. How to do that?? class BlogPost(models.Model): CATEGORY_CHOICES = ( ('travel_news', 'Travel News',), ('travel_tips', 'Travel Tips',), ('things_to_do', 'Things to Do',), ('places_to_go', 'Places to Go'), ) image = models.ImageField(blank=True, null=True) categories = models.CharField(max_length=64, choices=CATEGORY_CHOICES, default='travel_news') description = models.CharField(max_length=255) content = RichTextUploadingField() # todo support for tags tags = models.CharField(max_length=255, default='#travel') #todo date_created = models.DateField() @property def html_stripped(self): from django.utils.html import strip_tags return strip_tags(self.content) @property def comments(self): return self.comments_set.all() Here are my serializers: class CommentPostSerializer(serializers.ModelSerializer): class Meta: model = Comment # fields = '__all__' fields = ['name', 'email', 'subject', 'comment',] class BlogPostSerializer(serializers.ModelSerializer): comments = CommentListSerializer(many=True) class Meta: model = BlogPost fields = ['image', 'categories', 'description', 'content', 'tags', 'date_created', 'comments'] # fields = '__all__' Here is my view: class CommentCreateAPIView(APIView): queryset = Comment.objects.all() serializer_class = CommentPostSerializer -
Why does my Django form not work on submit?
So I'm using modelformset_factory, and my template renders it perfectly but submit button won't work. Let me show you my code:forms.py class AnswerForm(forms.ModelForm): answer = forms.CharField(required=False) share_to_others = forms.BooleanField(required=False) views.py from .models import Answer from .forms import AnswerForm def createAnswer(request, pk): AnswerFormSet = modelformset_factory(Answer, form=AnswerForm, extra=1) formset = AnswerFormSet( queryset=Answer.objects.filter(authuser=request.user.id, question_number=pk) ) if request.method == "POST": formset = AnswerFormSet(request.POST) if formset.is_valid(): instance = formset.save(commit=False) instance[0].authuser = request.user instance[0].question_number = thisQuestion instance[0].save() return redirect('/main') context = { 'formset':formset, } return render(request, '/answerPage.html', context) and my template ... <form method="POST" class="form-group">{% csrf_token %} <div class="row"> <div class="col"> {% crispy formset %} </div> </div> <div class="row"> <div class="col"> <button type="submit" class="btn">SUBMIT</button> </div> </div> </form> I don't see what I have done wrong. When I click the submit button, nothing happens and the page stays still. Any help is very much appreciated! :) -
Django preexisting tables not showing on shell
My database has few mysql tables which were prexixting i.e before django app migration.Ex: class Testesing(models.Model): users_id = models.IntegerField(blank=True, null=True) class Meta: managed = True db_table = 'test' Here this line says that don't create table because it is preexisting. managed = False Now the database to which my django app is connected has all tables, but in django shell it's only showing few tables which are not prexisting. When i run this command it only shows tables which were migrated using django app i.e newly created tables or tables created from app and not prexisting db tables.: from django.db import models I could see my prexisting db tables using this command in shell. [ m._meta.db_table for c in apps.get_app_configs() for m in c.get_models() ] I want to do crud operations with my tables but how can i fetch those tables: i.e want to do sometihing like this: Data = test.objects.all() -
Hit the database in loop make my site (how avoid it ?)
in the first this is my models: class MediaSecParnt(models.Model): withdegrey = models.ForeignKey(Degrey, on_delete=models.CASCADE) withsecondray = models.ForeignKey(Secondary, on_delete=models.CASCADE) nomberesteda = models.PositiveIntegerField(null=1, blank=1) nomberhodor = models.PositiveIntegerField(null=1, blank=1) date = models.DateField(null=1, blank=1) class Degrey(models.Model): name = models.CharField(max_length=200) class DegreyCompany(models.Model): withdegrey = models.ForeignKey(Degrey, on_delete=models.CASCADE, null=True, blank=True) company = models.ForeignKey(Secondary, on_delete=models.CASCADE, null=True, blank=True) spesial = models.ForeignKey('Spesial', on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200, default=withdegrey.name, null=True, blank=True) nomberetud = models.PositiveSmallIntegerField(null=True, blank=True) nomberexist = models.PositiveSmallIntegerField(null=True, blank=True) femail = models.PositiveSmallIntegerField(null=True, blank=True) reatrap = models.PositiveSmallIntegerField(null=True, blank=True) this for school when degree is the level studing DegreyCompany is the level of studing in every company mostally all have 3 level MediaSecParnt is Number of interviews with parents i use this queryset : mediasecparnt = MediaSecParnt.objects.select_related('withsecondray','withdegrey').filter(date__range=[primary1, primary2]).values('id', 'withdegrey__name', 'withdegrey__id', 'withsecondray__id', 'withsecondray__name', 'date','nomberesteda','nomberhodor') mediasecparnt = list(mediasecparnt) print(mediasecparnt) result come : [{'id': 2, 'withdegrey__name': 'level one', 'withdegrey__id': 1, 'withsecondray__id': 1, 'withsecondray__name': 'company one', 'date': datetime.date(2020, 9, 17), 'nomberesteda': 100, 'nomberhodor': 20}, {'id': 3, 'withdegrey__name': 'level one', 'withdegrey__id': 2, 'withsecondray__id': 1, 'withsecondray__name': 'company two', 'date': datetime.date(2020, 9, 30), 'nomberesteda': 10, 'nomberhodor': 2}] till now everything is good i want to accses to the 'nomberetud' with is colmune in table 'DegreyCompany' i use this request : mediasecparnt = MediaSecParnt.objects.select_related('withsecondray','withdegrey').filter(date__range=[primary1, primary2]).values('id', 'withdegrey__name', 'withdegrey__id', 'withsecondray__id', 'withsecondray__name', 'date','nomberesteda','nomberhodor') just … -
How can i filter before render page?
I want to filter some objects through sector. Here is my model: class Videos(models.Model): brand = models.CharField(max_length=255, verbose_name="Brand Name", blank=False, null=True) sector = models.CharField(max_length=255, verbose_name="Sector Name", blank=False, null=True) video = models.FileField(upload_to="videos/") And this is my view where i want to filter it: def automotive(request): videos = Videos.objects.filter() The thing is in my navbar i've few sector names. When user clicks one, it should render video with sector name that user clicked. For example, one of my sector name is Automotive. So when i click that, i should see videos that only sector is Automotive. So sorry for my broken English, i tried my best... -
Tiny MCE and Django
I was trying to build a blogging website. I used Tiny MCE and Django for the purpose. I could add/upload photos to my blogs. But the problem is the images uploaded via Tiny MCE are not responsive for smaller screens like a mobile phone screen. The texts are well responsive but the images are overflown. I went through Tiny MCE documentation but didn't find the answer. Here's my set of code: tinyinject.js: (I am not so good with JS) var script = document.createElement('script'); script.type = 'text/javascript'; script.src = "https://cdn.tiny.cloud/1/no-api-key/tinymce/5/tinymce.min.js"; document.head.appendChild(script); script.onload = function () { tinymce.init({ selector: '#id_content', plugins: [ 'advlist autolink link image imagetools lists charmap print preview hr anchor pagebreak', 'searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking', 'table emoticons template paste help' ], toolbar: 'insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | ' + 'bullist numlist outdent indent | link image | print preview media fullpage | ' + 'forecolor backcolor emoticons | help | image', imagetools_toolbar: "rotateleft rotateright | flipv fliph | editimage imageoptions", image_title: true, automatic_upload: true, file_picker_types: 'image', file_picker_callback: function(cb, value, meta) { var input = document.createElement('input'); input.setAttribute('type', 'file'); input.setAttribute('accept', 'image/*'); input.onchange = function() { var file … -
Django , adding images to the same object
i have this two models with a relationship 1-N: def get_image(instance, filename): return os.path.join('intervencao/fotografias', str(instance.intervencao), filename) class Intervencao(models.Model): ...... class Imagem(models.Model): intervencao = models.ForeignKey(Intervencao, related_name='intervencaoObjectsImagem', on_delete=models.CASCADE) imagem = models.ImageField(upload_to=get_image, blank=True, null=True, verbose_name="Fotografia") def __str__(self, ): return str(self.intervencao) So i have one form for each model , and i want to add some images for the same object My form class TabletForm2(forms.ModelForm): class Meta: model=Intervencao ..... class TabletFormImagem(forms.ModelForm): class Meta: model=Imagem fields = ['imagem'] imagem = forms.ImageField(required=True) My view def project_detail_chefe(request, pk): form = TabletForm2(request.POST or None, instance=instance) form2 = TabletFormImagem(request.POST, request.FILES) if request.method == "POST": if form.is_valid() and form2.is_valid(): instance_form1 = form.save() instance_form2 = form2.save(commit=False) instance_form2.intervencao = instance_form1 instance_form2.save() return redirect('project_detail_chefe',pk) else: form = TabletForm2(request.POST) form2 = TabletFormImagem() context = { 'form':form, 'form2':form2, } return render(request, 'tablet/info_chefes.html', context) tablet/info_chefes.html <form method="post" enctype="multipart/form-data" id="gravar"> {% csrf_token %} <!--First image--> <div class="row"> <div class="col-md-12"> {% for fotografia in intervencao.intervencaoObjectsImagem.all %} <div class='form-group'> <label id='titulo'>Fotografia:</label> <em><a href ="/media/{{fotografia.imagem|default_if_none:''}}" target="_blank" > {{fotografia.imagem|default_if_none:''}}</a></em> <img src="/media/{{fotografia.imagem|default_if_none:''}}" alt="..." class="img-thumbnail"> </div> <hr> {% endfor %} {{ form2.as_p }} </div> <div class="row"> <div class="col-md-12"> <hr> {% endfor %} {{ form.as_p }} </div> </div> <!--Seconde image--> <div class="row"> <div class="col-md-12"> {% for fotografia in intervencao.intervencaoObjectsImagem.all %} <div class='form-group'> <label id='titulo'>Fotografia:</label> … -
Get username or user as initial value on forms in django
I would like to get initial value on the following form but i get error : name 'user' is not defined. I don't know how to get user.username. class InvoiceForm(ModelForm): date = forms.DateField(widget=DateInput) company = forms.CharField(initial={"company": user.username}) class Meta: model = Invoice fields = "__all__" and the view to create the invoice is : class InvoiceCreate(CreateView): form_class = InvoiceForm model = Invoice template_name = "sales/invoice_form.html" def get_success_url(self, request): return reverse_lazy('invoice_details', kwargs={'pk' : self.object.pk}) def get(self, request, *args, **kwargs): self.object = None form_class = self.get_form_class() form = self.get_form(form_class) formset = InvoiceItemFormSet() products = list(Product.objects.values()) return self.render_to_response( self.get_context_data(form=form,formset=formset, products=products)) def post(self, request, *args, **kwargs): self.object = None form_class = self.get_form_class() form = self.get_form(form_class) formset = InvoiceItemFormSet(self.request.POST) if (form.is_valid() and formset.is_valid()): return self.form_valid(form, formset) else: return self.form_invalid(form, formset) def form_valid(self, form, formset): self.object = form.save() formset.instance = self.object formset.save() try: addmore = self.request.GET["addmore"] if addmore == "True": return redirect("update_invoice", pk=self.object.id) except Exception as e: pass return HttpResponseRedirect(self.get_success_url()) def form_invalid(self, form, formset): return self.render_to_response(self.get_context_data(form=form, formset=formset)) I would like to get initial value on the following form but i get error : name 'user' is not defined. I don't know how to get user.username. -
django-import-export package get Foreignkey value while Export to XL file
First pardon me for my bad english. I am very new in Django Framework. I want to Export a foreignkey value called title which is in 'Product' model. There is multiple Foreignkey Relations between different django app models. Please take a look below all of this models: products/models.py class Product(models.Model): title = models.CharField(max_length=500) brand = models.ForeignKey( Brand, on_delete=models.CASCADE, null=True, blank=True) image = models.ImageField(upload_to='products/', null=True, blank=True) price = models.DecimalField(decimal_places=2, max_digits=20, default=450) old_price = models.DecimalField( default=1000, max_digits=20, decimal_places=2) weight = models.CharField( max_length=20, help_text='20ml/20gm', null=True, blank=True) size = models.CharField( max_length=10, help_text='S/M/L/XL/32/34/36', null=True, blank=True) active = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now=True) carts/models.py class Entry(models.Model): product = models.ForeignKey(Product, null=True, on_delete=models.CASCADE) cart = models.ForeignKey(Cart, null=True, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) price = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) last_purchase_price = models.DecimalField( default=0.0, max_digits=20, decimal_places=15) weight_avg_cost = models.DecimalField( default=0.0, max_digits=20, decimal_places=15) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-timestamp'] And my working models is analytics/models.py, from where I want to export the product title in XL sheet. class AllReportModel(models.Model): # All report model invoice = models.ForeignKey(Invoice, on_delete=models.CASCADE, null=True, blank=True) ws_invoice = models.ForeignKey(WholesaleInvoice, on_delete=models.CASCADE, null=True, blank=True) entry = models.ForeignKey(Entry, on_delete=models.CASCADE, null=True, blank=True) stock_quantity = models.IntegerField() timestamp = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now=True) and Finally analytics/admin.py is : class … -
unknown directive "mywebsite.co.uk" in /etc/nginx/conf.d/flaskapp.conf:3
Running nginx -t in terminal results in nginx: [alert] could not open error log file: open() "/var/log/nginx/error.log" failed (13: Permission denied) 2020/10/19 08:43:08 [warn] 127100#127100: the "user" directive makes sense only if the master process runs with super-user privileges, ignored in /etc/nginx/nginx.conf:1 2020/10/19 08:43:08 [emerg] 127100#127100: unknown directive "mywebsite.co.uk" in /etc/nginx/conf.d/flaskapp.conf:3 nginx: configuration file /etc/nginx/nginx.conf test failed Is this an error to do w my domain "mywebsite.co.uk" or is something not configured right? I'm new to this so would appreciate any help and lmk if you need any further files. -
EmbeddedDocument ChoiceField
I have a model, lets call it A, with field: downloadable_material = fields.ListField(fields.EmbeddedDocumentField('Downloadable'), verbose_name='') Those documents are being created in 'A' Form. I want my 'A' Form to also have a MultipleChoiceField which lets you choose from already added 'downloadable_material'. Of course I want my choices to be saved in model 'A'. Here's a use-case scenario, just to be more clear: I open my 'A' Form in browser I create a couple 'downloadable_material' documents inside my 'A' Form, for example I've created DM1 and DM2. I click on my multiplechoicefield, which in this case lets me choose from DM1 and DM2. Let's pretend I've chosen only DM1, now I click save object As a result I would like to have an object, which has DM1 and DM2 in downloadable_material and DM1 in, for example, additional_material. Sure this sound complicated, you can ask me any question to make sure you have got the idea of my problem. -
Django project using scrapy on windows
I want to develop a Django project that uses scrapy. I am working on Windows and know that scrapy should be installed on Windows using Anaconda/conda. However, I don't know how to use scrapy installed by conda in my Django project. In Python shell import scrapy raises an error message. Is it possible to use Django+scrapy on Windows or I have to switch to Linux? -
Django - Reverse a queryset
I have very basic view with queryset, but for some reason I cannot reverse it. def home(request): posts = Post.objects.all().reverse() return render(request, "home.html", {'posts': posts}) For some reason no matter how I change code - instanses from queryset always rendering in same order. Below there are lines of code that I already tried and which didn't worked for some reason: Post.objects.all().reverse() Post.objects.order_by('-date') Post.objects.order_by('date').reverse() home.html: {% for post in posts %} {{ post.title }} {{ post.content }} {% endfor %} models.py: class Post(models.Model): title = models.CharField(max_length=100, unique=True, blank=True, null=True) image = models.URLField(blank=True, null=True, unique=True) content = models.TextField(blank=True, null=True) date = models.DateField(auto_now=False, auto_now_add=True) #To make in name, not objXXX def __str__(self): return self.title -
Build tools for using Github Actions for CI Pipeline for Python Django Project
Do you need a build tool like PyBuilder/Setuptools/etc. to have a CI Pipeline with Github actions for a Python Django app, or is a virtual environment and pip enough? -
How to properly configure certbot in docker?
Please help me with this problem, i have been trying to solve it for 2 days! Please, just tell me what i am doing wrong. And what i should to change to make it work! And what i should to do to take it work. ERROR: for certbot Cannot start service certbot: network 4d3b22b1f02355c68a900a7dfd80b8c5bb64508e7e12d11dadae11be11ed83dd not found My docker-compose file version: '3' services: nginx: restart: always build: context: ./ dockerfile: ./nginx/Dockerfile depends_on: - server ports: - 80:80 volumes: - ./server/media:/nginx/media - ./conf.d:/nginx/conf.d - ./dhparam:/nginx/dhparam - ./certbot/conf:/nginx/ssl - ./certbot/data:/usr/share/nginx/html/letsencrypt server: build: context: ./ dockerfile: ./server/Dockerfile command: gunicorn config.wsgi -c ./config/gunicorn.py volumes: - ./server/media:/server/media ports: - "8000:8000" depends_on: - db environment: DEBUG: 'False' DATABASE_URL: 'postgres://postgres:@db:5432/postgres' BROKER_URL: 'amqp://user:password@rabbitmq:5672/my_vhost' db: image: postgres:11.2 environment: POSTGRES_DB: postgres POSTGRES_USER: postgres certbot: image: certbot/certbot:latest command: certonly --webroot --webroot-path=/usr/share/nginx/html/letsencrypt --email artasdeco.ru@gmail.com --agree-tos --no-eff-email -d englishgame.ru volumes: - ./certbot/conf:/etc/letsencrypt - ./certbot/logs:/var/log/letsencrypt - ./certbot/data:/usr/share/nginx/html/letsencrypt My Dockerfile FROM python:3.7-slim AS server RUN mkdir /server WORKDIR /server COPY ./server/requirements.txt /server/ RUN pip install -r requirements.txt COPY ./server /server RUN python ./manage.py collectstatic --noinput ######################################### FROM nginx:1.13 RUN rm -v /etc/nginx/nginx.conf COPY ./nginx/nginx.conf /etc/nginx/ RUN mkdir /nginx COPY --from=server /server/staticfiles /nginx/static nginx.conf file user nginx; worker_processes auto; error_log /var/log/nginx/error.log warn; events { worker_connections 1024; } … -
VSCode debugging error AttributeError: type object 'winpty.cywinpty.Agent' has no attribute '__reduce_cython__'
I'm on windows and building an app with django=3.0.3 and python 3.7.9. I'm on Windows 10. While I debug the app in VSCode I get this error: AttributeError: type object 'winpty.cywinpty.Agent' has no attribute '__reduce_cython__' on an import: from notebook import notebookapp The app works perfectly fine when run on windows commandline. There is a discussion in another page for a similar error but mine is specific to the VSCode debugging. This is driving me mad. -
What are the possibilities to integrate phaser with react
I have the question about the Phaser (JS Game library) integration with React. I know that I can use the ion-phaser lib to add this lib to work in react, but lets assume I don't want to write the code from scratch again. Brief info: I have a full working set of games working in django. Each game has 2 scenes, starting with intro and playable with game itself. I have to move the logic etc to the another app that is react based on the frontend. Due the lack of time is it possible to somehow copy the code (all .js files) put them into public dir of react app and put them into iframe, or div. Maybe someone has similar situation. Rewriting the code base to fit ion-phaser lib frames could take a while. There are like 20 games with different logic and specific to django references. -
Why is jwt issued by another server also authenticated by my server in django rest framework?
I used the djangoreostframework-simplejwt module to implement jwt authentication in django rest framework. Using this, login class was created and user authentication was carried out normally when the user sent the request after putting the access to the header issued when accessing the views that require authentication among other views. The problem is that it also worked normally when I tried to authenticate with the access token issued by another server that applied the djangoreostframework-simplejwt. Could you check if there is any problem with my authentication method? Here's my code. views.py class customLoginView (GenericAPIView) : serializer_class = customLoginSerializer def post (self, request) : serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) try : user = User.objects.get(email=serializer.data['email']) except User.DoesNotExist : return Response({'message': ['이메일 또는 비밀번호를 확인해주세요.']}, status=401) if user.check_password(raw_password=serializer.data['password']) == False : up = serializer.data['password'].upper() if user.check_password(raw_password=up) == False : down=serializer.data['password'].lower() if user.check_password(raw_password=down) == False : return Response({'message': ['이메일 또는 비밀번호를 확인해주세요.']}, status=401) if not user.is_verified : return Response({'message': ['이메일 인증을 먼저 해주세요.']}, status=401) if not user.is_active : return Response({'message': ['계정이 비활성화 되었습니다. 관리자에게 문의하세요.']}, status=401) token = RefreshToken.for_user(user) data = { 'token_type': 'Bearer', 'access_token': str(token.access_token), 'expires_at': str((datetime.now() + timedelta(minutes=30)).astimezone().replace(microsecond=0).isoformat()), 'refresh_token': str(token), 'refresh_token_expires_at': str((datetime.now() + timedelta(hours=8)).astimezone().replace(microsecond=0).isoformat()) } return Response(data, status=200) serializers.py class customLoginSerializer (serializers.ModelSerializer) : … -
TemplateSyntaxError at /music/ Invalid block tag on line 6: 'path', expected 'empty' or 'endfor'. Did you forget to register or load this tag?
I wanted to remove a hardcoded urls and used a dynamic coded urls and load it over the server but I am receiving an error as: TemplateSyntaxError at /music/ Invalid block tag on line 6: 'path', expected 'empty' or 'endfor'. Did you forget to register or load this tag? Here are my code: index.html: {% if all_albums %} <h3>here are all my albums:</h3> <ul> {% for album in all_albums %} <li><a href = "{% path 'music:detail' album.id %}"> {{ album.album_title }}</a></li> {% endfor %} </ul> {% else %} <h3>You don't have any Albums</h3> {% endif %} music.urls.py: from django.urls import path from . import views app_name = 'music' urlpatterns = [ # /music/ path('', views.index, name='index'), # /music/712/ path('<int:album_id>/', views.detail, name='detail'), ] music.views.py: from django.shortcuts import render, get_object_or_404 from .models import Album # noinspection PyUnusedLocal def index(request): all_albums = Album.objects.all() return render(request, 'music/index.html', {'all_albums': all_albums}) # noinspection PyUnusedLocal def detail(request, album_id): album = get_object_or_404(Album, pk=album_id) return render(request, 'music/detail.html', {'album': album}) Analytic_practice.urls: from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('music/', include('music.urls')), ] -
How to add an attribute to a Django model from a view?
I have a Django application and I'm trying to add attributes to my Django model according to user datas. I have added some new attributes such as below; def add_new_columns(column_dict): conn = mysql.connector.connect( user=username, password=password, host=host, database=dbname ) cursor = conn.cursor() for key, value in column_dict.items(): sql_data = "ALTER TABLE data_data ADD %s varchar(50);" % (key) cursor.execute(sql_data) sql_cost = "ALTER TABLE cost_cost ADD %s varchar(50);" % (key) cursor.execute(sql_cost) sql_optimize_cost = "ALTER TABLE optimize_cost_optimizecost ADD %s varchar(50);" % (key) cursor.execute(sql_optimize_cost) conn.close() However when I try to create a ModelForm with the attributes that defaults and the new added attributes, I'm getting the error below even if the database contains the new added attributes; Unknown field(s) (color) specified for Data How can I create the ModelForm and add object to that model with new added columns? -
Django Admin Page is looking very Ugly(without CSS I think)
Recently I hosted my django website on EC2 ubuntu Instance with nginx server on AWS. When I open my admin page of this website IT is looking very ugly and there is not css but on local server 127.0.0.0:8000 it works fine. I also inspect on browser console, It is giving this error: GEThttp://jassem.in/static/admin/css/dashboard.css [HTTP/1.1 404 Not Found 51ms] The resource from “http://jassem.in/static/admin/css/nav_sidebar.css” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff). admin The resource from “http://jassem.in/static/admin/css/base.css” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff). admin The resource from “http://jassem.in/static/admin/js/nav_sidebar.js” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff). admin The resource from “http://jassem.in/static/admin/css/responsive.css” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff). admin The resource from “http://jassem.in/static/admin/css/dashboard.css” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff). admin How can I get back my previous django admin page. FYI I am a newbie on web technology and Django