Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get a url parameter with Django Rest Framework
I'm Using django rest framework and I would like to achieve an endpoint like so : http://127.0.0.1:8000/posts//like This endpoint will allow a user to like a certain post. But the problem is that I have no ideas about writing the view for that purpose. I think that I have to get the current id of the post, which I can only access with grabbing the "" from the URL. Here is how my view looks like : class PostList(generics.ListCreateAPIView): serializer_class = PostSerializer queryset = Post.objects.all() permission_classes = [isAuthenticatedOrReadOnly] #Get Post Details : delete / update / get the post class PostDetail(generics.RetrieveUpdateDestroyAPIView): serializer_class = PostSerializer queryset = Post.objects.all() #Get my posts : List class MyPostList(generics.ListCreateAPIView): serializer_class = PostSerializer permission_classes = [isAuthenticatedOrReadOnly] def get_queryset(self): return Post.objects.filter(user = self.request.user) class PostLike(generics.ListCreateAPIView): serializer_class = ActivitySerializer permission_classes = [isAuthenticatedOrReadOnly] def get_queryset(self): return Vote.objects.filter(activity_type='L', content_object=self.id, object_id=self.id) As you can see, I'm completely lost with the PostLike view. The goal of this view is to : Display likes of the current post id, create a like instance that target this post id Thank you ! -
How to make date formatting in Django template?
I apologize for my English already. I did some research, but none of them worked for me. But no data is shown. It appears if I don't type "date:" D d M y ". Example: {% for row in activities %} <tr> <td style="width:30%" class="ads-details-td"> <div> <p><strong> Date: </strong> {{ row.dateStart|date:"D d M Y" }} </p> </div> </td> </tr> {% endfor %} Incoming start date format 'dateStart': '2019-02-05 05:45:00' I will be glad if you help me. -
How to get unique values in django from database
So this is my query and it displays only file name but I want 'id' also. filenames=Upload.objects.values('file').distinct().filter(created_by=request.user).all() this will generate only unique files as dict. But I want 'id' of those files also and if use 'id' inside that 'values' it will not give unique file names. So this is my issue. I'm okay with other methods as well. -
Django Custom Tag Filtering
Need a little help. I have a news site, and what I'm trying to do is make a custom tag (it has to be a custom tag, part of my task) that will display the latest 3 news in a category. So let's say I click on a "health" article, the article opens, and my custom tag renders the latest 3 news from the health category next to the article. I hope I didnt confuse you, I'm still learning. My tag : from django import template from news.models import Article register = template.Library() @register.inclusion_tag("news/categories.html") def show_results(category=None): article = Article.objects.all() if category: article = article.filter(category=category) return {'article': article[:3]} My models: class Category(models.Model): category_title = models.CharField(max_length=200, default="") def __str__(self): return self.category_title class Article(models.Model): title = models.CharField('title', max_length=200, blank=True) slug = AutoSlugField(populate_from='title', default="", always_update=True, unique=True) author = models.CharField('Author', max_length=200, default="") description = models.TextField('Description', default="") is_published = models.BooleanField(default=False) article_text = models.TextField('Article text', default="") pub_date = models.DateTimeField(default=datetime.now, blank=True) article_image = models.ImageField('Article Image') article_category = models.ForeignKey(Category, on_delete="models.CASCADE", default="") img2 = models.ImageField('Article Image 2', default="", blank=True) img3 = models.ImageField('Article Image 3', default="", blank=True) img4 = models.ImageField('Article Image 4', default="", blank=True) img5 = models.ImageField('Article Image 5', default="", blank=True) img6 = models.ImageField('Article Image 6', default="", blank=True) def __str__(self): return … -
Need to add employee search function in googlesite
I have google sheet which store all employee details (name,email,employee number, etc.) and I need a suggestion for create local web with Flask/Django, add search function and then upload it to googlesite intranet. I'm python user but never do something like this before This is for all employee, I need to add something in googlesite like employee search function. So everyone in the company can find colleagues email, name, etc. via googlesite I dont have any code yet, but I think I can use Flask for Backend and ReactJS for Frontend design. I don't have the database, and don't want anyone to add the employee data. So I gonna update the data via google sheet and need to retrieve the data from it the step I thinking about is 1. we normally update the data via google sheet 2. create webpage with search function (which retrieve the data from google sheet) and mayb we use 127.0.0.5000 first 3. then use google api / heroku to deploy 4. embed url in the googlesite 5. when employee go to this webpage, they can search name, email, etc. from here and shows the employee result I learn some in the web and did … -
Converting Django project from Python 2 to Python 3: pip3 install django_comments NameError unicode
System info: 64-bit OS-X, Python 3.7 I am converting a Django website from Python 2 to Python 3. To do this, I ran 2to3 on the whole project. I then installed all of the required modules in INSTALL_APPS in settings.py - except one: django_comments. (env) user:languages user$ pip3 install django_comments Collecting django_comments Using cached https://files.pythonhosted.org/packages/c7/df/3a752f3e393b470087304dd47be6a4bad9867e7ec33963ff022d32143700/django-comments-1.0.0.b.tar.bz2 ERROR: Command errored out with exit status 1: command: /Users/user/.../env/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/tb/vbtzyvv92hz6262qv7x8r8jh0000gn/T/pip-install-xjv_0ird/django-comments/setup.py'"'"'; __file__='"'"'/private/var/folders/tb/vbtzyvv92hz6262qv7x8r8jh0000gn/T/pip-install-xjv_0ird/django-comments/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base pip-egg-info cwd: /private/var/folders/tb/vbtzyvv92hz6262qv7x8r8jh0000gn/T/pip-install-xjv_0ird/django-comments/ Complete output (7 lines): Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/tb/vbtzyvv92hz6262qv7x8r8jh0000gn/T/pip-install-xjv_0ird/django-comments/setup.py", line 12, in <module> version = get_version(), File "/private/var/folders/tb/vbtzyvv92hz6262qv7x8r8jh0000gn/T/pip-install-xjv_0ird/django-comments/django_comments/__init__.py", line 4, in get_version return u'.'.join(map(unicode, VERSION)) NameError: name 'unicode' is not defined ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. I have found that this may be related to compatibility with Python 3 and that one potential fix is to replace unicode with str. However, this is a module that I would like to work in Python 3 since the Django project relies on this for comments currently. Is it deprecated essentially with no way to work outside … -
Use django pagination with SQL query and no ORM
I know how to use django pagination with ORM django after filtering the required data and put in into pagination div queryset_list = employee.objects.all() query=request.GET.get("q") if query: queryset_list=queryset_list.filter( Q(name__icontains=query)| Q(father_name__icontains=query)| Q(mother_name__icontains=query)| Q(content__icontains=query)| Q(create_date__icontains=query) # Q(user__first_name__contains=query) ).distinct() paginator = Paginator(queryset_list, 5) page_request_var = "page" page = request.GET.get(page_request_var) queryset = paginator.get_page(page) context={ "object_list":queryset, "title":"List Items", "page_request_var":page_request_var, } return render(request,"blog/list.html", context) The above code is working My question is how to convert this ORM into raw SQL I know that I must use LIMIT and OFFSET in raw SQL to embedded into paginator. -
How to differentiate a HTTP Request submitted from a HTML form and a HTTP Request submitted from a client in django?
I have a model in django that is as below: class Student(Model): nationality = CharField(max_length=200) I have a form as below: class StudentForm(ModelForm): class Meta: model = Student fields = ('nationality', ) my template is as below: <form method="GET" novalidate id="my_form"> {{ student_form.as_p }} </form> <button type="submit" form="my_form" name="my_form">Submit</button> I have a view as below: def home(request): if request.POST: return HttpResponse('This should never happen') else: if request.GET.get('nationality'): student_form = StudentForm(request.GET) if student_form.is_valid(): return HttpResponse('get from form submission') else: return HttpResponse('get from client request') The problem with this method is that if sb submits the form without filling the nationality field, the result would be 'get from client request' that is wrong because the validation error should happen because the request is from submitting a form not direct client get request. What I can do is that I add a hidden field to my form as below: <form method="GET" novalidate id="my_form"> {{ student_form.as_p }} <input type="hidden" id="hidden" name="hidden" value="hidden"> </form> <button type="submit" form="my_form" name="my_form">Submit</button> and change my view as below: def home(request): if request.POST: return HttpResponse('This should never happen') else: if request.GET.get('hidden'): student_form = StudentForm(request.GET) if student_form.is_valid(): return HttpResponse('get from form submission') else: return HttpResponse('get from client request') However, there should … -
Apscheduler with django on windows server
Im using django for my website.In that,I need to run a job automatically.This django app is hosted on the IIS windows server.When I run the app locally(By command prompt),it works.But In the IIS,Job not running.Below here,I put some codes and its location I tried.Lets take my project name is myProject and my app name is myApp In myApp/init.py: import os if os.environ.get('RUN_MAIN', None) != 'true': default_app_config = 'myApp.apps.MyAppConfig' In myApp/apps.py: from django.apps import AppConfig class MyAppConfig(AppConfig): name = 'myApp' def ready(self): from taskscheduler import updater updater.start() In myApp/views.py: def job(): #some codes #and a row creation whether the app runs successfully or failed In updater/updater.py: from apscheduler.schedulers.background import BackgroundScheduler from myApp import views def start(): scheduler = BackgroundScheduler() scheduler.add_job(views.job, trigger='cron',hour='*', minute='20') scheduler.start() import logging logging.basicConfig() logging.getLogger('apscheduler').setLevel(logging.DEBUG) Please help me sortout. Thanks in advance -
React - how to render nested object with renderItem
I'm a bit struggling with rendering nested object in my front end. I know there is a map function might be helpful, but I'm not sure how I can get it to work in my case (with renderItem). The back end I'm using are Rest API framework and Django. This is what JSON structure looks like. { "id": 1, "name": "Job 1", "address": [ { "id": 4, "street": "65 Karamea Street", "suburb": "Beautiful Surburb", "town": "Christchurch", "postcode": "8001", "address_type": "h" } ], "franchise": { "id": 2, "name": "Company ABC", "person": 2, "legal_name": "Company ABC Ltd.", "created": "2019-08-09T09:40:35.697582Z", "modified": "2019-09-23T03:21:43.258983Z", "region": { "id": 4, "region": "QueensTown" } }, "customer1": { "id": 1, "last_name": "Tom", "first_name": "Wilson", "address": [ { "id": 11, "street": "1 Sunset Road", "suburb": "Auckland", "town": "Auckland", "postcode": "1234" } ] } This is the React code: import React from 'react'; import { List, Card } from 'antd'; const Job = props => { return ( <React.Fragment> <List grid={{ gutter: 16, xs: 1, sm: 2, md: 4, lg: 4, xl: 6, xxl: 3, }} dataSource={props.data} renderItem={item => ( <List.Item> <Card title={<a href={`/job/${item.id}`}>{item.customer1.first_name}</a>}>{item.franchise.legan_name} <span> | Based on </span> {item.name} </Card> </List.Item> )} /> </React.Fragment> ); }; export default Job; Within … -
How to run selenium from django
I am making a website that will use selenium to get data from another website. And i want to know how to do this properly. Basically the selenium script should run when the user clicks a button. May i will have to use multi threading or something? -
How can I invoke remote api in django view.py?
I Have a Django app which use api written i ASP.Net. I can call api from template (html page). Is there any way to call api from views.py? I have tried this. from django.shortcuts import render from django.contrib.auth.decorators import login_required # Create your views here. def categorydashboard(request): r = request.post('xxx.xxx.xx.xxx:xxxx/Category/getSubCategoryNamev2', d=request.GET) return render (request,'categoryDashboard.html',{}) API sample data (it is a GET request) [ { "category_id": 2, "category_name": "Hyper Mechanical", "Image_Path": null, "subcategory": [ { "category_id": 0, "category_name": null, "product_subcategory_id": 37, "product_subcategory_name": "Lift", "schema_id": null, "Image_path": "" } ] } ] Server runs well but when i call 'categorydashboard' view its throws following error AttributeError: 'WSGIRequest' object has no attribute 'get' I am new in Django so i am sorry if i have mistaken -
Show notification or alert of a requirement of a mobile user in Django web application
I have a mobile medical services application which posts to API with DRF of a web application (administrator) based on Django. How to manage any alert or notification of service requirements, so that it’s shown in the web application that this service has been requested. Can you give me a step-by-step guide on how this could be implemented? -
Django-rest-framework api add SessionAuthentication as optional
Hi i'm currently have my api that use this simple-JWT package for jwt token authentication, it worked great. But now when i try to call the api from the django website app using Ajax in which is from a page user already logged in but it still required me to use the jwt access_token. My ajax call from the page user already logged in: $.ajax({ type: "POST", url: "/api/add_favorite/" + property_id + "/", beforeSend: function (xhr) { xhr.setRequestHeader('Authorization', 'Bearer {{ refresh_token }}'); }, success: function (data) { if (data.code == 200) { alert('added to favorite'); replace_part_1 = '<a id="mylink2" href="#" value="' + property_id +'"><i class="fas fa-heart fa-lg" style="color: red" title="Remove from favorite"></i></a>' $("a[value='" + property_id + "']").replaceWith(replace_part_1); } } }); Now i don't want to set the header with authorization since in the page user already logged in so the session is already set. So i tried to add Django Session authentication to the the api like so: @api_view(['POST']) @authentication_classes([SessionAuthentication, JWTAuthentication]) @permission_classes([IsAuthenticated]) def add_favorite(request, property_id): if request.method == 'POST': try: favorite_property = Property.objects.get(pk=property_id) if request.user.is_authenticated: login_user = request.user if not login_user.properties.filter(pk=property_id).exists(): login_user.properties.add(favorite_property) return JsonResponse({'code':'200','data': favorite_property.id}, status=200) else: return JsonResponse({'code':'404','errors': "Property already exists in favorite"}, status=404) except Property.DoesNotExist: return JsonResponse({'code':'404','errors': "Property … -
How to activate virtual environment in Django for Windows with Python?
I've been told that to activate a Virtual Environment in Django for Windows I should try: environment_path\Scripts\activate But when I enter that, cmd returns this error: The system cannot find the path specified. I created the virtual environment by entering: python3 -m venv env However when I try env\Scripts\activate I get the error described. Can anyone help? Thanks. -
error url using django and rest framweork
error when i try to call some id of my urls for example the view in rest_frameork i try to enter http://127.0.0.1:8000/categoria/4 or 5 and i can't error mensagge "The current path, categoria/4, didn't match any of these. (error 404)" im ussing the rest_framework for it file urls.py from django.urls import path, include from django.conf.urls import url from . import views from rest_framework import routers router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) urlpatterns = [ url(r'^doctor$', views.DoctorList.as_view()), url(r'^doctor(?P<pk>[0-9]+)$', views.DoctorDetail.as_view()), url(r'^paciente$', views.PacienteList.as_view()), url(r'^paciente(?P<pk>[0-9]+)$', views.PacienteDetail.as_view()), url(r'^categoria$', views.CategoriaList.as_view()), url(r'^categoria(?P<pk>[0-9]+)$', views.CategoriaDetail.as_view()), url(r'^examen$', views.ExamenList.as_view()), url(r'^examen(?P<pk>[0-9]+)$', views.ExamenDetail.as_view()), path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] -
Django restful API to get permission of built-in users
I want to access Django's built-in user's permission, like add an instance of a model, delete, modify. Do you know how to access such information using Restful API? I have used django-rest-auth, but it seems that it can not provide the method to access permission. Could you please give me some suggestions? -
Testing socket activation failed, Django and Gunicorn
when I try to do this: sudo systemctl status gunicorn It answers with this: ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; disabled; vendor preset: enabled) Active: failed (Result: exit-code) since Wed 2019-09-25 01:50:37 UTC; 40min ago Main PID: 22345 (code=exited, status=216/GROUP) Sep 25 01:50:37 hybroo systemd[1]: Started gunicorn daemon. Sep 25 01:50:37 hybroo systemd[22345]: gunicorn.service: Failed to determine group credentials: No such process Sep 25 01:50:37 hybroo systemd[22345]: gunicorn.service: Failed at step GROUP spawning /hybroodir/hybrooenv/bin/gunicorn: No such process Sep 25 01:50:37 hybroo systemd[1]: gunicorn.service: Main process exited, code=exited, status=216/GROUP Sep 25 01:50:37 hybroo systemd[1]: gunicorn.service: Failed with result 'exit-code'. Sep 25 01:50:37 hybroo systemd[1]: gunicorn.service: Start request repeated too quickly. Sep 25 01:50:37 hybroo systemd[1]: gunicorn.service: Failed with result 'exit-code'. Sep 25 01:50:37 hybroo systemd[1]: Failed to start gunicorn daemon. root@hybroo:/hybroodir# curl --unix-socket /run/gunicorn.sock localhost However, it's supposed to answer this: ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; disabled; vendor preset: enabled) Active: inactive (dead) Any help is appreciated, I'm sorry if I'm not showing anything helpful, but I don't know what more I could show. I'm using: Postgres, Nginx, and Gunicorn on Ubuntu 18.04 in Google Cloud. -
ReactJs in Django return
I am new to Reactify Django. Actually, i am trying to have React JS to be rendered instead of HTML page. I have following: views.py from django.shortcuts import render def home(request): return render (request, 'home.html') home.html <html> <head> {% load staticfiles %} <script src="{% static '/App.js' %}"></script> </head> <body> <p>Hello World Home</p> {% block content %}{% endblock %} </body> </html> App.js import React from 'react'; import logo from './logo.svg'; import './App.css'; function App() { return ( <div className="App"> Hello to react app! </div> ); } export default App; settings.py STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(SETTINGS_PATH, 'frontend/src'), ) I am not sure, if i am understanding the concept correctly. But i am looking for returning the react rendered html in django.I have my react app installed in frontend directory in the same folder. Any clarification, will be greatly appreciated. -
How can I create a video and photo uploading feature on my website using Python and Django?
How can I create a video and photo uploading feature on my website using Python and Django? I have using forms,models(file_field) and yet it doesn't render to the front_end -
Unexpected Keyword when I Pass Url Parameter
I have a view called 'Teams' that loops through different NBA teams in a dictionary and shows their name and logo. When the user clicks on one of these logos, I want them to be taken to the 'TeamDetailView'. This should carry over the chosen team's city/name/logo, and I can see this information being passed in the URL. When I attempt to load the team's individual page, though, it gives me a type error and says that TeamDetailView() got an unexpected keyword argument 'city' In the local vars section, it shows my key/value pairs being passed correctly. How can I access these parameters on the team page and correct this error? callback_kwargs {'city': 'Atlanta', 'logo': 'atlanta-logo.png', 'name': 'Hawks'} Here is my view: def TeamDetailView(request): return render(request, 'bandwagon/team.html/') Here is my URL: path('team/<str:city>/<str:name>/<str:logo>/', views.TeamDetailView, name='bandwagon-team'), Here is my Template for the Teams List: {% for key, value in teams.items %} <a class="stream-list" href="{% url 'bandwagon-team' value.city value.name value.logo %}"> <img class="stream-img" alt="The Logo for the {{ value.city }} {{ value.name }}" src="../../../media/logos/{{ value.logo }}"> <p class="name">{{value.city }} {{value.name}}</p> </a> {% endfor %} Here is my Template for the Individual Team Page, which is quite basic for now until I get these … -
Ajax redirects to the url with preventDefault()
I'm using Django for an app that allows you to search and save recipes. I'm trying to have a form on a search results page that allows you to click 'save' and creates an object to the database without reloading the page. In the current setup when I click on the 'save' button for the form with id="add_form" I get redirected to a new url (add/) even though I've included preventDefault(). I thought this was due to me including the form action={%url 'add' %} however, I've tried removing the form action but that gave me a multiValueDictKeyError for raw_input = request.POST['ingredients'] so I thought it was calling the incorrect view function views.recipes instead of views.add. I've read some other ajax guides that explicitly state a form action so I thought that would help with the incorrect view function being called. views.py def recipes(request): if request.method == 'POST': # check for dietary restrictions restrictions = request.POST.getlist('restrictions') # format input ingredients raw_input = request.POST['ingredients'] ... return render(request, 'recipes/recipes.html', {'results': results}) else: return render(request, 'recipes/recipes.html', {'error': 'Please search for a recipe'}) @csrf_protect def add(request): if request.method == 'POST': title = request.POST['title'] image = request.POST['image'] source = request.POST['source'] user = request.user try: recipe = … -
Django tests imports use content type values from real database
My application is built on top of Django and DRF. I'm trying to test a serializer with a structure similar to this one: settings.py ... DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db', 'USER': 'user', 'PASSWORD': 'unbreakablepass', 'TEST': { 'NAME': 'test_db', } } } ... models.py class Status(models.Model): name = models.CharField(verbose_name=_('name'), max_length=150) order = models.PositiveIntegerField(verbose_name=_('order'), default=0) content_type = models.ForeignKey(ContentType) class Task(models.Model): status = models.ForeignKey(Status) serializers.py class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = ['status'] extra_kwargs = { 'status': { 'queryset': Status.objects.filter( content_type=ContentType.objects.get_for_model(Task) ) } } tests.py from myapp.serializers import TaskSerializer from myapp.models import Task class TaskTestCase(TestCase): def test_content_type(self): # Do something with ContentType.objects.get_for_model(Task) ... My problem is that since the serializers are imported in tests.py, they are imported before the test database is setup when I run manage.py test --keepdb. Now, the ContentType value in the queryset attribute of my related field, is filtered with ContentType values from the main db, not the test db. So my tests would fail if they attempted to use any value in the related field. The obvious choices seem to be: Import the serializer inside the testing code. I really dislike this. Also, many different tests may use the serializer. Use some … -
Is there any benefit to switching from django template to jinja if I only have simple templates?
I have an application where the vast majority of business logic is in the backend. I use django templates along with context variables to populate those templates. In majority, they are all simple and don't have fancy logic. My question is: Is there any improvement in terms of performance or readability or any other benefit if I switch from django templates to jinja in this particular case? -
return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such column: webapp_extendeduser.password
I'm trying to create a custom user model for my database but there is error said that there is no password column in my custom user model (which I name it as Extendeduser). I thought that there is no need to manually create the password column, am I wrong? Other than that there are also issues when trying to create a superuser using py manage.py command caused by the same error. Please help me solve these issues and thank you in advance. my models.py file from django.contrib.auth.models AbstractUser class Extendeduser(AbstractUser): pass def __str__(self): return self.extendeduser my post.py (Form)file from django import forms from django.contrib.auth.forms import UserCreationForm,UserChangeForm from .models Extendeduser class CustomUserCreationForm(UserCreationForm): class Meta: model = Extendeduser fields = ('username', 'email') class CustomUserChangeForm(UserChangeForm): class Meta: model = Extendeduser fields = ('username', 'email') my admin.py file from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from .post import CustomUserCreationForm, CustomUserChangeForm from .models import Extendeduser class ExtendeduserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = Extendeduser list_display = ['email', 'username',] admin.site.register(Extendeduser, ExtendeduserAdmin)