Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Clear Up Lost Websocket Connections When Using Django Channels + NginX
I am using Django channels for websocket connections. When websocket is properly closed from client-side, consumers' disconnect() is called and the connection is cleared up. However, when it is not, disconnect() is never called and the connection remains on the server side. I thought of three ways to solve this issue. 1) Application level: I could make a Django model that tracks each session(websocket connection)'s online status and call it from disconnect(). async def disconnect(self): Online.objects.filter(channel_name=self.channel_name).delete() Since not all connections would be properly closed with disconnect() I should set up a celery task and run it every 60 seconds to see if there are outdated connections in the Online model. The cons of this approach is I have to hit the db quite often to maintain the Online list of channel names. NginX server level: I was not successful to find a solution of this approach. I am currently using just a Django deployment server, so I have not tried out, but I looked up Stackoverflow to prepare the setting. If there is a auto-closing-connection setting for keepalive, I will not need to implement the application-level solution. But I could not find a good answer. What I have found so … -
Adding record of page views and details of change to django_admin_log
We are using LogEntry/django_admin_log and recording additions, changes and deletions made from Django Admin. However we have two issues we need to address: 1.) Changes record only the field that changed. Not the old and new values. We would like to add the specific details of all changes. 2.) We would like to record an action in this log every time a page is viewed on the Django Admin panel. How would it be best to proceed? We are happy to do some work to extend the existing functionality of this, or we are happy to move to a completely new 3rd part module if necessary, or write our own. But would like some guidance from some experts? -
Local django server - login fails with new safari version
I've updated my MacBook to the latest Mojave 10.14.6 version. Since that update I'm not able to login into my locally installed django webserver using Safari anymore. I always get the error message "Invalid CSRF token". With Chrome it's working. -
'User' object has no attribute 'invitations_recived'
I am trying to show the invitations in a web tictactoe game on the player home page. What I get is following error: AttributeError at /player/home/ 'User' object has no attribute 'invitations_recived' Request Method: GET Request URL: http://127.0.0.1:8000/player/home/ Django Version: 2.2.3 Exception Type: AttributeError Exception Value: 'User' object has no attribute 'invitations_recived' Exception Location: E:\PycharmProjects\django-fundamentals\venv\lib\site-packages\django\utils\functional.py in inner, line 257 Python Executable: E:\PycharmProjects\django-fundamentals\venv\Scripts\python.exe Python Version: 3.7.1 Python Path: ['E:\\PycharmProjects\\django-fundamentals\\ticktactoe', 'E:\\PycharmProjects\\django-fundamentals\\venv\\Scripts\\python37.zip', 'C:\\Users\\ja\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs', 'C:\\Users\\ja\\AppData\\Local\\Programs\\Python\\Python37-32\\lib', 'C:\\Users\\ja\\AppData\\Local\\Programs\\Python\\Python37-32', 'E:\\PycharmProjects\\django-fundamentals\\venv', 'E:\\PycharmProjects\\django-fundamentals\\venv\\lib\\site-packages', 'E:\\PycharmProjects\\django-fundamentals\\venv\\lib\\site-packages\\setuptools-39.1.0-py3.7.egg'] I tried double checking the syntax, names and the similiar titled posts: django 'User' object has no attribute 'user' Why am I getting AttributeError: Object has no attribute AttributeError: 'module' object has no attribute 'tests' views.py from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.decorators import login_required from gameplay.models import Game from .models import Invitation from .forms import InvitationForm @login_required def home(request): my_games = Game.obejcts.games_for_user(request.user) active_games = my_games.active() invitations = request.user.invitations_recived.all() return render(request, 'player/home.html', {'games': active_games, 'invitations': invitations}) home.html {% if invitations %} <div class="list-group"> {% for inv in invitations %} <a class="list-group-item" href="{% url 'player_accept_invitation' id=inv.id %}"> {{ inv.from_user.username }} hast invited you to a game </a> {% endfor%} </div> {% else %} <p>You have no invitations</p> {% endif %} I expect to see the … -
Ajax Django file preview
I want to upload a xlsx file through a simple html form and pass some values for a Django function to process. Since I have no knowledge of Ajax or any idea to do the following I am seeking your help. I want to upload the file and pass some values. After I submit the file/values I want a page to load which would have a set of output values as a preview of sorts. I've heard that Ajax is the way but I have no idea. Please help me either write it or give me a step by step guide for it. p.s I have no JS knowledge. <center> <form method="post" enctype="multipart/form-data" action ='File/'> {% csrf_token %}<br><br> Select a file: <input type="file" name="vendorfile"><br> Start: <input type="text" name="start_value" ><br> Dest: <input type="text" name="dest_col" ><br> Num: <input type="text" name="num_col" ><br> Rate: <input type="text" name="rate_col" ><br> <button type="submit" >Preview</button> </form> </center> <!DOCTYPE html> <html lang='en'> <head> <meta charset='UTF-8'/> <meta name='viewport' content='width=device-width, initial-scale=1.0'/> <meta http-equiv='X-UA-Compatible' content='ie=edge'/> <title>Document</title> </head> <body> {% for k,v in _empty %} {% for x,y in v %} {{ k }}::<br> {{ x }}::<br> {{ y }}:: {% endfor %} {% endfor %} </body> </html> url(r'^(?i)File/$', FileView.as_view(), name='File-Page'), url(r'^(?i)xls/$', views.xlsparser, … -
i want to plot data from database dynamically as it is updating every second, i want that that to be shown every second in front end in chart
my query is what is the best process to build dynamic graph from database in django, as database is updaing every second and data should be fetched every second and plotted dynamically to graph. <html> <head> <title></title> <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> </head> <body> <div id="myDiv"></div> <script> var trace1 = { x: [{% for datas in all_data %}{{datas.current}},{% endfor %}], y: [{% for datas in all_data %}{{datas.voltage}},{% endfor %}], type: 'line', }; var data = [trace1]; Plotly.newPlot('myDiv', data, {}, {showSendToCloud: true}); </script> </body> </html> from django.http import HttpResponse from django.shortcuts import render from .models import EmsDb150 class fetch: def __init__(self): pass def database(self): self.all_data = EmsDb150.objects.all() var = {'all_data' : self.all_data} return var def index(request): return render(request, 'login.html') def test(request): ob = fetch() r = ob.database() return render(request, 'test.html', r) def details(request): ob = fetch() r = ob.database() return render(request,'details.html', r) -
Django: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path
I'm a beginner to django and trying to figure out how to incorporate ckeditor into a blog. I'm stuck at the step of copying ckeditor static files into the static root. No matter what fix I try, when I run python manage.py collectstatic, I get the error: ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. I've tried numerous online guides for ckeditor, read the django documentation on static files, and searched for an answer to this issue, but have not been able to find any answer which fixes the error. Here is my current settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = *** # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #My apps 'blogger', 'ckeditor', 'ckeditor_uploader', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'blogs.urls' TEMPLATES = [ { … -
Django importing a value of a Class Object to another Class in the same Model
I am new to DJANGO, And i got stuck with a problem in my models. I tried a lot, but couldnt find a way to get the result. name = models.CharField(max_length=100) img = models.ImageField(upload_to='pics') desc = models.TextField() price = models.IntegerField() offer = models.BooleanField(default = False) from this above Model class I want the same value of 'name' field in the below Model class class Destination_individual(models.Model): # name = models.CharField(max_length=100, default = None) name = img = models.ImageField(upload_to='pics_indiavidual') caption = models.CharField(max_length=100) img2 = models.ImageField(upload_to='pics_indiavidual') caption2 = models.CharField(max_length=100) img3 = models.ImageField(upload_to='pics_indiavidual') caption3 = models.CharField(max_length=100) img4 = models.ImageField(upload_to='pics_indiavidual') caption4 = models.CharField(max_length=100) img5 = models.ImageField(upload_to='pics_indiavidual') caption5 = models.CharField(max_length=100) My first Class (Destination) is migrated to the Server, and I want the Name field value from that database(Destination) to be shown in the Name field of Destination_individual database. Please guide me how to do that. Many Thanks. -
django/wagtail makemigrations does not work once apps move to custom folder
I am new to Django/wagtail project, wants to change the project structure by putting all the apps inside custom apps folder and inside the module-specific (projects) folder as I need to merge 3 different applications. enter image description here here common folder contains apps which are common to all 3 projects I am trying to run makemigrations and migrate which is not giving any out put , I also tried putting init.py and models.py inside common and apps folder to treat as package (which I don't want) ,still no results can someone help me out with my new structure ,am I doing anything wrong ? -
Fetch Request to Django Server CORS blocks only one view
I have a react frontend running on localhost port 8080 and a django backend on port 8000. I build an API that I call through javascript fetch requests. The django backend has cors-headers installed and set to CORS_ORIGIN_ALLOW_ALL=True. The fetch does work for all endpoints in the API, except a new endpoint called metrics I just added. Once I call this view on a GET request I recieve the following error: Access to fetch at 'http://localhost:8000/api/v1/metrics/' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response. I use the same fetch method to call all API endpoints: return fetch(url, { method: 'GET', mode: 'cors', cache: 'no-cache', credentials: 'same-origin', headers: { 'Authorization': 'Token ' + token }, redirect: 'follow', referrer: 'no-referrer', }) Also the call does work through postman, however not from the React-App. I suppose the error is originated in the preflight OPTIONS response the django server gives, however I fail to see how the response is different from other endpoints. The definition of the view is: class ListMetrics(generics.ListCreateAPIView): '''Lists and creates new Metrics.''' queryset = models.Metric.objects.all() serializer_class = serializers.MetricSerializer (Authorization is enabled in the django settings by default … -
redirect reverse with kwarg; pattern not found, but url works
I try to redirect to a url on some condition and get the following error: Error: Reverse for ... url="/nl/payments/mollie/invoice-payment-success/3248db26-fdce-4590-a5b9-9314fe30019c/" not found. ' ... is not a valid view function or pattern name. However when I test the url in address bar it works fine. Here's my redirect: if obj.status == obj.PAID: return HttpResponseRedirect(reverse('payments:success_invoice_payment', kwargs={'uuid': invoice.uuid})) and urls: path('mollie/invoice-payment-success/<uuid>/', SuccessInvoicePayment.as_view(), name="success_invoice_payment" ) Any tips are much appreciated! -
how would I get rid off error 'Manager' object has no attribute 'active'
My search field is not working, I get the error which says "'Manager' object has no attribute 'active'" I have tried to google and solve it but still I can't remove the error views.py def IndexView(request): query_list = Documents.objects.active() if request.user.is_staff or request.user.is_superuser: query_list = Documents.objects.all() query = request.GET.get('q') if query: query_list = query_list.filter(Q(docs_name__icontains=query) | Q(item_type__icontains=query) | Q(Description__icontains=query)).distinct() paginator = Paginator(query_list, 5) page = request.GET.get('page') try: qs = paginator.page(page) except PageNotAnInteger: qs = paginator.page(1) except EmptyPage: qs = paginator.page(paginator.num_pages) title = "Home-Back My Item" return render(request, "loststuffapp/home.html", context={"documents":Documents.objects.all}) home.html <li> <form action="{% url 'loststuffapp:IndexView' %}" method="get"> <input name="q" type="text" placeholder="Search..." value=" {{request.GET.q}}"> </form> </li> -
Find all points in the database within a particular radius in Django
I have a Django model with separate columns of latitude and longitude (not the point field). I want to select all the points in my database within a particular radius from a given point. I tried geo-django but is required me to have a Pointfield. Is there any alternative I can retrieve all points with latitude and longitude as separate columns. Also I have indexed all my data using django-elasticsearch-dsl , so if there is is any method through elasticsearch-dsl would be equally helpful. I tried the method in the following link , but it too required to have a Pointfield . https://gis.stackexchange.com/questions/141533/geodjango-find-all-points-within-radius/177292#177292?newreg=690fabeb672246d98a7d29efa5422042 -
Access data of a model linked through a OneToOneField model on a form
I want a pre-populated form with the details (e.g. first name and surname) about the profile of a logged-in user, so that they can update them. I have a custom user model with first name and surname in it, and then a profile model which is linked to the user model and extends it, containing some extra information. I've defined a constant within the profile model which theoretically should get the user's first name and surname. models.py: class User(AbstractBaseUser): email = models.EmailField(verbose_name="email", unique=True, max_length=255) first_name = models.CharField(max_length=30, blank=True, null=True) surname = models.CharField(max_length=30, blank=True, null=True) [...] objects = UserManager() views.py: @login_required def profile_edit(request): if request.method == 'POST': p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if p_form.is_valid(): p_form.save() messages.success(request, f'Your account has been updated') [...] forms.py: class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ('first_name', 'surname') template.html: {% extends "base.html" %} {% block content %} <div> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ p_form }} <button class="button" type="submit"> User update</button> </form> </div> {% endblock content %} When accessing the template via the browser I expect to see the form already populated with the profile's (i.e. user's) first name and surname. Instead, I get a django.core.exceptions.FieldError: Unknown field(s) (surname, first_name) specified for Profile in … -
Using Kiwi's password reset through the "forgot password" link displays 500 Internal Server Error. Is this an issue with settings at common.py?
Recently I had to change another user's password due to a probable typo. Using the login page's "forgot password" displayed a 500 error. Looking through Kiwi's dashboard, documentation, and github discussions, it was said that users can only change their own passwords. While I have worked around the issue (unable to change password) by using docker exec -it kiwi_web /Kiwi/manage.py changepassword userNameHere , I want to know if the cause for the initial 500 error is due to a settings issue in Kiwi's common.py file or it is something else entirely. Tried https://docs.djangoproject.com/en/2.2/topics/auth/default/ https://kiwitcms.readthedocs.io/en/latest/configuration.html https://github.com/kiwitcms/Kiwi/issues/610 https://docs.djangoproject.com/en/2.0/topics/email/#quick-example EMAIL_BACKEND = 'django_ses.SESBackend' AWS_SES_ACCESS_KEY_ID = 'key' AWS_SES_SECRET_ACCESS_KEY = 'key' EMAIL_HOST = '' EMAIL_PORT = 25 EMAIL_FROM = 'mail' DEFAULT_FROM_EMAIL = 'kiwi@example.com' EMAIL_SUBJECT_PREFIX = '[Kiwi-TCMS] ' Expected to be able to use password reset aimed towards the user's set email address. Actual is the 500 error. New to this btw. Thanks in advance. -
django how to create a sign out link with template?
I have tried this: .sign-out { height: 21px; width: 168px; color: #0854B3; font-family: Averta, serif; font-size: 14px; line-height: 21px; text-align: center; padding-top: 17px; margin-left: 291px; } <html> ... <form method="post" action="{% url logout %}"> {% csrf_token %} <div class="sign-out" type="submit">sign out</div> </form> <html> However the sign out text isn't clickable -- how do I make it so? -
Search in XEditableDatatableView is not working
Search in XEditableDatatableView isn't working properly for the custom fields/Non-field columns. I am trying to search with both the mobile number and email address which are multiple (formset I have used). But in search_fields whatever is there in the end it searches that. If my search_fields is like this search_fields = ['full_name', 'contactnumber__number', 'emailaddress__email_id'] then my search is working for only emailaddress and not for contactnumber and full_name. If I exchange the fields then search works with the last field only. The editable thing is working but search is happening with only one field. models.py from django.db import models from phonenumber_field.modelfields import PhoneNumberField class EnquiryModel(models.Model): full_name = models.CharField(max_length=100) class ContactNumber(models.Model): number = PhoneNumberField() enquiryform = models.ForeignKey(EnquiryModel, on_delete=models.CASCADE, blank=True, null=True) class EmailAddress(models.Model): email_id = models.EmailField(blank=True, null=True) enquiryform = models.ForeignKey(EnquiryModel, on_delete=models.CASCADE, blank=True, null=True) views.py class EnquiryDatatableView(XEditableDatatableView): model = EnquiryModel template_name = 'enquiryform/enquiry_list_datatable.html' class datatable_class(Datatable): candidatename = columns.TextColumn("Name", sources=None, processor='get_full_name') contactnumber = columns.TextColumn("Contact", sources=None, processor='get_contactnumber') emailaddress = columns.TextColumn("Email ID", sources=None, processor='get_emailaddress') def get_full_name(self, instance, *args, **kwargs): return format_html("<a href='/enquiryform/" + str(instance.id) + "' target='_blank' >" + instance.full_name + "</a>") def get_contactnumber(self, instance, *args, **kwargs): cnumber = EnquiryModel.objects.get(id=instance.id) numbers = cnumber.contactnumber_set.all() return "<br>".join([str(a.number) for a in numbers]) def get_emailaddress(self, instance, *args, **kwargs): eforms = … -
Inner join using Django router
I have two models "Users" and "UserHasMachine" which are connected by primary key I wanted to create queryset with fields from both of the tables filtered by a field "machine" field in "UserHasMachine" table I tried to use select_releated but it seems to return just full "User" table without filtering by a field in "UserHasMachine" models.py class User(models.Model): id = models.BigAutoField(primary_key=True) email = models.CharField(unique=True, max_length=128) name = models.CharField(max_length=256, blank=True, null=True) pwd_hash = models.CharField(max_length=128, blank=True, null=True) pwd_salt = models.CharField(max_length=256, blank=True, null=True) is_builtin = models.IntegerField() has_account = models.IntegerField() is_verified = models.IntegerField() is_enabled = models.IntegerField() verifycode = models.CharField(max_length=128, blank=True, null=True) user_creator = models.ForeignKey('self', models.DO_NOTHING) is_deleted = models.IntegerField() deleted_at = models.DateTimeField(blank=True, null=True) created_at = models.DateTimeField(blank=True, null=True, auto_now_add=True) updated_at = models.DateTimeField(blank=True, null=True, auto_now=True) class Meta: managed = False db_table = 'user' class UserHasMachine(models.Model): user = models.ForeignKey(User, models.DO_NOTHING, primary_key=True) machine = models.ForeignKey(Machine, models.DO_NOTHING) role = models.CharField(max_length=5) created_at = models.DateTimeField(blank=True, null=True, auto_now_add=True) updated_at = models.DateTimeField(blank=True, null=True, auto_now=True) class Meta: managed = False db_table = 'user_has_machine' unique_together = (('user', 'machine'),) views.py class UserMachineViewSet(ListRetrieveUpdateModelViewSet): queryset = UserHasMachine.objects.select_related('user') serializer_class = UserMachineSerializer filter_backends = (filters.DjangoFilterBackend, ) filter_fields = ('machine_id', ) permission_classes = (partial(UserInAnyGroup, { 'update': ['admin'], 'partial_update': ['admin'] }),) class UserViewSet(ListRetrieveUpdateModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer filter_backends = (filters.DjangoFilterBackend, ) … -
Pagination calling APIs data again in django
I am working on a project where I have to pass several projects ids to API calls. I am storing that in a list and on that list I am using paginator. But when I access the next page again the whole view gets called and it makes those API calls again instead of taking it from the stored list. for i in rt: t = requests.get('https://wstest2.xtm-intl.com/rest-api/projects/' + str(i['id']), headers=headers,verify=False) tt = t.json() print('yo') targetlist.append(tt) mylist=list(zip(rt,targetlist)) page=request.GET.get('page',1) paginator = Paginator(mylist, 10) pagelist=paginator.get_page(page) context={'pagelist':pagelist} return render(request,'dashboard/home.html',context) -
i am facing trouble in django fyp
What I need to do ,I want to submit my university final year project in Django .I have done my basic with Django and Django-rest-frame..what I need to do next, I also need idea for project any one help me? -
Is it possible to control data displayed on templates of multiple apps from admin?
I have a partial template that I use on multiple apps. You can imagine it like something like a footer that containst contact info. I want to be able to change that contact info from admin but since it is used by multiple apps I would probably have to make a model for this in every app that I have in my project. Is it possible to make something like a global model that would be able to do this? -
Should i annotate types everywhere?
Should i annotate types in my unit tests functions? What also with overridden django methods like save and get or post functions in generic view? -
How to get a token passed to Django allauth Signup
I am using allauth and want a user to be able to invite people via email to sign up to an account. When the new user signs up, I want to set their 'school' field to be the same as the user who invited them. In other words, they are part of the same school and I want to store that info when saving the new user. To achieve this, I have an invite button which sends an email with the original user's school passed as a token, like so: class AddUsers(TemplateView): template_name = 'schools/add-users.html' def get(self, request, *args, **kwargs): add_user_form = AddUserForm() context = { 'add_user_form': add_user_form } return render(request, self.template_name, context) def post(self, request, *args, **kwargs): if 'add_users' in request.POST: add_user_form = AddUserForm(request.POST) if add_user_form.is_valid(): to_email_address = add_user_form.cleaned_data.get('email_field') user = request.user school = request.user.school mail_subject = 'Invitation to create an account' url = request.build_absolute_uri(reverse('account_signup')) uid = urlsafe_base64_encode(force_bytes(school.pk)) token = account_activation_token.make_token(school) activation_link = "{0}?uid={1}&token{2}".format(url, uid, token) message = 'Hi,\n\nYour colleague ' + user.first_name + ' has invited you to sign up.\n\n' message += 'Click the activation link below\n\n' message += activation_link email = EmailMessage(mail_subject, message, to=[to_email_address]) email.send() return HttpResponseRedirect(reverse('schools:add-users',)) return HttpResponseRedirect(reverse('settings', )) I override the allauth Signup form like … -
How can I display all my existing records in Mysql from Django database?
I migrated the Django database model to MySQL. When I tried to access the data in MySQL, I can't seem to find my existing data. How can I fix this? Migration code: settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'sample', 'USER': '********', "PASSWORD": '********', 'HOST': '*****', 'PORT': '*****', 'OPTIONS': { 'sql_mode': 'traditional', } } } models.py from django.db import models import os from PIL import Image from datetime import date import datetime from .validators import validate_file_extension import base64 from django.utils.functional import cached_property from django.utils.html import format_html def get_directory_path(instance, filename): today = date.today() t = datetime.datetime.now() day, month, year = today.day, today.month, today.year hour, minutes, seconds = t.hour, t.minute, t.second filename = str(day) + str(month) + str(year) + str(hour) + str(minutes) + str(seconds) + '.png' dir = 'media' path = '{0}/{1}'.format(dir, filename) return path class Image(models.Model): image = models.FileField(upload_to = get_directory_path, null = True , validators=[validate_file_extension]) created_date = models.DateTimeField(auto_now = True) def __str__(self): return str(self.id) After this, I typed: python manage.py makemigrations python manage.py migrate Everything seems to work well but I'm not able to view my data. Any suggestions? -
How to show execution percentage on html template in django at realtime
How can I show the no of loop executed at the backend on html page? or a progress bar of the loop execution.