Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Implementation fcm django to my project's requirement.
I have admin and employees on my project. And employees can make leave request and the admin must handle the request. Now I must notify admin that ok that user have sent you a leave request and admin can now accept/reject the notification. After that again I need to notify that particular user that ok your request is accepted/rejected. class AcceptRequest(APIView): def post(self, request, *args, **kwargs): id = kwargs.get('id', 'Default Value if not there') status = kwargs.get('status', 'Default Value if not there') leave_request = LeaveRequest.objects.get(pk=pk) print(leave_request) if status == accept : leave_request.status = 'accept' else: leave_request.status = 'reject' Urls: url( r"v1/acceptRequest/(?P<id>\d+)/(?P<status>accept|reject)", #send accept or reject also as kwargs AcceptRequest.as_view(), name='acceptRequest' ), How can I implement this in django? I saw fcm-django but it says it is for mobile device. Or is there any implementation method to it ? -
why the ajax powered button is not working in django?
I am trying to implement a like button in django using AJAX. My models are: class post(models.Model): Profile=models.ForeignKey(Profile,on_delete=models.CASCADE) Picture=models.ImageField(upload_to='PostMedia',blank=True,null=True) DatePosted=models.DateTimeField(default=timezone.now) Content=models.TextField(blank=True,null=True) user_like=models.ManyToManyField(User,related_name="likes",blank=True) def __str__(self): return self.Profile.user.username @property def totallikes(self): return self.user_like.count() class Meta: ordering=['-DatePosted'] @property def like_count(self): return len(likes.objects.filter(post=self)) while my urls for it is:- path('like/',views.like_button,name='like_button'), my view function is:- def like_button(request): if request.method=='POST': user=request.user postobject=get_object_or_404(post,pk=id) if postobject.likes.filter(id=user.id).exists(): postobject.likes.remove(user) else: postobject.likes.add(user) context={'likes_count':postobject.total_likes} return HttpResponse(json.dumps(context),content_type='application/json') finally the template is:- {% for p in result %} <div class="SpriteContainer"> <input type="button" class="like" name="{{ p.id }}" value="Like"> <p>{{ p.totallikes }}</p> </div> {% endfor %} <script> $('.like').click(function(){ var pk=$(this).attr('name') $.ajax({ type:"POST" url:"{% url 'like_button' %}" data:{'pk':pk,'csrfmiddlewaretoken':'{{ csrf_token }}'} dataType:"json" success:function(response){ alert('Company likes count is now'+response.count_likes); } error:function(rs,e){ alert('Something went wrong') } }); }) one more thing when i am looking at my post entries in django admin, it already makes many to many relationship with all possible users. Is it correct? -
How can i choose choice related on ForeignKey
How can i set dynamically choices when i add new objects in django admin site i have 3 models in models.py (Company, Department, User) when i add User in admin site, i want to set choices. but it didn't work. User have two fields (dept, company) and each field related on Company and Department. what i want to do is that if i choose A company then dept querysets set to dept which A company has only. how can i set queryset dynamically when i create objects in django in model.py class Company(models.Model): c_name = models.CharField(max_length=30) def __str__(self): return self.c_name class Department(models.Model): d_name = models.CharField(max_length=30) def __str__(self): return self.d_name class User(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE,blank=True, null=True) wnum = models.IntegerField(default=0) name = models.CharField(max_length=10) user_pic = models.ImageField(null=True) dept = models.ForeignKey(Department, on_delete=models.CASCADE, blank=True, null=True) job = models.CharField(max_length=20, choices=job_list) user_id = models.CharField(max_length=30, default="") user_pw = models.CharField(max_length=30, default="") def __str__(self): return self.name in forms.py class UserForm(ModelForm): class Meta: model = User dept = ModelChoiceField(queryset=Dept.objects.get(d_name="A") -
Reverse for 'product' not found. 'product' is not a valid view function or pattern name
url.py of list app urlpatterns = [ path(r'^Products/$',views.product,name='Products'), ] views.py of list app def product(request): return render(request,'list/product.html',all_dict) template in which tagging <a class="level-top" href="{% url 'list:product' %}"> -
TemplateNotFound after app deployed to Heroku
I've deployed an Flask app to Heroku. The app worked in the environment, but on the server it fails to load the template. File structure: project-------------------------------------------------- | | | | | | data static templates app.py Procfile requirements.txt | home.html Procfile: web: gunicorn app:app app.py: app = Flask(__name__, template_folder='templates') # Make the WSGI interface available at the top level so wfastcgi can get it. wsgi_app = app.wsgi_app @app.route('/', methods=['GET']) def home(): feed = request.args.get('feed', None) if feed== None: posts = load_feed(' ') else: posts = load_feed(feed) return render_template("home.html", posts=posts) if __name__ == '__main__': import os HOST = os.environ.get('SERVER_HOST', 'localhost') try: PORT = int(os.environ.get('SERVER_PORT', '5555')) except ValueError: PORT = 5555 app.run(HOST, PORT) Log: https://pastebin.com/Vwq0p9mE -
How to install pycurl on Elastic beanstalk (django+celery+sqs)
I am using SQS for my Django/Celery application on AWS Elastic Beanstalk. Everything works great on my localhost, but I when I deploy to Elastic Beanstalk I always get this error regarding pycurl: File "/opt/python/run/venv/local/lib/python3.6/site-packages/kombu/asynchronous/http/curl.py", line 43, in init raise ImportError('The curl client requires the pycurl library.') I tried different ways (e.g. manually install pycurl), but just cannot make it work. Could anyone please help here? Thanks a lot! -
How to annotate a QuerySet with a filtered self join in django
Motivation I have a dataset with the results of sports matches, which I want to annotate with past performance in the time period leading up to each match. The way I think about doing this is: Annotate each Match with the set of matches which took place within the relevant time period (MatchManager.matchset_within_period below). Annotate each Match with the aggregation of stats across this set of related matches (MatchManager.annotate_with_stats below). I am able to do this with a somewhat convoluted query (outlined below) involving an extra Dataset model which I traverse up to and back down from in order to get a reference to the full set of matches, which I can then filter and aggregate. Question This approach seems really complicated, and probably bad for performance. It's definitely difficult to follow (or at least unintuitive) for a reader. Is there a way to obtain the match set I need for step (1) directly, without the extra model (e.g., using a Subquery direclty on Match)? Example usage In [1] test_matches = Match.objects.filter(...) Match.objects \ .annotate_with_stats(for_days=300) \ .filter(id__in=test_matches) \ .values('pk', 'home_team_avg_score') Out[1] <MatchQuerySet [{'id': 287, 'home_team_avg_score': 91.04166666666667}, {'id': 288, 'home_team_avg_score': 91.21739130434783}, {'id': 289, 'home_team_avg_score': 92.45833333333333}]> Simplified code models.py (simplified) class Team(models.Model): … -
getting MultiValueDictKeyError: 'data' when sending HTTP post request SWIFT
How to construct a json object with name 'data' in SWIFT? I am trying to send a HTTP post request using SWIFT. The server is in Django.The json object should be sent with the name 'data' for the the server to handle it correctly. print(request.POST) gives the following output QueryDict: {'{"data":{"df":10,"sdvm":10,"mvm":10,"fpdf":10,"watchId":"AppleTest","mood":1,"locLat":0,"p625":10,"mangle":10,"sdangle":10,"fatigue":1,"id":"123","battery":20,"pain":1,"medication":1,"locLon":0,"activity":1,"timestamp":"2019-01-04T18:28:04.614-05:00","promptDisplay":"False","sleep":1,"heartrate":100}}': ['']} jsonStr = request.POST["data"] gives the following error "KeyError: 'data' " When I constructed json in javascript I am not getting the error. print(request.POST)gives the following output when JSON is constructed in javascript. QueryDict: {'data': ['[{"id":"123","watchId":"AppleTest","timestamp":"2019-01-04T18:28:04.614-05:00","battery":20,"mvm":10,"sdvm":10,"mangle":10,"sdangle":10,"p625":10,"df":10,"fpdf":10,"pain":1,"fatigue":1,"mood":1,"sleep":1,"medication":1,"activity":1,"promptDisplay":"False","heartrate":100,"locLat":0,"locLon":0}]']} The Query dict received by the server is different in both cases. request.POST["data"] can't retrieve the key-data when Im working in SWIFT. //The following swift code is used for sending post request func JSONStringify() { let json = ["data":["id":"123","watchId": "AppleTest","timestamp":"2019-01-04T18:28:04.614-05:00","battery":20,"mvm":10,"sdvm":10,"mangle":10,"sdangle":10,"p625":10,"df":10,"fpdf":10,"pain": 1,"fatigue":1,"mood":1,"sleep":1,"medication":1,"activity":1,"promptDisplay":"False","heartrate":100,"locLat":0.0,"locLon":0.0]] print(json) if let jsondata = try? JSONSerialization.data(withJSONObject: json){ let url = URL(string: "http://0.0.0.0:8/pylite/pain_data_rcv")! var request = URLRequest(url: url) request.httpMethod = "POST" request.httpBody = jsondata let task = URLSession.shared.dataTask(with: request) { data, response, error in print("got here",response as Any) guard let data = data, error == nil else { print(error?.localizedDescription ?? "No data") return } print(response as Any) let responseJSON = try? JSONSerialization.jsonObject(with: data, options: []) print(responseJSON as Any) if let responseJSON = … -
How do i implement Logic to Django?
So I have an assignment to build a web interface for a smart sensor, I've already written the python code to read the data from the sensor and write it into sqlite3, control the sensor etc. I've built the HTML, CSS template and implemented it into Django. My goal is to run the sensor reading script pararel to the Django interface on the same server, so the server will do all the communication with the sensor and the user will be able to read and configure the sensor from the web interface. (Same logic as modern routers - control and configure from a web interface) Q: Where do I put my sensor_ctl.py script in my Django project and how I make it to run independent on the server. (To read sensor data 24/7) Q: Where in my Django project I use my classes and method from sensor_ctl.py to write/read data to my djangos database instead of the local sqlite3 database (That I've used to test sensor_ctl.py) -
Is there a Django admin form field that allows for a list of optional suggested values instead of strictly validated choices?
Given a model with a CharField, I'd like admin users to be able to pick from a list of suggested values for the CharField, however unlike choices I'd like to allow alternative free-text input. Is there such a type of form-field I can configure for my ModelAdmin for this model's CharField? -
Django - get list of grouped inputs from HTML form
In my form I have some generated fields similar to these ones: <input name=data[1][1][first_name] type="text"> <input name=data[1][1][last_name] type="text"> <input name=data[1][2][first_name] type="text"> <input name=data[1][2][last_name] type="text"> <input name=data[3][1][first_name] type="text"> <input name=data[3][1][last_name] type="text"> After form is sent I'd like to get the data in view. request.POST gives me 'flat' QueryDict: [QueryDict(6)]: data[1][1][first_name]: aaa data[1][1][last_name]: bbb data[1][2][first_name]: ccc data[1][2][last_name]: ddd data[3][1][first_name]: eee data[3][1][last_name]: fff What is best way to get list, dict, or something else which will be nicely iterable and I'll be able to achieve data by indexes like that: for id in data: for number in id: print(number['first_name']) print(number['last_name']) -
Add button to Django admin index page
I want to add a site-wide action to Django admin, called "Synchronize SQL-KB". For that I have copied locally templates/admin/index.html file from Django and modified it as follows: ... {% if app_list %} <table> <tr> <td> <a href="sync-sql-kb/">Synchronize SQL-KB</a> </td> </tr> </table> {% for app in app_list %} ... So as you can see I want the link button to trigger a request to /admin/sync-sql-kb/. How to register this URL now? Where and how to implement a handler function? Note that this situation in my view differs from other SO questions in that the action is site-wide, rather than bound to a specific Django model. -
Django: Declare Users as 'Logged In' and Save Status
I have a custom authentication backend for my Django website that I’m hooking up to a MySQL database. I’m writing custom authentication procedures to see if the user is in the database. If they are in the DB, then I want to let them have access to the entire website. Otherwise, I want to keep them at the login screen. The problem that I’m running into is how to give them access to the rest of the site for each view and save the fact that they are logged in? How do I save their ‘authenticated’ status each time they access a new view? -
Django error: type object 'HttpRequest' has no attribute 'META'
I am new to django. I am coding a urlshortner now I wanted to ad functionality to read Http referer to count number of times the link has been clicked from various social platforms. In documentation it states that HttpRequest object that in included in django.http will extract it using - HttpRequest.META['HTTP_REFERER'] So I did this to print out the type of info that it contains - from django.http import HttpRequest from .models import UrlSave def display(request,id): print(HttpRequest.META['HTTP_REFERER']) try: short_url = UrlSave.objects.get(pk=id) visit_time = short_url.times_visited short_url.times_visited = short_url.times_visited+1 url = short_url.to_view short_url.save() context = {'visit':visit_time,'url':url} return render(request,'shorturl/previsit.html',context) except: return HttpResponse('Wrong Url') But when I visit the link it prints out the error in CLI - AttributeError: type object 'HttpRequest' has no attribute 'META' I am unable to find out the reason for it even after going through many stackoverflow pages Please Help -
How to use two unique constraints Django model?
I have a Django model for a player of a game class Player(models.Model): name = models.CharField(max_length=50) team = models.ForeignKey('Team', on_delete=models.CASCADE, blank=True, null=True) game = models.ForeignKey('Game', on_delete=models.CASCADE) objects = GameManager() class Meta: unique_together = ('name', 'game',) I have only one unique constrain, that the name and the game are unique together. Now, I would like to extend our page by adding registered users. So, I would add this to the model. user = models.ForeignKey('auth.User', on_delete=models.CASCADE, blank=True, null=True) So, an registered user can subscribe to a game by adding a name, team, game, and his/her user. However, the user should only be able to add his account once to an game, which would be a second unique constrain unique_together = ('user', 'game',) Is it possible to give in Django two unique constraints to the model? Or do I have to search in the table manually prior to saving the new entries? Or is there a better way? Thanks -
How do I import a model into my console so that I can lookup instances of it from my db?
I'm using PyCharm 2018.2 and Python 3.7. How do I import a model into my console so that I can lookup instances of it from the db? I thought this would do it from .models import Article but when I run this on a console, I get the below errors. I'm not sure what they mean >>> from .models import Article Traceback (most recent call last): File "<input>", line 1, in <module> File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 20, in do_import module = self._system_import(name, *args, **kwargs) KeyError: "'__name__' not in globals" Below is my models.py file ... from django.db import models # Create your models here. from datetime import datetime from django.utils import timezone class Webpage(models.Model): path = models.CharField(max_length=100) def __str__(self): return self.path def create(cls, path): Webpage = cls(path=path) return Webpage class Article(models.Model): webpage = models.ForeignKey(Webpage, on_delete=models.CASCADE,) path = models.CharField(max_length=100) url = models.TextField time = models.DateTimeField(default=datetime.now) votes = models.IntegerField(default=0) comments = models.IntegerField(default=0) front_page = models.BooleanField(default=False) def __str__(self): return self.path @classmethod def create(cls, webpage, path, url, votes, comments): article = cls(webpage=webpage,path=path,url=url,votes=votes,comments=comments) return article -
How to adjust urls in Django and import path from Django urls
I'm trying to learn Django CRUD but when I run my code I see this error: "can not import path from django.urls: Here is my urls code: from django.contrib import admin from django.urls import path from employee import views urlpatterns = [ path('admin/', admin.site.urls), path('emp', views.emp), path('show',views.show), path('edit/<int:id>', views.edit), path('update/<int:id>', views.update), path('delete/<int:id>', views.destroy), ] Please inform me. thanks, Saeed -
How to process specific model prices in Django with Stripe
So here's my code first and foremost. I'm new to Django and trying to create an ecommerce site. The way it works is that the admin creates products and users come on to the site and purchase them. The site uses Stripe to process payments. views.py: from django.shortcuts import render from django.views import generic from django.core.paginator import Paginator from django.conf import settings import stripe import decimal stripe.api_key = settings.STRIPE_SECRET_KEY from .models import Product # Create your views here. class ProductListView(generic.ListView): model = Product paginate_by = 3 def get_context_data(self, **kwargs): # new context = super().get_context_data(**kwargs) context['key'] = settings.STRIPE_PUBLISHABLE_KEY return context def charge(request): if request.method == 'POST': charge = stripe.Charge.create( amount=round(decimal.Decimal(request.POST['price'])), currency='usd', description='A Django charge', source=request.POST['stripeToken'] ) return render(request, 'store/charge.html') product_list.html: {% extends 'home/base_generic.html' %} {% load static %} {% load cool_paginate %} {% block add %} <link rel="stylesheet" href="{% static 'store/css/products.css'%}"> {% endblock %} {% block title %} <title> Store </title> {% endblock %} {% block content %} <div class="row"> {% for product in product_list %} <div class="col-sm-4"> <div class="card" id="django-card" style="width: 300px; height: 350px;"> <img class="card-img-top" src="{{ product.image.url }}" height=150px width=150px> <div class="card-body"> <h5 class="card-title">{{ product.name }}</h5> <p class="card-text"> {{ product.description }} And only {{ product.price }}! </p> <form action="{% … -
Where in Django can I run startup code that requires models?
On Django startup I need to run some code that requires access to the database. I prefer to do this via models. Here's what I currently have in apps.py: from django.apps import AppConfig from .models import KnowledgeBase class Pqawv1Config(AppConfig): name = 'pqawV1' def ready(self): to_load = KnowledgeBase.objects.order_by('-timestamp').first() # Here should go the file loading code However, this gives the following exception: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. So is there a place in Django to run some startup code after the models are initialized? -
Comparing static variable with DB in Django view?
I have the below view. I am looking to say, IF due date in the database is < today, then your project is late. The date format is YYYYMMDD I'm not able to get today to print to the screen, so I think I'm doing something wrong. The todo_list variables can print. The todo_list is somethnig I loop through in the HTML. The 'today' variable will be static. Can anyone help? def todo(request): dt_now = datetime.now() target_hour = int(dt_now.strftime('%s')) today = datetime.fromtimestamp(target_hour).strftime('%Y%m%d') todo_list = Todo.objects.filter(Q(creator=request.user) | Q(assignee=request.user)).order_by('priority') context = {'todo_list' : todo_list, 'today' : today} return render(request, 'home.html', context) And this is the HTML {% for todo in todo_list %} <div class="col-sm-3 mb-4"> <div class="card h-100"> {% if todo.complete is False %} <h5 class="card-header">{{ todo.text }}</h5> {% else %} <h5 class="card-header">{{ todo.text }} <small><span class="badge badge-warning">CLOSED</span></small></h5> {% endif %} <div class="card-body"> <p class="card-text"> <table class="table table-hover"> <tr> <td>Created By</td> <td> {{ todo.today }} {% if todo.due > todo.today %} OVERDUE {% endif %} </td> -
How to add change password functionality to Django / React app
I'm trying to add change password functionality to a Django / React app. I'm struggling to find any way to make this work. I'm using django-rest-auth and django-rest-framework. I would be happy to either submit the password change request from a React page, or else to redirect the user to the native Django template-driven page - leaving my SPA, but acceptable to get the functionality working. However, the change password page requires the user to be logged in, and I can't see how to do this from the React app. I've set up the Django page with a custom template, but if I link to it from the app then the URL redirects to login: If I copy the request to cURL and run it in a terminal, I see this error: # api/urls.py from django.urls import include, path from django.contrib.auth import views from django.conf.urls import include, url urlpatterns = [ ... path('password_change/', views.PasswordChangeView.as_view(template_name='account/password_change.html'), name='password_change'), ] account/password_change.html {% extends 'account/base.html' %} {% block body_block %} <h1>Change your password</h1> <form method="post" action="."> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit" /> </form> {% endblock %} I log in to my app and then navigate to where the change password page … -
get attribute name based on slug
I have a page listing articles based on categories. The category is filtered from the slug in the url. I want to display a tag in the template with the category name. With get_context_data I am able to retrive the slug and use it as {{categoryslug}} But how do I get the name of the category given the slug? Model.py class Category(models.Model): name = models.CharField(max_length=50,unique=True, blank=True) slug = models.SlugField(max_length=100,unique=True, blank=True) def __str__(self): return self.name class Article(models.Model): title= models.CharField(max_length=40, blank=True) category = models.ForeignKey('Category', on_delete= models.PROTECT, related_name="pcat", blank=True) def __str__(self): return self.title View.py class ListArticleView(ListView): model = Article context_object_name = "listcat" template_name = "myapp/categories.html" paginate_by = 5 def get_queryset(self): return Article.objects.filter(category__slug=self.kwargs['cat_slug']) def get_context_data(self, **kwargs): context=super(ListArticleView,self).get_context_data(**kwargs) context['categoryslug']=self.kwargs['cat_slug'] return context URLS.py path(('/<cat_slug>'), views.ListArticleView.as_view(), name='some_categories')) -
How do I load the first object from a result set?
I'm using PyCharm 2018.2 and Python 3.7. I want to load an object from my database. It doesn't matter, which one, so I just figured the first one that is returned by a query for all objects. I thought I could do this in the console by running obj = Article.objects.first() but this is spawning a bunch of errors taht I can't quite interpret. How do I load the first object from my db? /Users/davea/Documents/workspace/articleclip_project/venv/lib/python3.7/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>. """) manage.py@articleclip_project > obj = Article.objects.first() bash -cl "/Users/davea/Documents/workspace/articleclip_project/venv/bin/python /Applications/PyCharm.app/Contents/helpers/pycharm/django_manage.py obj = Article.objects.first() /Users/davea/Documents/workspace/articleclip_project" bash: -c: line 0: syntax error near unexpected token `(' bash: -c: line 0: `/Users/davea/Documents/workspace/articleclip_project/venv/bin/python /Applications/PyCharm.app/Contents/helpers/pycharm/django_manage.py obj = Article.objects.first() /Users/davea/Documents/workspace/articleclip_project' Process finished with exit code 2 -
Django test case loop for all url_patterns for anonymous users
My webapp requires a login, and I want to test that all url_patterns in a django app, badges, redirect to the login/home page. I have a loop here that can handle simple urls: def test_all_badge_page_status_codes_for_anonymous(self): ''' If not logged in then all views should redirect to home page ''' for path in urlpatterns: name = 'badges:%s' % path.name self.assertRedirects( response=self.client.get(reverse(name)), expected_url='%s?next=%s' % (reverse('home'), reverse(name)), ) However, this fails for any path that requires a keyword argument, such as: path('<int:badge_id>', views.detail, name='badge_detail'), How can I automagically, insert arguments for paths so I don't have to write a separate line for each path in url_patterns? -
Background image in inline style
I need to use static files in my inline styles background-image in my HTML page, but the image won't show. I've found all kinds of solutions, but I'm still not sure how to show a background-image from a stic file. It's used in my home.html template in a holidays app <a href="#" style="background-image:url(../../../../../static/img/kreta.jpg);" title="Kreta" alt="Kreta"> I don't see my image now and I expect to see my background-image