Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Elasticsearch dsl adding foreign key
I have a model called Poll, this model has a one to many relationship with another model called Choice 1 poll can have many choices. Every time a poll is saved, I'd like to save that poll in Elasticsearch. Model: class Poll(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) question = models.CharField(max_length=200) def indexing(self): obj = QuestionIndex( meta={'id': self.id}, question=self.question, choices=self.choice_set.count(), # How many choices are there? ) obj.save() return obj.to_dict(include_meta=True) Index class QuestionIndex(Document): question = Text() choices = Integer() class Index: name = 'questions' I have already added a signal in Django to execute to save the data in Elasticsearch. This works fine, however, I see that the value of choices is always 0 even though I add choices. The choices do get saved in my database, but the count of choices is always 0. What am I doing wrong? -
django templates show the latest data first
I have to show the latest date of data in up side first, in my original code, it only show the oldest date of data in up side and list below to newer in down side modle.py from django.conf import settings from django.contrib.auth import get_user_model from django.db import models from django.urls import reverse class Article(models.Model): title = models.CharField(max_length=255) body = models.TextField() date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) def __str__(self): return self.title def get_absolute_url(self): return reverse('article_detail', args=[str(self.id)]) views.py from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.views.generic import ListView, DetailView from django.views.generic.edit import UpdateView, DeleteView, CreateView from django.urls import reverse_lazy from .models import Article class ArticleListView(LoginRequiredMixin, ListView): model = Article.order_by('-date') template_name = 'article_list.html' login_url = 'login' in the form blow it will list the oldest date of data in up side and newer data in down side ,, what I wanna to do is the newest data in up side and older data in down side article_list.html {% extends 'base.html' %} {% block title %}Articles{% endblock title %} {% block content %} {% for article in object_list %} <div class="card"> <div class="card-header"> <span class="font-weight-bold">{{ article.title }}</span> &middot; <span class="text-muted">by {{ article.author }} | {{ article.date }}</span> </div> <div class="card-body"> {{ … -
Deploy Django web application on web server that already hosted a wordpress website
As a beginner, I am developing a django project and want to replace the website that was built on wordpress that is without any custom-make back-end function such as account login and database access. Before complete replacement, I would like to deploy the test version of django project at either the sub-directory or sub folder of the website (test.example.com or example.com/test/) to see if it functions well. However, I encountered huge difficulties when deploying the django project as it is hard to find good materials for such kind of deployment. Please share your experience if you was able to build a django website with other functional website within the same web server. The web server was based on Centos with directadmin. I used to follow the guide at but frustrated after days of try and debug..: https://opensourcemissions.wordpress.com/2010/03/12/finally-a-working-django-non-root-url-with-mod_wsgi/ -
how do I display the data cleaning results table when I press the data cleaning button?
I want to display data cleaning results in the form of tables. but I do not know how to call the function I created in my function page. def cleaning(a): a = data.ffill().bfill() return a I expect the output in my HTML page is a table. -
Create Django a many-to-one / foreign key field with a child value (Python)
To summarize my problem, I want to create a foreignKey field to show all of the songs a user has. For each song a user has I also want to see how many times that same user has played a specific song. class Songs: song = models.CharField(max_length = 30) class Profile: user = models.CharField(max_length = 30) songs_available = models.ForeignKey(Songs, models.SET_NULL blank=True, null=True,) All I want to know is a count of how many times the specific user played a specific song. -
Unresolved Library (Custom Template Tag) in Pycharm
I've created a new custom template tag to show SVG images, and it works fine (pages are rendered properly), but Pycharm is throwing an "Unresolved Library" warning that I'd like to see if I can fix. I used this answer from Django 1.10.1 'my_templatetag' is not a registered tag library. Must be one of: (which I initially thought was useful, as it allowed me to use this tag in ALL my apps.) and consisted of adding the following in my settings.py file TEMPLATES = [ { .... 'libraries':{ 'include_svg': 'myproject.templatetags.include_svg', } }, }, ] The project structure is myproject/ app1 ... myproject/ ... settings.py templatetags/ __init__.py include_svg.py ... I have my settings.py file identified in the PyCharm settings for the project. the include_svg.py file consists of from django import template from django.utils.safestring import mark_safe register = template.Library() @register.simple_tag def include_svg(file_name): return mark_safe(open(file_name).read()) and of course app1/templates/file1.html {% extends 'base.html' %} {% load static %} {% load include_svg %} ... {% include_svg 'myproject/static/img/icons/round-skip_next-24px.svg' %} ... Any thoughts on how to fix? -
How do I setup my Python Path so that pytest is able to find my Django 'manage.py' file?
I'm a college student currently working on a small Django web app project and I'm trying to get pytest up and running on my container. When I try to run pytest, I receive an error pytest-django could not find a Django project (no manage.py file could be found). You must explicitly add your Django project to the Python path to have it picked up. make: *** [pytest] Error 1 I'm wondering how to fix this error so that pytest is able to find my manage.py which is inside another folder. I've tried messing with the settings a bit but to no avail. Here's what I tried in the manage.py file: PROJECT_ROOT = os.path.dirname(__file__) sys.path.insert(0, os.path.join(PROJECT_ROOT, 'timetracker')) This is my project structure: timetracker/ |---- accounts/ |---- timetracker/ |---- settings.py |---- conftest.py |---- manage.py docker-compose.yml Dockerfile Makefile pytest.ini requirements.txt Dockerfile: ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ ENV DJANGO_SETTINGS_MODULE timetracker.settings Any advice is appreciated! -
How to call a django url after clicking on a bootstrap tab and show results on the tab content?
I have created two bootstrap tabs whose data is comming from django functions. I can easily post essential data of all tabs while the tabs are loaded but I want to load data of each tab once the tab is clicked instead of loading all data together. Bootstrap uses href or data-target to load a tab content. So, when I set django url in href attribute and activate the tab by JavaScript, the django function is invoked but bootstrap does not open the tab. It always opens the first tab. <ul id="myTab" class="nav nav-tabs bar_tabs" role="tablist"> <li role="presentation" class="active"><a href="#tab_content1" id="home-tab" role="tab" data-toggle="tab" aria-expanded="false">Profile</a> </li> <li role="presentation" class=""><a href="{% url 'edit_Peak' %}" role="tab" id="profile-tab3" data-toggle="tab" aria-expanded="false">Monitor</a> </li> </ul> <div id="myTabContent" class="tab-content"> <div role="tabpanel" class="tab-pane fade active in" id="tab_content1" aria-labelledby="home-tab"> </div> <div role="tabpanel" class="tab-pane fade" id="tab_content3" name="tab_content3" aria-labelledby="profile-tab"> {% include "setting/monitor.html" %} </div> </div> My JavaScript code is: <script> $(document).ready(function(){ switch("{{section}}"){ case 'monitor': $('#myTabContent #tab_content3').tab('show'); break; case 'profile': $('#myTab a[href="#tab_content1"]').click(); break; } }) </script> I have also used the below javascript to activate second tab, but it does not wok. $("#myTab").tabs("select", 2); I appreciate your help. -
How to set an image field in django to an image file on S3?
I have a django model (Page) with an image field (https://github.com/matthewwithanm/django-imagekit), with files stored on S3. I can upload and delete images just fine using boto3, but I'm trying to implement a gallery feature, where the user can select from a series of photos already on S3 and then set the Page's image to the selected photo. It seems that if i do page.picture.save(....), I need to pass the filename and the content for it to upload the file to S3 again, but this seems a bit redundant since the file is already on S3. Is it possible to just point the image field to the relevant src? -
It is not clear how the django date_hierarchy is supposed to work
I have a Django 2.0 model with a datetime field called 'created'. I set the date_hierarchy in the admin to that field. When I display the admin page, the date hierarchy appears as expected - April 2019, May 2019, June 2019. I have three items in the model, each with a created date in April, May, and June. When I click on any one of the dates in the date_hierarchy link, I expect the admin page to change and only show one item, which has the same created date as the month I clicked. However, all three entries are still displayed. Is date_hierarchy not working properly, or is my expectation wrong? Thanks! Mark -
Handling a signal for an M2M relationship with model inheritance in Django
The question title is quite the sentence, but hopefully the code below will clear it up: class Foo(models.Model): ... class AbstractParent(models.Model): foos = models.ManyToManyField( Foo, related_name='%(app_label)s_%(class)s_related' ) def bar(self): ... class Meta: abstract = True class ChildOne(AbstractParent): ... class ChildTwo(AbstractParent): ... Lets say that my app's label is 'myapp'. Basically, the base class of the ChildOne and ChildTwo has a M2M to the class Foo. What I want to do is this: whenever an object of the Foo class is saved, I want to call the bar() method of all the objects of ClassOne and ClassTwo which has a relation to the Foo object through the foos field. To do this, I tried writing a simple signal: from django.db.models.signals import post_save from django.dispatch import receiver @receiver(post_save, sender=Foo) def call_bar_for_all_related_objects_to_foo(sender, instance, **kwargs): # Do the thing At this point, Im kinda lost. How do I query all the children classes of the AbstractParent class and call their bar() methods whenever there is a relation to the instance in the signal? Ideally, I want to query my database only once, and in one query, I want to get all the objects of ChildOne and ChildTwo related to the instance in the signal. … -
Baffling Exception From Django 2.0 Admin Template
This is a weird (for me) debugging issue. I have a Django 2.0 application with three apps - app1, app2, and app3. app1 was working a long time ago, as well as app2 and app3. At this point, I am only using the admin interface for all three apps. I was doing some work in app3 to optimize some code. I completed that and was running some quick tests on app1, and it blows up. I can access the main admin page for all the models in app1, but when I click on the change page I get this error Template error: In template /home/mark/python-projects/memorabilia-JSON/memorabilia/templates/admin/memorabilia/change_form.html, error at line 14 Could not parse the remainder: '>' from ''</table'>' 4 : 5 : {% for fieldset in adminform %} 6 : {% cycle '<table border=0 width=100%>' ' ' %} 7 : {% cycle '<tr>' ' ' %} 8 : {% cycle '<td width =50%’ ‘td width =50%>' ' ' %} 9 : 10 : {% include "admin/includes/fieldset.html" %} 11 : 12 : {% cycle '</td>' '</td>' ' ' %} 13 : {% cycle '</tr>' ' '%} 14 : {% cycle '</table'> ' ' %} 15 : 16 : {% endfor %} 17 … -
Django -- 'data' is not a registered namespace
Im practicing data's CRUDS,and meet some error when I trying to code delete function. in timesheet.html: {% for data in TR %} <tr> <th>{{data.month}}</th> <th>{{data.worktime}}</th> <th>{{data.email}}</th> <th></th> <th><a href="{% url 'data:delete' data.0 %}"><button type="button">刪除</button></a></th> </tr> {% endfor %} in views.py: def delete(request, id): with connection.cursor() as cursor: sqldelete = """ delete from timesheet where idtimesheet = %s """ cursor.execute(sqldelete, (id,)) return redirect("/timesheet") in urls.py urlpatterns = [ path('', views.timesheet, name='timesheet'), # path('index/', views.index, name='index') path('data_db/', views.data_db, name='data_db'), path('delete/<int:idtimesheet>', views.delete, name="delete") ] -
How to reference a template in another app?
I've got a "plans" django app and a "myproject" django app. The directory structure looks like the following: >plans >>templates >>>plans >>>>base.html >myproject >>templates >>>join.html So when the join.html template is rendered, I would like it to extend the base.html from the plans app. Is this possible? If not, what would be better? -
How to show an Excel file in a Django view? [duplicate]
This question already has an answer here: Excel Workbook to html Django/Python 2 answers how can I show an Excel file from a database in an HTML view? I manage to upload the file and host it in uploads /, but I do not know how to display it in a view. -
Django REST framework getstream notifications
I'm trying to follow the getstream docs for django with rest framework. https://github.com/GetStream/stream-django Here is a minimal drf api cloned from the drf tutorial https://github.com/morenoh149/django-rest-framework-getstream I get an error TypeError at /notifications/ Object of type Feed is not JSON serializable when opening /notifications/ in a browser. How do I write an endpoint to show the user's notifications? views.py class NotificationViewSet(viewsets.ViewSet): """ This viewset returns a notifications feed for the logged in user. The feed contains events for when a relevant snippet is created. """ serializer_class = NotificationSerializer def list(self, request): print('notif list', request.user.id) user_id = request.user.id notification_feed = feed_manager.get_notification_feed(user_id) #notifications = notification_feed.get(limit=5)['results'] #serialized_activities = self.serialize_activities(notifications) return Response(notification_feed) serializers.py class ActivitySerializer(serializers.Serializer): id = serializers.UUIDField() foreign_id = serializers.CharField() verb = serializers.CharField() time = serializers.DateTimeField() def __init__(self, *args, **kwargs): object_serializer = kwargs.pop("object_serializer", None) actor_serializer = kwargs.pop("actor_serializer", None) super().__init__(self, *args, **kwargs) if object_serializer: self.fields["object"] = object_serializer() else: self.fields["object"] = serializers.CharField() if actor_serializer: self.fields["actor"] = actor_serializer() else: self.fields["actor"] = serializers.CharField() class AggregatedSerializer(ActivitySerializer): group = serializers.CharField() activities = ActivitySerializer(many=True) class NotificationSerializer(AggregatedSerializer): is_seen = serializers.BooleanField() is_read = serializers.BooleanField() -
I want to copy the value of input and textarea to clipboard
I have a question ^^; I want to copy the input to the clipboard by pressing copy1 I want to copy textarea to clipboard by pressing copy2 Thank you if you let me know how. ============================================== I searched some code for this, but it felt difficult. I applied this code <input type="text" name="" value="{{p.content1}}" size="40"> <button class="btn btn-outline-primary btn-sm myinput" id="copy_code select-this">copy1</button> $("#copy_code").click(function(e){ e.preventDefault(); document.execCommand('copy', false, document.getElementById('select-this').select()); alert("copy is completed") }); ex) https://codepen.io/fabean/pen/GprQJa but error Uncaught TypeError: Cannot read property 'select' of null at HTMLButtonElement.<anonymous> ((index):251) at HTMLButtonElement.dispatch (custom.js:3) at HTMLButtonElement.q.handle (custom.js:3) -
I got this error when I try to create a new user from django admin page:NotImplementedError at /admin/account/myuser/add/
I created a custom user model and admin model and when I try to create a new user from admin,I got this error: NotImplementedError at /admin/account/myuser/add/ This is my models.py class MyUserManager(BaseUserManager): def create_user(self, email, date_of_birth, password=None): if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), date_of_birth=date_of_birth, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, date_of_birth, password): user = self.create_user(email, password=password, date_of_birth=date_of_birth ) user.is_admin = True user.save(using=self._db) return user class MyUser(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) date_of_birth = models.DateField() is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) role= models.CharField(max_length=100) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['date_of_birth'] And my admin.py : from django import forms from django.contrib import admin from django.contrib.auth.models import Group from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.forms import ReadOnlyPasswordHashField from account.models import MyUser class UserCreationForm(forms.ModelForm): """A form for creating new users. Includes all the required fields, plus a repeated password.""" password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) class Meta: model = MyUser fields = ('email', 'date_of_birth') def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return password2 def save(self, commit=True): # Save the provided password in … -
Django Channels or StreamingHttpResponse for my needs?
I am currently working on a project web application using Django. I've prepared scripts (Python) beforehand which work fine but I've run into an issue trying to implement it with Django. I used html-requests sessions to keep the http connection alive during repeated requests. Should I be using Django Channels or StreamHttpResponse for the same effect or something different entirely? Mainly, jQuery with AJAX to call view.function repeatedly until requirement met, but since fetching a url with session.get each time, it's creating a new session so I get the incorrect data back when trying to navigate a page. Searching anything session related with django will give me django sessions results. I've managed to keep arbitrary data using django sessions or updating database, since I couldn't find a way to persist a custom class in between these calls, the only issue now is persisting the http connection. Should I be looking into StreamHttpResponse, Django Channels, or something else entirely? -
How do I pass information from the user that submits a ModelForm to a ManyToMany save?
I'm trying to insert a records into an intersection table from a Django ModelForm utilizing a CreateView but I'm not sure how to access information from the currently logged in user. I've tried request.user but I don't know where to put it in my view or form and each time I get the same error of "null value in column 'school_id' violates not-null constraint." All other values are correct. Can someone teach me the proper way to do this? I'd really appreciate it. I tried to put this in my view but it didn't work: def form_valid(self, form): form.instance.applicant = self.request.user g = Group.objects.get(name='PendingApplicants') g.user_set.add(self.request.user) for program in form.cleaned_data['programs']: pro = tblProgramSchool() pro.application_id = self.object pro.program = program pro.school = self.request.user.mainschool pro.save() return super().form_valid(form) I tried this in my form but it also didn't work: def save(self, commit=True): instance = forms.ModelForm.save(self, False) old_save_m2m = self.save_m2m def save_m2m(): old_save_m2m instance.programs.clear() for program in self.cleaned_data['programs']: instance.programs.add(program = program, school = self.request.user.mainschool) self.save_m2m = save_m2m instance.save() self.save_m2m() return instance I know I'm missing something fundamental but after reading through a bunch of answers and Django documentation I'm feeling lost. models.py class Application(models.Model): id = models.AutoField(primary_key=True) applicant = models.ForeignKey('users.CustomUser', null = False, blank = … -
Restricting a template in Django
I have some parts of my Django project that i want to restrict to users who did not confirm their email address. Here is what i did right now: models.py class account_emailaddress(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) @property def verified(self): return self.verified.filter(verified=True,primary=True).exists() And this is the template: {% block content %} {% if user.profile.verified %} <style> </style> <body> <div> <p>Here goes a bunch of features</p> </div> </body> {% else %} <p> Your email is not confirmed </p> {% endif %} {% endblock %} The problem: At the actual moment, even if the email is confirmed, the site will throw a Not confirmed error, but i don't understand how it keeps happening. Here is how the db is structured: there is a table, called account_emailaddress. There are five rows in this table, the one to check the verification is verified, which will give 0 when the address is not verified and 1 when it is verified. What am i doing wrong? -
How to remove duplicate nested objects Django REST?
How to remove duplicate nested comments Django REST? Serializer recoursive displays comments. In JSON duplicates comments (the third is displayed in two places): How to get rid of it? { "id": 1, "slug": "mp3kit", "publications_date": "2019-03-19T13:49:58Z", "tag": "Tag", "title": "Title", "content_preview": "Content preview", "body": "Body", "image_preview": null, "image_preview_name": "mp3kit", "comments": [ { "name": "First", "body": "First", "date": "2019-06-02T15:09:16.788405Z", "id": "57fd0069-a8ce-484f-afac-4cc609a1b70c", "parent": null, "reply": [ { "name": "Third", "body": "Third", "date": "2019-06-02T15:09:42.512872Z", "id": "0801ef96-796d-477b-8631-b21559527156", "parent": "57fd0069-a8ce-484f-afac-4cc609a1b70c", "reply": [] } ] }, { "name": "Second", "body": "Second", "date": "2019-06-02T15:09:27.209497Z", "id": "5b2f0d25-bcd0-4b19-b05c-e6a5e7de1280", "parent": null, "reply": [] }, { "name": "Third", "body": "Third", "date": "2019-06-02T15:09:42.512872Z", "id": "0801ef96-796d-477b-8631-b21559527156", "parent": "57fd0069-a8ce-484f-afac-4cc609a1b70c", "reply": [] } ] } As I understand you need to put a filter on the field "comment" in ArticleSerializer, to disable output comments with parent? Model: class Article(models.Model): id = models.AutoField(primary_key=True) slug = models.SlugField() publications_date = models.DateTimeField(blank=True, null=True, default=datetime.datetime.now) tag = models.CharField(max_length=100, blank=True, null=True) title = models.CharField(max_length=100, blank=True, null=True) content_preview = models.TextField(blank=True) body = HTMLField(blank=True, null=True) image_preview = models.ImageField(upload_to=upload_to, blank=True) image_preview_name = models.CharField(max_length=100, blank=True, null=True) def __str__(self): return self.title @property def comments_list(self): return self.comments.filter() class Comment(models.Model): id = models.CharField(max_length=100, blank=True, unique=True, default=uuid.uuid4, primary_key=True) date = models.DateTimeField(auto_now=True, auto_now_add=False) name = models.CharField(max_length=100) body = models.TextField(blank=True, null=True) … -
Returns "Value Error" while using cycle for in views function
I am trying to make a URL checker.I meen if a value of slug in url is the same with a value of slug inside class Category, category_displaying returns standart page else ERROR. views object = Category.objects.filter() slug_object = Category() def category_displaying(request, slug): for slug in slug_object.slug: return render(request,'index/index.html', {'object' : object}) else: return HttpResponse('EROR PAGE NOT FOUND') models class Category(models.Model): title = models.CharField(max_length = 15) slug = models.SlugField(default='') def __str__(self): return self.title urls urlpatterns = [ path('', views.displaying, name = "main"), path('<slug>/', views.category_displaying, name = "category"), ] It returns ERROR but when I remove cycle for it works but not such as I want.It displays tamplate with all values of <slug>. -
Django - query filter on manytomany is exists
I have such a model: class News(models.Model): # ... channels = models.ManyToManyField(Channel) # ... What is the most effective way to fetch news related to channels? -
Static & Media files 404 behind NGINX proxy pass
I have what I believe to be a slightly convoluted Django/Gunicorn/NGINX stack that is giving me trouble as I try to migrate it from the django development server to a production setup with Gunicorn and NGINX. Specifically, I'm having trouble serving static files. SYSTEM ARCHITECTURE: I have one physical server with a public IP address. This physical server hosts 3 VM's on a private virtual network (NAT). Each VM run's it's own django project on port 8001. I forward port 8001 on each VM to unique available ports on the physical machine. So, in summary, the architecture looks like the following: PRIVATE VIRTUAL NETWORK VM's: VM1 runs "site 1" on VM1 port 8001 VM2 runs "site 2" on VM2 port 8001 VM3 runs "site 3" on VM3 port 8001 HOST SERVER: Publishes "site 1" on host port 8001 (VM port 8001 fwd.to Host port 8001) Publishes "site 2" on host port 8002 (VM port 8001 fwd.to Host port 8002) Publishes "site 3" on host port 8003 (VM port 8001 fwd.to Host port 8003) This works really well for development with the django development server. I just need to include a port # in the URL. As in: myserver.edu:8001 for site …