Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Decorator for Queries
I have multiple pages where I pull three sets of data. One set of data is always different, while the other two sets are always the same. Is there a way to make the two constant data into a decorator so I don't have to keep keying them? Thank you. views.py @constants_decorator def page01_view(request): data01 = Data01.objects.all() constant01 = Constant01.objects.all() constant02 = Constant02.objects.all() context = { 'data01': data01, 'constant01': constant01, 'constant02': constant02, } return render(request, 'page01.html', context) @constants_decorator def page05_view(request): data05 = Data05.objects.all() constant01 = Constant01.objects.all() constant02 = Constant02.objects.all() context = { 'data05': data05, 'constant01': constant01, 'constant02': constant02, } return render(request, 'page05.html', context) I'm still trying to understand how Decorator works and all the examples i've watch and read thru are very simple and nothing with passing data. I've tried below, but my pages are coming up empty. decorator.py def constants_decorator (view_func): def wrapper_func(request, *args, **kwargs): constant01 = Constant01.objects.all() constant02 = Constant02.objects.all() context = { 'constant01': constant01, 'constant02': constant02, } return view_func(request, *args, **kwargs) return wrapper_func -
django 3, render two forms in template
I have two forms of two models, I need to send them in my template, previously in django 2 it worked fine, but now that I update to django it does not return well I get the source code, if I remove the dict and the RequestContext (request)) in views.py it redeems me the html but it does not show my forms, I show the following code forms.py class UserForm(UserCreationForm): class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2') class UserProfileForm(ModelForm): class Meta: model = UserProfile fields = ('empresa', 'telefono', 'rfc', 'upload') urls.py urlpatterns = [ url(r'^registro$', views.registro, name='registro'), ] views.py def registro(request): if request.method == 'POST': uf = UserForm(request.POST, prefix='user') upf = UserProfileForm(request.POST, prefix='userprofile') if uf.is_valid() * upf.is_valid(): user = uf.save() userprofile = upf.save(commit=False) userprofile.user = user userprofile.save() name = 'Registro Pagina' email = 'main@example.com' fullemail = name + " " + "<" + email + ">" content = {"%s: %s" % (key, value) for (key, value) in list(request.POST.items())} content = "\n".join(content) message = str(upf) msg = EmailMessage('new register', content, fullemail, ['main@example.com', 'other@example.com']) #msg.content_subtype = "html" # Main content is now text/html msg.send() return HttpResponseRedirect('/') else: uf = UserForm(prefix='user') upf = UserProfileForm(prefix='userprofile') return render(request, 'cfdipanel/register.html', … -
Generate Private key for SSL Certificate to be used inside Docker Container
I'm working on a project that runs Docker and has 3 containers: Django PostgreSQL traefik Now I'm going to generate a private key to add an SSL certificate to my website, the question is where should I generate private key? Inside the main server that running the Docker? or inside the Django container? or inside Traefik container? I'm using trafik:alpine for trafik & python:3.6-alpine for Django if it is the container where I should generate a private key, What is the command line should I use inside container to generate a private key? Actually I have built private.key and certification.crt files referenced them inside traefik.toml file and i got this error: failed to load X509 key pair: tls: failed to find any PEM data in certificate input That's why I think the problem is with my private.key which I generated inside the main server not inside any container. Here is the configuration i use inside traefik.toml file if you want to know more information: logLevel = "INFO" defaultEntryPoints = ["http", "https"] # Entrypoints, http and https [entryPoints] # http should be redirected to https [entryPoints.http] address = ":80" [entryPoints.http.redirect] entryPoint = "https" # https is the default [entryPoints.https] address = … -
FullCalendar Django model
I am a newbie and don't know much about using Fullcalender. I am trying to show my saved Full Calender event from django model in full calender but it is not displaying the saved event. I just want to show event name on the date specified. I have tried multiple methods including these two options Please help -
Pass html dropdown option as api call Django
Attempting to construct a simple Django app where a user can enter text search criteria and select from a drop down list of providers then these are passed as an api call (news api) views.py def api_request(request): search_term = request.POST.get('textfield') source = request.POST.get('list_providers') url = 'https://newsapi.org/v2/everything?' parameters = { 'q': '%s' % search_term, 'sources': '%s' % source, } response = requests.get(url, params=parameters) response_json = response.json() articles = response_json['articles'] return render(request, 'news.html', context={"articles": articles, "search_term": search_term, "source": source}) home.html {% block content %} <form method="POST"> {% csrf_token %} <input type="text" name="textfield", placeholder="Enter search criteria"> <br/> <select name = "list_providers"> <option value = "option1">Option 1</option> <option value = "option2">Option 2</option> <option value = "option3">Option 3</option> </select> <br/> <button type="submit">Search</button> </form> {% if search_term & sources %} {% for title, author, date, des in mylist %} <h3>Title:</h3> {{title}} <h4>Published by:</h4> {{author}} <h4>Published at:</h4> {{date}} <h4>Summary:</h4> {{des}} {{value | linebreaks}} <br/> {% endfor %} {% endif %} {% endblock %} But the error given on page load is: KeyError at / 'articles' I have been able to pass multiple text input criteria without error so believe the issue is possibly in the default selection criteria for the dropdown. -
Djnago: Bootstrap3 form dropdown options display issue
I am using bootstrap3 in django template to display dropdown menu so that user can select the option they chooses. After selecting the option, selected option is not displaying clearly. See below images. While selecting the options After selecting the option its displays like below It's hard to see what option user selected. How to fix this issue so that user can see clearly see what option they chose? below is the html code I am using for this {% extends 'base.html' %} {% load bootstrap3 %} {% block content %} <body> <section class="hero p9"> <div class="explore-section"> <div class="container"> <form method="post" > {% csrf_token %} {% bootstrap_form form %} <button class='btn btn-default' type='submit'>Select</button> </form> </div> </div> </section> </body> {% endblock content %} FYI, this is the below is the form I am using for this. class selectPostTypeForm(forms.Form): STATUS_CHOICES = (('1', 'Text Post'),('2', 'Image Post'),('3', 'Video Post'),) post_type = forms.ChoiceField(choices=STATUS_CHOICES) -
How to create / use a custom backend for Django
I'm still learning to use the Django framework, so I might be in over my head here, but I'm trying to use a backend that is not officially supported by Django. I recently stumbled upon Deta and after messing around with it a bit I thought it would be an great to host my Django project on it, to support the developers of Deta and to familiarize myself with the service some more.. To keep things simple I thought of using the database service provided by Deta: Deta Base, for the backend of my Django project instead of a traditional SQL database that I would have to host somewhere else. I haven't found much information on using or creating a custom backend for Django although I assume it is probably complicated and not recommended because of Django's ORM. I would love to hear the opinion of more experienced Django developers on the subject to know if my idea is even possible and worth it (in terms of time/effort required). Thanks for reading this far ;-) -
Compare items from InlineFrom before saving Django
I have an InlineForm on my forms that I save a list of names, but I'd like to check if the names are different before saving it. When I try a FOR to save the names in a list, I get the individual letters instead. How can I solve this problem? Here's my form and validation code: forms.py class ColabForm(forms.ModelForm): class Meta: model = Colaboradores fields = '__all__' colaborador_projeto = forms.CharField(label="Colaborador do Projeto", widget=forms.TextInput( attrs={ 'class': 'form-control col-8', 'maxlength': '200', } )) def clean(self): colaborador_projeto = self.cleaned_data.get('colaborador_projeto') lista_erros = {} verifica_nome(colaborador_projeto) if lista_erros is not None: for erro in lista_erros: mensagem_erro = lista_erros[erro] self.add_error(erro, mensagem_erro) return self.cleaned_data validation.py def verifica_nome(colaborador_projeto): lista_nomes = {} loop = 0 for nome in colaborador_projeto: lista_nomes[loop] = nome loop += 1 print(lista_nomes) Here's how the print shows: {0: 'V', 1: 'i', 2: 'c', 3: 't', 4: 'o', 5: 'r'} {0: 'J', 1: 'é', 2: 's', 3: 's', 4: 'i', 5: 'c', 6: 'a'} {0: 'L', 1: 'e', 2: 't', 3: 'i', 4: 'c', 5: 'i', 6: 'a'} P.S.: I know I'm not sending the errors list yet. I wanna solve the 'comparing names' problem first, before I send the error to my HTML page. -
Django Elastic Beanstalk Implementing Cron job
I am trying to set a cron job on my project to send a email after 15 minutes. 04_cronjb: command: "* * * * * source /opt/python/run/venv/bin/activate && python manage.py cronjb" leader_only: true This is what i am using in config file But when i try to deploy my project it shows a weird error Command failed on instance. Return code: 127 Output: /bin/sh: __init__.py: command not found. init.py is the file which is in root of my folder. When i try the simple command 04_cronjb: command: "source /opt/python/run/venv/bin/activate && python manage.py cronjb" leader_only: true It works fine. What am i doing wrong in this? -
convert django api to django-rest-framework api with 200 response code
Here is my code which sends 200 api response after doing some stuffs. It is working but, I wants to convert this as django-rest-framework way with DRF template. def refresh_dashboard(request): profile = request.session["profile"] refresh_profile_events(profile) # refresh_profile_events.apply_async(args=[profile]) return JsonResponse({"code": 200, "msg": "success"}) Below code i am using but it is giving below error. Please have a look how we can achive this class RefreshAPIView(RetrieveAPIView): permission_classes = (IsAuthenticated,) def get_object(self): user = self.request.user return type('DashboardData', (), {"code": 200})() Error: assert self.serializer_class is not None, ( AssertionError: 'RefreshAPIView' should either include a `serializer_class` attribute, or override the `get_serializer_class()` method. -
Searchable Dropdown for many to many field in django model form
How can I Create a Searchable Dropdown for many to many fields in Django model form? I tried using django-searchable-select but this is not available for django 3.0 Can somebody help me ????? -
Create DRF request object programmatically
I'm building a chat application using DRF & Channels. Since sockets are not reliable and as a fall-back, channels themselves recommend to use APIs as a fallback. I've built the APIs, now trying to use the same Views/Viewset to integrate with the socket events too. class InboxViewset(viewsets.ModelViewSet): serializer_class = InboxSerializer queryset = Inbox.objects.all() The idea is my different socket events would be ViewName_Method, for eg:- InboxViewset_list. So, whenever the Django channel consumer instance receives an event with event_type as InboxViewset_list, I would initialize the view and return the same JSON response returned by it. view = InboxViewset() return view.list() Hence following the DRY and reusability principles. Now, for this to happen I would need to create DRF request object. I tried exploring that but could figure it out. This is what I tried. from django.http import HttpRequest from rest_framework.request import Request djrequest = HttpRequest() user = User.objects.first() djrequest.user = user djrequest.query_params = {} djrequest.META['SERVER_NAME'] = '127.0.0.1' djrequest.META['SERVER_PORT'] = '80' request = Request(request=drequest) view = InboxViewset(request=request) view.list(request=request) How can I replicate creating a DRF request programmatically? -
Flutter sending a post request to a Django API with a file as the body
I have a Django API where a user is able to upload a file through a post request with the following body: { "file": *attached file* } In Django, the file is gathered from the request with request.FILES['file'] The request has to be sent from flutter (dart) code. I have tried a few ways, this is the function from my latest attempt which shows an error - because the "file" is not in the correct format. static void uploadProfilePhoto(File file, String fileId) async { Uint8List fileBytes = file.readAsBytesSync(); var response = http.post( globals.baseURL() + "/upload/", //headers: {"Content-Type": "application/json"}, body: { "file":base64Encode(fileBytes) } ).then((v)=>print("v: "+v.body)); } Any idea in what format the "file" should be sent from flutter? Else is there any other method which might work? Thank you in advance. -
Python object response in development is different of production response
I already use a code that call an API request and from nothing this broken my code. I tried to check what happening, my object response does not have a valid json. The instruction that I use is: def get_tickers(self, symbols): """Get tickers.""" data = {"symbols": symbols} return self.session.get("%s/public/ticker" % self.url, params=data).json() This work well until broken for nothing. I use the same Dockerfile in Prod environment and Dev environment to prevent some differences that could be showing In dev (Mac OS) my code still working and returns me this response: [{'symbol': 'ETHBTC', 'ask': '0.034707', 'bid': '0.034705', 'last': '0.034699', 'low': '0.034477', 'high': '0.035257', 'open': '0.035083', 'volume': '89442.2126', 'volumeQuote': '3117.3903987376', 'timestamp': '2020-09-19T16:04:57.968Z'}, {'symbol': 'BTCUSD', 'ask': '11084.95', 'bid': '11084.14', 'last': '11086.54', 'low': '10813.93', 'high': '11177.98', 'open': '10890.52', 'volume': '18086.71200', 'volumeQuote': '198275586.9755433', 'timestamp': '2020-09-19T16:04:58.020Z'}] In Prod this result is not a valid json, I know that single quotes is not a valid json, but, my questions is: Why in dev this working and prod not? I using python 3.8. Same dockerfile, same versions, same code, same base. Anyone already get this error? -
Instead having a base.html in global templates directory , template does not exist error is coming
I am not able to extend base.html inside templates folder in app 'todo'. base.html is present inside templates folder in main directory. -
two problem in config ssh collectstatic and nginx
hello i have two problem one is small the other is large in the ssh project Django 1-collectstatic gives an error 0 static files copied to 'home/name/nameprojects/staticfiles', 162 unmodified, 666 post-processed. 2-i try to disable apache to configure nginx nginx does not want to install correctly -
Trying to print zip column from the database using rest api
Error saying that too many values to unpack (expected 2). models.py @api_view(["GET"]) def zipcodes(request): tasks= ZipCodes.objects.get('zip') if request.method == "GET": serializer = TaskSerializer(tasks, many=True) return Response(serializer.data) -
Django comment replies
I have a problem with implementing replies to comments. models.py class Comment(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField(blank=False, null=False, max_length=500, verbose_name='Treść') date_of_create = models.DateTimeField(default=timezone.now) post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True) topic = models.ForeignKey(Topic, on_delete=models.CASCADE, null=True) comment = models.ForeignKey('self', on_delete=models.CASCADE, null=True, related_name='replies') views.py class PostDetailView(FormMixin, DetailView): model = Post template_name = 'blog/post_detail.html' context_object_name = 'post' form_class = CommentForm def get_context_data(self, **kwargs): context = super(PostDetailView, self).get_context_data(**kwargs) context['form'] = CommentForm(initial={'post': self.object}) return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): if request.method == 'POST': new_comment = Comment.objects.create( author = self.request.user, post = self.object, comment = self.request.GET.get('name'), content = form.cleaned_data['content'] ) return JsonResponse({'comment': model_to_dict(new_comment)}, status=200) else: return self.form_invalid(form) I think I am close, but I dont know how to indicate id of the comment I want to reply to. I tried something like comment = self.request.GET.get('name') because I tried something like below in form. I have implemented Jsonresponse with ajax and when i try to post reply it gives "comment" : "null" so it doesn't "catch" it. Have you guys any ideas to resolve this? Thanks in advance. <form action="" method="POST" id="commentForm" name="{{ comment.id }}"> {% csrf_token %} {{ form|crispy }} <button type="submit" id="commentBtn">Wyślij</button> </form> -
Is there a way in Django to create a product model where some fields will be created directly in the admin views?
For a school project, I want to create a Django app similar to Woocommerce. What I mean by that is I want the site owner/admin to be able to add his own product attributes. Instead of creating classes for each type of product, I just wanted a simple Product class which would have attributes common to all products such as price and sku and a way for the admin to add custom attributes. I'll give you an example: let's say you just sell T-shirts on your e-commerce shop. It's easy, you create a field "size" with choices "S", "M" or "L" and another field "color" with different color choices. Now, imagine you create an e-commerce Django app which is supposed to work for different kinds of vendors. One will maybe sell cars, another house furniture, who knows? You want the store vendor admins to be able to create their own product attributes. Now you can't create a model with all possible fields like color, manufacturer, horsepower, height, ... because you would have too many fields for one model and you would certainly forget some. I thought I could create 3 classes: Product, ProductAttribute, ProductAttributeValue and play with Foreign and ManyToMany … -
elastic bean stalk, django, and wsgipath
I am finding issue with my WSGIPath in my django elasticbeanstalk deployment. my .ebextensions folder is in root, my django.config file contains the following: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: shofidecksite.wsgi:application now there are a few things what the code should be where shofidecksite is. I have tried the following: shofidecksite which is the name of the django project shofidecksite again, which is the elasticbeanstalk application name shofi-env which is the environment name I keep getting the error: ERROR Your WSGIPath refers to a file that does not exist. and I am having a very hard time figuring out what it wants from me. Can anyone add some light to this please -
Django AWS Elastic Beanstalk- How to create a cron job
I have deployed my django project on AWS. Now i want to create a cron job to send emails. Almost all the answers on net are somewhat different i no of them seem to be working for me. So please can some tell me a latest and best way to create a cron job. -
How to say Cloudinary to load media files to media/ folder in Django?
My settings: INSTALLED_APPS = [ ... 'cloudinary' ] CLOUDINARY_STORAGE = { 'CLOUD_NAME': '...', 'API_KEY': '...', 'API_SECRET': '...', } DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage' I looked to the cloudinary cloudinary_storage.storage.MediaCloudinaryStorage class and discovered that it has TAG property which takes value from MEDIA_TAG setting which is by default = 'media'. But anyway all my media files are saved to the root. What should I do to save it to the 'media/' filder? -
Urlpatterns in django are not redirecting(why are responses not diplaying?)
**I created this but when I try to run the server, it only shows the django website, its not a problem in firewall either, I have turned it off ** from django.contrib import admin from django.urls import path from django.http import HttpResponse def home(request): return HttpResponse('home') def contact(request): return HttpResponse('contact') urlpatterns = [ path('admin/', admin.site.urls), path('', home), path('about/', contact), ] **I also added it to apps** INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts', -
how can i know that email is real email or not using django framework
I built an email sender by using the Django framework but the logic that I built it accepted any email whatever is real email or not !! # Sending Email View def send_email(request): if request.method == 'POST': form = SubscribeForm(request.POST or None, request.FILES or None) if form.is_valid(): message = form.cleaned_data['body'] subject = form.cleaned_data['subject'] recipient_list = request.POST['to_email'] email = EmailMessage(subject, message, EMAIL_HOST_USER, [recipient_list]) email.send(fail_silently=False) messages.success(request, f'email sent to {recipient_list} successfully.') return redirect('/') else: form = SubscribeForm() context = { 'form': form, } return render(request, 'index.html', context) **Settings.py** EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' #<<===========================================================================>> EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = '587'enter code here EMAIL_HOST_USER = 'MyAccount@gmail.com' EMAIL_HOST_PASSWORD = 'MyPassword' EMAIL_USE_TLS = True -
Django ckeditor Image compression to Jpeg and image resize
Hi can anyone suggest me a way, I'm trying to do couple of things i'm using RichTextUploadingField in model, can anyone please help me with this: Compress django ckeditor uploaded image to jpeg to save disk space. For this i found CKEDITOR_FORCE_JPEG_COMPRESSION setting on django-ckeditor github page but it is throwing me error: NameError:name 'CKEDITOR_FORCE_JPEG_COMPRESSION' is not defined I want to set default django ckeditor uploaded image size suppose if i wupload 1000px image it should automatically converted into 600 or 500px without impacting the image quality or if possible image resize option like we do in word drag and resize. Ckeditor settings config: Ckeditor config: CKEDITOR_UPLOAD_PATH = "uploads/" CKEDITOR_IMAGE_BACKEND = "pillow" CKEDITOR_FORCE_JPEG_COMPRESSION = True CKEDITOR_CONFIGS = { 'default': { 'width': '100%', 'height': 600, 'contentsCss': 'img {max-width: 100%;height: auto! important;}', 'toolbar': 'Custom', 'toolbar_Custom': [ [ 'Bold', 'Italic', 'Underline' ], [ 'Font', 'FontSize', 'TextColor', 'BGColor', 'Find', 'Replace', '-', 'SpellChecker' ], [ 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', 'Table', 'TableTools' ], [ 'Link', 'Unlink' ], [ 'RemoveFormat', 'Source', 'Smiley', 'Image', 'Youtube', 'Preview' ] ], }, }