Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - parse data into javascript variable
I am working with django and a libary called gridstack.js. For this I got javascript functionality to use the libary. My idea is that the user can change the grid and press save. If he does that the data will be overritten with the new one. Now I created a Model field data = models.TextField(max_length=50000, default='{x: 0, y: 0, width: 2, height: 2}') this I call in the views.py like this: views.py def index(request): data = SaveData.objects.all() return render(request, 'main/index.html', { 'data': data }) Inside the templates javascript tag I want to give this data to a variable like let the_data = '{{ data.get.data }}';. But it dont parse the data into the js variable. I can call {{ data.get.data }} in the template and the correct data is shown. How can I add this? I already tried different variants like var the_data = JSON.parse("{{data|escapejs}}");. -
Nginx Deployed Anguler Frontned Does not Connect to DRF backend
I have deployed drf backend and angular frontend in the same aws instance, i deployed them using Nginx and gunicron for the drf and Nginx for the angular. I tested the drf API using postman it works fine but the angular frontend doesn't connect to the API, the site works but it cannot connect to the backend API.It shows failed net:: ERR_CONNECTION_REFUSED I have whitelisted the frontend address in the python app setting. frontend is hosted at 80 and the backend is at 8080. server block for backend: server { listen 8080; server_name 0.0.0.0; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/Sheradam_backend; } location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/Sheradam_backend/Sheradam_backend.sock; } } server block for frontend server { listen 80; listen [::]:80; server_name Sheradambd.com; root /home/ubuntu/Sheradam_frontend/dist/SheraDam; server_tokens off; index index.html index.htm; location / { # First attempt to server request as file, then # as directory, then fall back to displaying a 404. try_files $uri $uri/ /index.html =404; } } python app setting: STATIC_URL = '/static/' CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = ( 'http://localhost:8081', 'http://localhost:4200', 'http://localhost', ) -
Parsing JSON Response to Django DB
I am trying to save this Json response for Twilio to my DB but not sure how I parse this into my model in Django. At the moment it is just outputting the Json response to the terminal def validate_order_with_details(request): try: client = Client(twillio_account_sid, twillio_auth_token) message = client.messages.create( from_=twillio_from_no, body=printer, to=twillio_sender_mobile_no ) if message: return JsonResponse({"data": True, "printer": printer}) else: return JsonResponse({"data": True, "printer": "Error! while process twilio msg."}) print("There are an error with your transaction") except Exception as e: return JsonResponse({"data": True, "printer": str(e)}) print("There are an error with your transaction") else: return JsonResponse({"data": False}) Any help is appreciated. -
Can/How I build a user management system in Django from scratch and not be a singleton pattern?
Can/How I build a user management system in Django from scratch and not be a singleton pattern I need to build a user management system to use it in microservices -
how to show the field data of one app model on the other app template?
Well I am creating a user profile where user can see his all posts which he has been uploaded. But I dont understand one thing that how could i possibly grab the fields of Post model from Posts/models.py and show them on the template which i has created in other app(Profiles) templates. The reason i am trying to access them on otherapp is because I want to show them in the userprofile.html template where user can see his own posts list too. Just like face book posts. posts/models.py : class Post(models.Model): username = models.ForeignKey(User, verbose_name=("user name"), on_delete=models.CASCADE) description = models.CharField(('Description'),max_length=250) title = models.CharField(('Content Title'), max_length=250) create_date = models.DateTimeField(default = timezone.now) image_data = models.ImageField(upload_to='User_Posts', height_field=None, width_field=None, max_length=None) def __str__(self): return self.title profiles/views.py from posts.model import Post from django.views.generic import ListView class UserPostListView(ListView): model = Post context_object_name = 'userpost_list' template_name = 'profiles/userprofile.html' def get_queryset(self): user = get_object_or_404(User, username = self.kwargs.get('username')) return Post.object.filter(username = user).order_by('-create_date') profiles/templates/profiles/userprofile.html <div class="jumbotron"> {% for post in userpost_list %} <div class="post"> <h1><a href="">{{ posts.post.title }}</a> <img src="" alt="not found" height="60" width="60" style="float:right ;border-radius: 20px;" ></h1> <div class="date"> <p> <!-- Published on: {{ object.author.post.create_date|date:"D M Y" }} --> </p> </div> </div> {% endfor %} </div> </div> -
How to Use RESTful APIs with Django
I have been trying to integrate a REST API developed using Django-rest framework with another Django web app. But stuck in passing JSON data into the front-end. I would appreciate any help. Here are my respective files. I have tried two different urls on views.py file, one is AWS API Gateway API, when used no errors are thrown but data is not displayed in front-end. AWS API JSON data where object is like {'key': 'value'}. it contains only one object though views.py def ClientList(request): response = requests.get('A URL') client_data = response.json() return render(request, 'clients/client_list.html', context=client_data) When I change the url in views.py for django-rest framework API then I get an error like "the JSON object must be str, bytes or bytearray, not list" [JSON data where objects are like {key: value},{key:value}, .... Table body was changed accordingly. FrontEnd HTML <table class="table data-list-view"> <thead> <tr> <th></th> <th>NAME</th> <th>EMAIL</th> <th>MOBILE</th> <th>ADDRESS</th> <th>ROLE</th> <th>ACTION</th> </tr> </thead> <tbody> {% for client in client_data %} <tr> <td></td> <td class="product-name">{{client.UserId}}</td> <td class="product-category">{{client.Height}}</td> <td class="product-category">{{client.Income}}</td> <td class="product-category">{{client.Age}}</td> <td> <div class="chip chip-success"> <div class="chip-body"> <div class="chip-text">{{client.role}}</div> </div> </div> </td> </tr> {% endfor %} </tbody> </table> -
Overriding innit in forms to filter the id in Django
I have a model called Provider and other called Contact, the issue I am facing is I have a form which displays all the outputs of the objects of ProviderEmail and ProviderCircuit, so I have to do a filter and to do it what I did was to try to override the innit and to pop of kwargs the instance but it shows None. I dont know what I am doing wrong. views: def provider_detail(request, id): provider = Provider.objects.filter(id=id) circuit = ProviderCircuit.objects.filter(id=id) if request.method == "POST": form = ContactForm(data=request.POST, instance=circuit) if 'save' in request.POST: if form.is_valid(): email = form.cleaned_data['email'] emails = [] for i in email: emails.append(i.email) subject = form.cleaned_data['subject'] form.provider = provider form.save() message = render_to_string('hermes/account_activation_email.html', { 'form': 'hello', }) send_email_task(subject, message, emails) return redirect('hermes:provider') else: form = ContactForm() context = { 'provider': provider, 'circuit': circuit, 'form': form, }**strong text** return render(request, 'hermes/providers_detail.html', context) models: class ProviderEmail(models.Model): email = models.EmailField() provider = models.ForeignKey('Provider', on_delete=models.CASCADE) def __str__(self): return self.email class ProviderCircuit(models.Model): circuit_id = models.CharField(max_length=30, blank=True, null=True) provider = models.ForeignKey('Provider', on_delete=models.CASCADE) aldea_id = models.CharField(max_length=255, blank=True, null=True) class Meta: ordering = ['circuit_id'] def __str__(self): return self.circuit_id class Provider(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(null=False, unique=True) def __str__(self): return self.name def get_absolute_url(self): return … -
Exception Type: NameError at / Exception Value: name 'pcgames' is not defined in django
hello i tried to make pagination i have problem when i try to add pagination to my home html page , i tried this in my code but i got error .. i tried do this : views.py : def home_page(request, template='html_file/enterface.html'): contextt = { 'opratingSystems': OpratingSystems.objects.all(), 'androidgames': AndroidGames.objects.all(), 'androidapk': AndroidApks.objects.all(), 'antivirus': Antivirus.objects.all(), 'pcgames': PCgames.objects.all(), 'pcprogram': PCprogram.objects.all(), } app = pcgames.objects.all() page = request.GET.get('Page', 1) # the_home_page is the name of pages when user go to page 2 etc paginator = Paginator(app, 6) # 6 that's mean it will show 6 apps in page try: pcgame = paginator.page(page) except PageNotAnInteger: pcgame = paginator.page(1) except EmptyPage: pcgame = paginator.page(paginator.num_pages) return render(request,template,contextt) in HTML page : <div class="container"> <div class='row'> {% for pcgame in pcgames %} <div class='col-xs-12 col-sm-6 col-md-4 website-thumb'> <a href=" {{ pcgame.page_url }} "> <img src="{{ pcgame.get_image }}" class='image_control_for_home_page_pc_games' alt=''> </a> <h3 class="font_control_for_home_page_pc_games_name"><a href=" {{ pcgame.page_url }} ">{{ pcgame.name }}</a></h3> </div> {% endfor %} </div> {% if pcgame.has_previous %} <a id="border_pagination" class="btn btn-outline-info mb-4" href="?Page=1">First</a> <a id="border_pagination" class="btn btn-outline-info mb-4" href="?Page={{ pcgame.previous_page_number }}">Previous</a> {% endif %} {% for num in pcgame.paginator.page_range %} {% if pcgame.number == num %} <a class="btn btn-info mb-4" href="?Page={{ num }}">{{ num }}</a> {% elif … -
Date range in javascript
Iam trying to input a chart in my html template, since Javascript and jquery is not my best attribute iam stuck at a problem to set start data and end date for my Graphs. With the below code Iam able to plot the graph and also I set the date time picker for user, how can I set the Start date and end date input by user in my chart. PS: Chart is plotted by "Chart.js" library. <script> $(function() { $('input[name="daterange"]').daterangepicker({ opens: 'left' }, function(start, end, label) { console.log("A new date selection was made: " + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD')); }); }); const xlabels =[]; const ylabels =[]; chartIt(); async function chartIt() { await getData(); const ctx = document.getElementById('myChart').getContext('2d'); const myChart = new Chart(ctx, { type: 'line', data: { labels: xlabels, datasets: [{ label: 'Number of failure orders', data: ylabels, fill: false, backgroundColor: 'rgba(0, 0, 0)', borderColor:'rgba(0, 0, 0)', borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } } ] } } }); } async function getData(){ const response = await fetch('https://raw.githubusercontent.com/ankurparanjpe/khajana/master/khajana/orders.csv'); const data = await response.text(); const table = data.split('\n').slice(1); table.forEach(row => { const columns = row.split(','); const date = … -
Django Rest Framework - 'retrieve' without primary key
I wrote the following code: def retrieve(self, request, pk=None): if(request.user.is_staff): queryset = Profile.objects.filter(pk=pk).order_by('id') else: queryset = Profile.objects.filter(user=request.user).order_by('id') page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) When making a call to /api/profile/ I get the following response: detail "Not found.". How can I avoid getting a 404? -
Access a list of dictionaries inside of a dictionary in Django templates
I'm trying to access a list inside of my Django Html template, but I can't seem to grab the first element of the list the normal way by grabbing it via its index. In my views, I have a function edamam that calls the API endpoint and returns a JSON dictionary named ingredients. Here's the function: @login_required def edamam(request): ingredients = {} if 'ingr' in request.GET: ingr = request.GET['ingr'] app_key = APP_KEY app_id = APP_ID url = f'https://api.edamam.com/api/food-database/v2/parser?ingr={ingr}&app_id={app_id}&app_key={app_key}' response = requests.get(url) ingredients = response.json() print(f'Type: {type(ingredients)}') return render(request, 'todo/edamam.html', {'ingredients': ingredients}) else: return render(request, 'todo/edamam.html', {'error': 'That item does not exist in the database.'}) I printed typeof(ingredients) to be certain I'm returning a dictionary and the printout does verify that in the console: Type: <class 'dict'> In my views edamam.html, I'm grabbing ingredients.parsed (ingredients is just a massive dictionary) because I'm trying to get the list named parsed in order to grab elements from that. <div class="col-md-5"> {% if ingredients %} <p>{{ ingredients.parsed }}</p> {% endif %} {% endblock %} </div> which returns: [{'food': {'foodId': 'food_bnxr4n3b1ld7i6ace2hkqbwm89du', 'label': 'cheeseburger', 'nutrients': {'ENERC_KCAL': 263.0, 'PROCNT': 12.97, 'FAT': 11.79, 'CHOCDF': 27.81, 'FIBTG': 1.1} , 'category': 'Generic foods', 'categoryLabel': 'food'} }] My question is, how … -
alert condition is not working as expected
enter image description here html: {% if messages %} <div class="row"> <div class="col-4"> {% for message in messages %} {% if message == "success" %} <div class="alert alert-success" role="alert"> User created </div> {% else %} <div class="alert alert-danger" role="alert"> {{ message }} </div> {% endif %} {% endfor %} </div> </div> {% endif %} instead of success the alert is considering danger. Can some one help me what is wrong in the codition -
how to add sitemap on nginx?
I am trying to add sitemap on my website for SEO purpose. I was given sitemap.xml file by a guy who helps on Search Engine Optimization. so my nginx configuration is :- location /static/ { autoindex on; root /home/user/myweb; } location /media/ { autoindex on; root /home/user/myweb; } location / { include proxy_params; proxy_pass http://unix:/home/user/gunicorn.sock; } location = /sitemap.xml { root /home/user/myweb; } } so now when i try to access :- www.myweb.com/sitemap.xml this will not serve sitemap.xml file instead it will take me to www.myweb.com/home/user/myweb/sitemap.xml which is 404 not found. so how can i configure sitemap.xml file in my site ? -
Django login Error: save() got an unexpected keyword argument 'update_fields', this happens when i try to login
I just got an error when I try to log in. the error happens only when I add the save method in the User model. But when I remove the save method there is no error at all. I want to decrease the quality of the user picture using PIL to load the website faster, that's why I add the save method. THANKS! here is the user model: class User(AbstractUser): is_student = models.BooleanField(default=False) is_lecturer = models.BooleanField(default=False) is_parent = models.BooleanField(default=False) phone = models.CharField(max_length=60, blank=True, null=True) address = models.CharField(max_length=60, blank=True, null=True) picture = models.ImageField(upload_to='profile_pictures/%y/%m/%d/', default='default.png', null=True) email = models.EmailField(blank=True, null=True) username_validator = ASCIIUsernameValidator() def __str__(self): return '{} {}'.format(self.first_name, self.last_name, self.email) @property def get_full_name(self): full_name = self.username if self.first_name and self.last_name: full_name = self.first_name + " " + self.last_name return full_name def get_absolute_url(self): return reverse('profile_single', kwargs={'pk': self.pk}) def save(self): super().save() try: img = Image.open(self.picture.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.picture.path) except: pass def delete(self, *args, **kwargs): if self.picture.url != settings.MEDIA_URL + 'default.png': self.picture.delete() super().delete(*args, **kwargs) The full log of the error is here: Internal Server Error: /accounts/login/ Traceback (most recent call last): File "C:\Python37\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Python37\lib\site-packages\django\core\handlers\base.py", line 115, … -
Using TinyMCE with filebrowser and grappelli
I've been wanting to set up a blog app with a WYSIWYG editor. I use S3 as the storage backend for image uploads outside of the editor. For that purpose, I use "django-storages". I have deployed this on Heroku and for that purpose, I use django-heroku as well. To enable image upload for TinyMCE i went ahead and installed Grappelli and filebrowser. I added the URLs for the same added the context processor for Grappelli, set the TINYMCE_FILEBROWSER setting to true. I ensured the URLs for filebrowser and grappelli come before the URL for admin When I call collectstatic, I get this messages like this Found another file with the destination path 'admin/js/timeparse.js'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path. When I open up admin and go to the image upload button on the editor, it doesn't show the upload icon. I was wondering if anyone who has had any experience with this can help me out? I am open to setting up some time with them as well :) Here's the rundown on settings.py INSTALLED_APPS = [ 'django.contrib.admin', … -
User registration, Login, Logout, etc... Django
Is there a way to register, login, logout users, etc... in a Django REST APi. I am using DjangoRestFramework. For authentication, I am using djangorestframework-jwt for JSONWebTokenAuthentication. If I want to be able to have users register, login, logout, etc... What are the options? Also is it customizable? what is the most used out there in the industry, in terms of reliability, etc... Thanks. -
Django - like unlike system - how changing the button color for unliking?
Here is my follow/unfollow system. If user clic first, he adds if he clics seconds time he removes. What's the best way to change the color of the text of the button? After user clics for the first time? user/views.py @login_required(login_url='/cooker/login') def FollowView(request, pk): userprofile = get_object_or_404(UserProfile, user_id=pk) if request.method == "POST": _followed = request.user in userprofile.follow.all() if _followed: userprofile.follow.remove(request.user) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) else: userprofile.follow.add(request.user) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) @property def total_follow(self): return self.follow.count() Here is my template: user/template/exemple.html <div class="col-sm-4"> <form action="{% url 'user:follow_public' current_user.pk %}" method="POST">{% csrf_token %} <button type="submit" name="user_id" value="{{ current_user.id }}" style="width: 100%;background: #ff6670;padding: 10px;border-radius: 10px; margin-bottom: 15px;outline:none;">Follow {{current_user.username}}</button> </form> </div> -
ModuleNotFound cause 502 deploying django with zappa on aws lambda
I've faced ModuleNotFound error when try to deploy django to aws via zappa. when i tried to run server locally using below commmand it works well (venv) python manage.py runserver or (venv) python manage.py runserver --settings=remoteMedi.settings.prod zappa settings is like folder hierachy is like installed_app is like why i can't get it? -
How can i add registration data in another model and can login from that data in django
Recently i am facing a problem in registration. I have made a ** accounts** app in my project for registrations. I don't want to save data in default User model in dB. i am trying to make an eCommerce site where people can register to buy products. What is the best way for registrations and log in? Extending the user model could have solved the problem but I want a totally different model for that user who wants to buy products for registration and login. Is it the best way what i am thinking for an eCommerce site registration? How can i do it? -
how do i write this type of code using python django? [closed]
I need to write code that will have three levels. i.e. person;A,B,C. person A joins a club. he refers person B. Person B then refers person C. I need person A to get a point for inviting person B.since person B also invited person C and B was invited by A.Person B needs to get a point while person A gets half a point.Person B is a direct referal to person A while person C is an indirect referal.person C is a direct referal to person B. I need the code to continue like that such like if person C now invites person D. person C will get a point and person B will get half a point. And it goes on like that.I just need someone to get me the code. -
how to put tags in articles in python django
My client want me to build an web application in which user send articles. and put tags at the end of articles. I am a python developer but i do not know how to do coding for tags in front-end as well as back-end.Kindly help me -
Manually render CSS and JS files in Django?
Based on this answer, I was trying to manually render my css and javascript files before loading. My project level urls.py: from django.contrib import admin from django.urls import path, re_path, include from . import views urlpatterns = [ path('admin/', admin.site.urls), re_path(r'(?P<filename>[a-zA-Z_-]+\.css)$', views.css_renderer), re_path(r'(?P<filename>[a-zA-Z_-]+\.js)$', views.js_renderer), path('', include('mapmaker.urls')) ] And the corresponding views.py: from django.shortcuts import render # Create your views here.# def css_renderer(request, filename): print('rendered ' + filename) return render(request, filename + '.css', {}, content_type="text/css") def js_renderer(request, filename): print('rendered ' + filename) return render(request, filename + '.js', {}, content_type="text/js") However, the routes are not being matched at all. I have checked the regular expression as well. My server log: ... [06/Sep/2020 17:11:18] "GET / HTTP/1.1" 200 15728 [06/Sep/2020 17:11:18] "GET /static/mapmaker/map-styles.css HTTP/1.1" 200 4455 [06/Sep/2020 17:11:18] "GET /static/mapmaker/menu-styles.css HTTP/1.1" 200 1369 [06/Sep/2020 17:11:18] "GET /static/mapmaker/index.js HTTP/1.1" 200 4630 [06/Sep/2020 17:11:18] "GET /static/mapmaker/styles.css HTTP/1.1" 200 439 [06/Sep/2020 17:11:18] "GET /static/mapmaker/favicon.ico HTTP/1.1" 200 1150 What is the problem here? Fairly new to django here. -
How to check if there is a existing websocket connection or not?
Check websocket connection : get list of all existing websocket connection or check whether there is any websocket connection or not? -
Why cannot i access the about page when i can access the home page in the same directory?
I can access the home.html (http://127.0.0.1:8000/) without any issues but about page (http://127.0.0.1:8000/about/) gives me the below error: Using the URLconf defined in django_project.urls, Django tried these URL patterns, in this order: admin/ [name='blog-home'] about [name='blog-about'] The current path, about/, didn't match any of these. django project folder urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), ] app folder urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.home, name='blog-home'), path('about', views.about, name='blog-about'), ] app folder views.py: from django.shortcuts import render def home(request): return render(request, 'blog/home.html') def about(request): return render(request, 'blog/about.html') directory structure: . ├── blog │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ ├── __init__.py │ │ └── __pycache__ │ │ └── __init__.cpython-37.pyc │ ├── models.py │ ├── __pycache__ │ │ ├── admin.cpython-37.pyc │ │ ├── apps.cpython-37.pyc │ │ ├── __init__.cpython-37.pyc │ │ ├── models.cpython-37.pyc │ │ ├── urls.cpython-37.pyc │ │ └── views.cpython-37.pyc │ ├── static │ │ └── blog │ │ ├── css │ │ │ ├── main.css │ │ │ └── test.css │ │ ├── images │ │ │ ├── favicon.png │ │ │ └── freedom.jpg │ │ … -
Permission denied: '/home/ubuntu/django/media/images' while saving image on django production server on Apache2 running on ubuntu
I'm using an AWS instance to run django on production server on Apache2 server running on ubuntu. In one of the operations, I'm trying to save the profile image of the user, though I'm getting permission denied error, though everything's running smoothly on development server. Following are my settings.py configs: MEDIA_ROOT =os.path.join(BASE_DIR, "media") MEDIA_URL ='/media/' I've followed various solutions given on this thread, though still the same error persists. Can I try anything else?