Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to paginate ForeignKey instances in DetailView
I have written simple blog and my problem is how to use Django pagination to paginate ForeignKey Comments In a DetailView of post. I know that Django provides comments framework but for learning purposes my own simple comment system is what i want. My models.py: class Comment(models.Model): comment_text = models.TextField(blank=True) comment_author = models.CharField( max_length=50, help_text="Enter your nickname.") comment_date = models.DateTimeField(auto_now_add=True) post = models.ForeignKey('Post', on_delete=models.CASCADE, related_name='comment') Views.py: class PostDetailView(generic.DetailView): model = Post And template: {% extends "base_generic.html" %} {% block title %} <title>Blog Post</title> {% endblock %} {% block content %} <div> <h1>{{post.title}}</h1> <em>{{post.post_date}} by {{post.author}}</em> {% if post.author == user %}<a class="btn btn-dark btn-sm" href="{% url 'edit_post' post.id %}">Edit</a>|<a class="btn btn-dark btn-sm" href="{% url 'delete_post' post.id %}">Delete</a>{%endif%} {%if post.image %}<div class="post-image"><img src="{{post.image.url}}"></div>{%endif%} <div class="post-content"><p>{{post.post_text}}</p></div> <div style="margin-left:20px;margin-top:20px"> <h4>Comments</h4> {%if post.comment %} {%for comment in post.comment.all %} <hr> <em>Posted by {{comment.comment_author}} on {{comment.comment_date}}</em> <p>{{comment.comment_text}}</p> {%endfor%} {%endif%} <a href="{%url 'comment_post' post.id%}" class='btn btn-success'>Add a comment</a> </div> {% endblock %} My pagination is already in base_generic.html all I am looking for is how to extend my class based view to paginate comments instances only. -
Error django: AttributeError: module 'django.contrib.auth.views' has no attribute 'Home'
I'm currently trying to implement the ability to login and logout into my django site and I'm getting the following error when attempting to use the command python manage.py runserver while in the virtual environment. I'm using django 2.2 my porject: realtime |-core |-nodejs |-realtime |-templates | |-index.html |-url.py my code url.py from django.conf.urls import include, url from django.contrib import admin from django.contrib.auth import views urlpatterns = [ url(r'Home/$', views.Home, name='Home'), url(r'^node_api$', views.node_api, name='node_api'), url(r'^accounts/login/$', auth_views.LoginView.as_view(template_name='myapp/login.html')), url(r'^login/$', views.LogoutView.as_view(template_name=template_name), name='logout'), ] -
What's the best way to implement DB Router in Django?
I have implemented Automatic DB Routing in Django and using AWS Aurora for Database with replication. I have found a minor replication lag with my database which hampering the flow. Issue occurs let's say when a read queryset is getting executed with 'slave' then while updating value using that queryset showing error something like 'read-only access for that table.' that means for update it should route to master db. Here is my DB Settings for Multiple DB: DATABASES = { 'master': { 'ENGINE': 'django.db.backends.mysql', 'STORAGE_ENGINE': 'MyISAM / INNODB / ETC', 'NAME': 'db', 'USER': 'master', 'PASSWORD': 'master', 'HOST': 'localhost', 'PORT': '3306', }, 'slave': { 'ENGINE': 'django.db.backends.mysql', 'STORAGE_ENGINE': 'MyISAM / INNODB / ETC', 'NAME': 'db', 'USER': 'name', 'PASSWORD': 'pass', 'HOST': 'localhost', 'PORT': '3306', }, 'slave2': { 'ENGINE': 'django.db.backends.mysql', 'STORAGE_ENGINE': 'MyISAM / INNODB / ETC', 'NAME': 'db', 'USER': 'name', 'PASSWORD': 'pass', 'HOST': 'localhost', 'PORT': '3306', } } DATABASE_ROUTERS = ['path.to.AuthRouter'] Please provide me the best way to handle multiple db route automatically in django. -
Python Requests Library JSON as BODY in POST Request
I'm using Python Requests library and I'm having a hard time constructing a POST request. When I use POSTMAN, I am able to receive the correct response, but when I try to implement my code, something goes wrong. Any help would be MUCH appreciated. Here is my code: url = 'some url' headers = { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': 'Basic {}'.format(AUTH_STRING) } payload = { "transaction_details": { "order_id": "ORDER-{}".format(order_id), "gross_amount": order_total } } snap_token = requests.post(url, headers=headers, json=payload) -
New to Django and Python, custom class based view am I doing this correct?
I am trying to fight my way trough self learning Django (as this is a beast on it's own) and Python (just for coding <3) in combination with nginx, postgresql and gunicorn - I have some limited experience with PHP. After a short struggle I managed to get everything up and running. (enough tutorials for that around ) Basically what I am doing right now is trying to customize the Django authentication system, specifically starting with the login part and adding a remember me option for the user, I got everything to work the way I like but I am wondering if I am doing everything the 'correct' (or convenient) way? ( I started with customizing the user model so you might encounter some bits and pieces related to that. ) So I could use some pointers of what I can do better or improve. In my project directory settings.py SESSION_EXPIRE_AT_BROWSER_CLOSE = True I added the above line so that any sessions that are created are expired on browser close by default ( yes this might not always work in chrome ). in my APP directory for the user authentication: forms.py from django import forms from django.contrib.auth.forms import AuthenticationForm class … -
Django ORM annotate with condotional check
I've got 3 models: User, Event, Participator: class Event(models.Model): STARTED = 'started' NOT_STARTED = 'not_started' FINISHED = 'finished' STATUS_CHOICES = ( (STARTED, _('Started')), (NOT_STARTED, _('Not started')), (FINISHED, _('Finished')), ) status = models.CharField(max_length=50, choices=STATUS_CHOICES) creator = models.ForeignKey('users.User', on_delete=models.CASCADE) max_participators_count = models.PositiveIntegerField() class Participator(models.Model): INVITED = 'invited' JOINED = 'joined' PARTICIPATED = 'participated' PARTICIPATOR_STATUSES = ( (INVITED, _('Invited')), (JOINED, _('Joined')), (PARTICIPATED, _('Participated')) ) status = models.CharField(max_length=50, choices=PARTICIPATOR_STATUSES) participator = models.ForeignKey('users.User', on_delete=models.CASCADE) event = models.ForeignKey('events.Event', on_delete=models.CASCADE, related_name='participators_set') I'm to write query where I can annotate to Event info about user's participation status. There are 4 available statuses: is_creator, participator, can_join, cannot_join. is_creator - When user is event's creator participator - When user is in event's participators_set and his status isn't INVITED can_join - When participators_count < max_participators_count of Event and Event's status is NOT_STARTED cannot_join - default value Event.objects\ .annotate(participators_count=Count('participators_set', filter=~Q(participators_set__status=Participator.INVITED)))\ .annotate(user_status=Max(Case( When(creator=user, then=Value('is_creator')), When(Q(participators_set__participator=user) & ~Q(participators_set__status=Participator.INVITED), then=Value('participator')), When(Q(status=Event.NOT_STARTED) & Q(participators_count__lt=F('max_participators_count')), then=Value('can_join')), default=Value('cannot_join'), output_field=CharField()))) I'm getting an error as I'm trying to avoid Event copies by using Max(): FieldError: Cannot compute Max('<Case: CASE WHEN <Q: (AND: ('creator', <User: email@a.com>))> THEN Value(is_creator), WHEN <Q: (AND: ('participators_set__participator', <User: email@a.com>), (NOT (AND: ('participators_set__status', 'invited'))))> THEN Value(participator), WHEN <Q: (AND: ('status', 'not_started'), ('participators_count__lt', F(max_participators_count)))> THEN Value(can_join), ELSE … -
How does Django know where my html page is?
I am a beginner to web-development and have a small doubt that would clear my understanding of the file-system. The Situation So I have set up a sample django project and i want to open a link like http://127.0.0.1:8000/nick on my django page. To archive this please look at the images below. Step 1 : I added a path to that name. Step 2 : I made a function in the views.py that will take the request to the nick.html file Step 3 : My simple nick.html file The Doubt I have So now I am wondering how Django is able to locate nick.html in my codebase because if you look at my project structure, the html file is in jobs>templates>jobs>nick.html and in my views.py file if: (i) I give return render(request, 'jobs/nick.html') it works !! (ii)But if I give, return render(request, 'templates/jobs/nick.html') ,it throws an error page stating - TemplateDoesNotExist at /nick So, all I want to know how is this thing working because a general computer background guy will assume to provide the full path in such scenarios so why does it throw an error even though the path is correct? Am I missing something here? Please help. … -
I want to fetch last months connection from the database from django models object
def handle(self, **options): clients=Client.objects.values('uid','lastConnection').order_by('lastConnection') print clients today = datetime.datetime.now() print today last_month = today.month - 1 if today.month>1 else 12 last_month_year = today.year if today.month > last_month else today.year - 1 How to fetch last months connection from the object models can anyone help? -
Unable to set default vale of DateTimeField to "0000-00-00 00:00:00"
fld_date_time = models.DateTimeField(db_column='FLD_DATE_TIME', blank=True, null=True, default="0001-00-00 00:00:00") This field in models.py throws error as: ["'0000-00-00 00:00:00' value has the correct format (YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) but it is an invalid date/time."] How to add the default value in django? -
Django catch-all URL thatstill works with APPEND_SLASH
I am trying to route all unknown URLs to a single view. However, in doing this my known URLs only work when they do not have a trailing slash, despite setting APPEND_SLASH to True in "settings.py". Here is some code: settings.py: APPEND_SLASH = True ADMIN_URL = "admin/" urls.py: from django.conf import settings from django.contrib import admin from django.urls import include, path, re_path from myapp.views import my_catch_all_view urlpatterns = [ path(settings.ADMIN_URL, admin.site.urls), re_path(r"^.*", my_catch_all_view), ] If I go to "localhost:8000", I correctly get routed to my catch-all view. And if I go to "localhost:8000/foobar/", I correctly get routed to my catch-all view. And if I go to "localhost:8000/admin/", I correctly get routed to the admin view. But, if I go to "localhost:8000/admin", I incorrectly get routed to my catch-all view. I have seen this answer, but unfortunately that doesn't work for me. Any suggestions? -
ajax like button django
my ajax jquery : $(".likebutton").on('click', function () { post_id=$(this).attr('name'); console.log('CLICKED IN LIKE'); $.ajax({ dataType: 'json', url: post_id +'/like/', data: { }, success: function (data) { alert("SUCESSS"); if (data.success) { console.log("SUCCESS") $(this).parents('.timeline-footer').html('<p class="pull-left m-r-15">'+data.likecount+ 'Likes </p>'+ '<a class="likebutton" style="color: blue"'+ 'href="dashboard/tasks/'+ post_id +'/like/"'+ 'class="m-r-15 text-inverse-lighter"><i'+ 'class="fa fa-thumbs-up fa-fw fa-lg m-r-3"> </i>'+ 'Like</a>'+ '<a href="dashboard/tasks/'+post_id +'/$/" class="m- r-15 text-inverse-lighter"><i'+ 'class="fa fa-comments fa-fw fa-lg m-r-3"> </i>'+ 'Comment</a>') // here you update the HTML to change the active to innactive }else{ console.log("ERROR"); alert("ajax call not success."); } } }); }); my like template: <p class="pull-left m-r-15"> {{ obj.like.count }} Likes </p> <form action="{% url 'student:like' pk=obj.id %}" method="POST"> {% csrf_token %} <input type="submit" value="Like" name="{{ obj.id }}" class="likebutton m- r-15 text-inverse-lighter" {% if request.user in obj.like.all %} style="color: blue" {% endif %}"></input><i class="fa fa-thumbs-up fa- fw fa-lg m-r-3"></i> </form> My view: def LikeToggleView(request,pk=None): print("NOT AJAX") if request.is_ajax(): post_id = request.POST.get('post_id') response_data = {} obj = get_object_or_404(Task, pk=post_id) user = request.user print("AJAX LIKE") if user in obj.like.all(): obj.like.remove(user) note = Notification.objects.create(sender=user, task=obj, notification = user.username + ' Disliked Your Post ' + obj.title) note.receiver.add(obj.student) else: obj.like.add(user) note = Notification.objects.create(sender=user, task=obj, notification = user.username + ' Liked Your Post ' + obj.title) note.receiver.add(obj.student) response_data['likecount'] = obj.like.count … -
Celery with multiple django sites
I have a one django backend for few customer's sites: my_proj |- my_proj |- __init__.py |- settings.py |- settings_development.py |- settings_production_1.py |- settings_production_2.py |- settings_production_3.py |- my_app_1 |- my_app_2 ... Each site is a separate proccess managed by supervisord and uses separate database. Also I have a redis on a separate server. I need some celery background tasks with database access. How can I do that? -
how to make anaconda and django application live
I developed one application using anaconda (for python AI,ML) and Django. I want to make live this application. can I make live this application using Elastic beanstalk or there is another way ? please guide. Thanks in advance -
EC2: WIndows instance not accessible from public IP
I know its quit old thread but before writing I tried all ways but could not succeed. So I am not able to access my Django dev server which is running on Window ec2 instance on port 80. I added following Inbound rule in Security group. HTTP TCP 80 0.0.0.0/0 HTTP TCP 80 ::/0 I also check in ACL and I saw all traffic are allowed. Just to resolve any binding IP issue . I am running my instance on 0.0.0.0:80 Still I am not able to access on public and private IP on port 80 or anyone which i set under inbound rule. However when I access public IP or localhost and it's IP like 127.0.0.1 from the same windows instance. I am able to access it. Please help me out with this issue. -
One model-object is JSON-serializable and another is not
There are two objects. Both inherit from models.Model. Both have ImageField, ManyToMany and other basic django model fields. Both serialized through something like that: for obj in object_model.objects.all(): [obj.id]['object'] = obj This is a product cart of sorts. The problem is, one is seriaziled without any problem is the other one is "not JSON serializeable". I try to figure out what fields or values are actually causing that, since, of course, those are different classes, but i'm unable to find that big of a difference between them. I also tried to serialize like so: for obj in object_model.objects.all(): [obj.id]['object'] = { 'id': obj.id, 'title': obj.title, 'image_preview': obj.image } The problem with this method is that as an image i can only get url string and i need an actual image to crop it using easy_thumbnail. Any help will be appreciated, thanks! -
Error: djnago.db.migrations.exception.MirationSchemaMissing: Unable to create the django_migrations table('42000',[42000]
I am getting error while i am trying to django default migrate with sqlserver(Error: enforce unique constraints are not supported in azure sql data warehouse) Versions: Djanago(2.1) Sqlserver Please help me. -
Django prefetch_related in loop, what is wrong?
i am trying to reduce the amount of queries in a Django app, but can't figure out how to do it the right way. I have a model with product all products has a default price, now I have a customerproduct with some customer related product prices I am open for a redesign ;) class Product(models.Model) name = models.CharField(max_length=255) price = models.DecimalField(default=0, max_digits=12, decimal_places=2) .... def get_prices(self, customer=None): ''' get prices for the current product based on the price matrix given by bbp ''' if customer: prices = self.get_customer_prices() if prices: self.price = self.customerproduct_set.filter(deleted=0).last().price return self class CustomerProduct(AbstractProductPrice): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) price = models.DecimalField(default=0, max_digits=12, decimal_places=2) .... Now i want all products with related customer prices. products = Product.objects.all().prefetch_related('customerproduct_set') for product in products: product.get_prices(customer=1) Prefetch is not "working" i don't understand how to use it.. please help. I have 31 products in my db and django_debug_tool result in 35 queries. -
Flask vs Django Rest Framework
We are planning to make a search service of our existing urdu search engine which we developed from scratch by collecting complete urdu content from all over the web and made it searchable. Now we want to provide facility of search using RESTfull API to our clients so they can use it on their websites or on custom application as a custom search feature provided by google. We will use REST api for this purpose. but for client authentication and authorization we want to use API key like feature, so that we can keep track of query limit of each user and user authentication. our REST service will first authenticate request by API key authentication and authorization then send search results on client application. can anyone tell me which is the best for my case. For Rest API creation (Flask or Django REST framework) and for Front-end with clients dashboard and query analytics (Php or Django) kindly reply me as soon as possible. -
How to check that data is deleted or not in PostgreSQL
Yesterday we've added a simple form to our site, and we just implemented an API View using Django which is connected to a PostgreSQL database. Today I queried the database to see how many rows are submitted, and I encountered a strange thing in the results, We've created and migrated our model using Django ORM, so the primary key is defined as an auto-increment integer field, the problem is row ids are not continuous and they are so diverse, when I'm writing this question, the max id value is 252, but we have only 72 records in the table, I've seen this before in other tables, but those tables were subjected to delete and update queries, but we only insert to this new table, and my question is: is our data deleted or it's a normal behavior in PostgreSQL? I've searched in google and it seems that the only way is to check WAL logs, but we have not enabled that for our database yet, is there another way to check that the data is consistent or not? Thanks. -
Refresh Drop-down based on selection - Django Smartmin
We have models like: Class District: name = models.CharField() Class Village: name = model.CharField() district = models.Foriegnkey() Class Location: name = models.CharField() village = models.Foreginkey() We are using Smartmin for CRUD Operations. While creating location, in my Form we are displaying District, Village dropdown and name field (name of the location). I need to refresh the village based on the district selection. Please help me in this regards. Thanks in advance -
Django: How can I perform two forloop under one tablerow?
I want to do this in my template: <tr> {% for journal in journal_debit %} <th><center>{{ journal.Date}}</center></th> <th><center>To</center></th> <th><center><{{journal.To}}</center></th> <th><center>{{ journal.id }}</center></th> <th><center>{{journal.Debit}}</center></th> {% endfor %} {% for journal in journal_credit %} <th><center>{{ journal.Date}}</center></th> <th><center>By</center></th> <th><center>{{journal.By}}</center></th> <th><center>{{ journal.id }}</center></th> <th><center>{{journal.Credit}}</center></th> {% endfor %} I want to merge two forloop in one table row in django template for a better presentation in my template.. Is it possible in django? Any idea? -
Scrapy - Reactor not Restartable in Djanjo
I have meet a porblem when I want to run my spiders in Djanjo.Some months ago.This method work for me: def crawllist(self,lists): runner = CrawlerRunner(get_project_settings()) for topic in lists: logging.error("topic name is %s" % topic.name) runner.crawl(topic.type,author = topic.author,links = topic.base_url) d = runner.join() d.addBoth(lambda _: reactor.stop()) logging.error("start crawl") reactor.run(installSignalHandlers=False) But it doesn't work now. I have read all answers about it. But doesn't work for me.The spider can run successfully when I run it locally without djanjo. But meet the Reactor not Restartable in Djanjo. I have tried a method like that def crawl(self,type,url,author): print('crawl11') module_name="Spidermanager.spiders.{}".format(type+'spider') scrapy_var = importlib.import_module(module_name) #do some dynamic import of selected spider spiderObj=scrapy_var.zhihuSpider(author = author,links = url) print(spiderObj.start_urls) runner = CrawlerRunner(get_project_settings()) runner.crawl(spiderObj) print('crawl finished') It solves the reactor problem。But the spider seems not run and crawl nothin. -
Create a Blog which support multiple type of post
I am a new user of Django, and I am trying to figure out how to created a model which can support multi-type assignement For example, I have a model Contract, and this class can contain many ContractElement A ContractElement has a title, a content and a type, this type can be "numeric", "text", "image" or "user" (the last one is a reference to an User object). In each cases, the type determine what the content is and how it will be processed by the rest of my application (including how it will be displayed on the HTML page). But I don't know what is the right way to declare the ContractElement class in order to support all these cases :( Here an example of what I want to do : I have a model "Page" which represent a blog page. on that blog page, you can add videos, images or text. I need something to represent all these case. For now, I have two solutions, the first one use inheritance : When you create a new post on the blog, you create an Element which inherit from PageElement model : class PageElement(models.Model): page = models.OneToOneField( Page, on_delete=models.CASCADE, related_name='%(class)s_elements' ) … -
Django 2.1 recalling old slug url variables
I am having some issues directing a url pattern through the following type of path: Listview --> Listview2 --> DetailView. I am running into trouble with my url patterns. Here is what I am working with: app_name = 'ism' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<slug:client_slug>/', views.CostCenterListView.as_view(), name='cost_center_list'), path('<slug:client_slug>/<slug:cost_center_slug>/', views.cost_center_detail, name='cost_center_detail'), ] The home page of this app is a list of all clients. Clicking on a client will populate a new page showing a list of that client's sub-clients (cost_center). Here is part of my template {% url %} call to my final path listed above (/slug/slug/): {% for cost_center in cost_centers %} <ul> <li><a href="{% url 'ism:cost_center_detail' cost_center.slug %}">{{ cost_center }}</a></li> </ul> {% endfor %} Adding this along with its accompanying view causes an error: NoReverseMatch at /ism/cleint_slug/ Can you confirm that my issue has to deal with my {% url %} in my template not remembering the first slug in my url path? My error message seems to indicate that it's trying to find: .../cost_center_slug instead of: .../client_slug/cost_center_slug/ My assumption is that django would magically remember the first part of my url pattern (ie client_slug), but that does not appear to be happening. Do I need to … -
Does django bulk_create possible exceptions
When using Model.objects.bulk_create([]) if an exception occurs during the insertion does it roll back the entire operation or it continues with the non conflicting records, and is there any way to know which records were inserted and which trow and error?