Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django login input fields not showing
Im following a tutorial which creates uses the auth app to login etc. For some reason, the input fields arent showing for the username and password (they were showing before). Code is: login.html <h2>Login</h2> <form method="post"> {% csrf_token %} {{form.as_p}} <button type="submit">Login</button> </form> views.py from django.views import generic from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.http import HttpResponse from django.shortcuts import render from django.db.models.query import QuerySet from .models import Subject def index(request): return render(request, 'minerva/lout.html') class ListView(generic.ListView): template_name = 'minerva/list.html' context_object_name = 'all_subjects' def get_queryset(self): return Subject.objects.all() def crew(request): return render(request, 'minerva/crew.html') def profile(request): return render(request, 'minerva/profile.html') def lout(request): return render(request, 'minerva/index.html') def lscreen(request): return render(request, 'minerva/login.html') def login(request): return render(request, 'registration/login.html') urls.py from django.urls import path, include from . import views from django.conf.urls import url app_name = 'minerva'#namespace urlpatterns = [ path(r'', views.index, name='index'), path('list',views.ListView.as_view(), name = 'list'), path('crew',views.crew, name = 'crew'), path('profile',views.profile, name = 'profile'), path('lout',views.lout, name = 'lout'), path('lscreen',views.lscreen, name = 'lscreen'), path('accounts/', include('django.contrib.auth.urls')), path('accounts/login',views.login, name='login'), ] -
Which is better django or nodejs?
I'm really confused about learning django or node.js Many websites say that node.js provide more opportunities nad some say django is more dynamic. Please help me make a decision. -
Django object - field choice
I am building gallery app and I want Django to be able to serve choice of field for one object in the model. I am uploading full picture and thumbnail of the image in my model. I want user to be able to choose between "auto created thumbnail" which would use django-imagekit's field called ImageSpecField or upload their own thumbnail via my own defined field called ResizedImageFieldFile. Full image field would be served by standard ImageField so that ImageSpecField can generate thumbnail from it. For simplicity sake : can that be achieved using same object called thumbnail and form written in a way that there is choice between auto and own thumbnail or I am doomed to use two objects called for ex. thumbnail and thumbnail_auto. Thank you! -
Cross Platform Single Sign On
Want to know some best ways how to achieve Single Sign On for cross platform django projects. I have a monolithic application which is getting converted to Multi Tenant system. The core part of the monolithic application is converted and divided into micro services but there are portions and part of monolithic application which will take time to get converted. So currently I cannot remove monolithic application hence needed a way to implement Single Sign On for these two application running in parallel. Monolithic Stack:- Python, Django1.10, mysql, MultiTenantSystem Stack :- Python, Django2.1, Postgres Some references :- https://github.com/aldryn/django-simple-sso https://medium.com/@MicroPyramid/django-single-sign-on-sso-to-multiple-applications-64637da015f4 -
elastic search model init() raise key error
According to the documentation I've created class with some of my model fields to perform search later. Also I've created conection with default params. But I can't call init() for UserIndex from elasticsearch_dsl import DocType, Text, Boolean, Date, Keyword from elasticsearch_dsl.connections import connections connections.create_connection(hosts=['localhost'], timeout=20) class UserIndex(DocType): pk = Text() phone_number = Text() nickname = Text() name = Text() birth_date = Date() class Meta: index = 'user' After UserIndex.init() command I'm getting an error: File ".../lib/python3.6/site-packages/elasticsearch_dsl/document.py", line 138, in init i.save(using=using) File ".../lib/python3.6/site-packages/elasticsearch_dsl/index.py", line 289, in save current_settings = self.get_settings(using=using)[self._name]['settings']['index'] KeyError: '*' -
Sending warning/error emails, with preset time intervals between them
In Django when I have a critical or non-critical/warning 'error', I send an email to a specified address depending on error. The issue is that sometimes, the staff receives multiple messages with the same error in a short interval of time. I need a mechanism that after sending an error type will not send a new message for the same error in a preset time interval, maybe increasing the time intervals between sending. Also, I need a reset mechanism if the error is not triggered anymore. I prefer something that doesn't involved retaining info in the database. I don't have any code, because I don't have a clear plan to implement it. I thought of using a general variable, maybe a dictionary, and reset it after a time, if no error is trigger, but I don't know how can work with 'spacing' warning emails. -
Django: Writing tests for template tag
I am using django-qr-code to generate QR codes. I wonder how to write a test if the QR code generation works properly. Do you have any tips? <img src="{% qr_url_from_text attendee.ticket_code size='M' %}" alt="Ticket QR code"> -
how can i show just spicific url in barre link with django
i devlop an application to a blog using django The problem is when I open a link to a publication For example, https: // localhost: 8000 / article / 89 / And I want to open another link to a brochure and see this https: // localhost: 8000 / article / 89 / article / 80 / Whenever you click a link, the same thing happens Is there a solution please view.py articles def show_article(request, id): post = get_object_or_404(articles, id=id) add = comment_put.objects.all().filter(user_put = id).order_by('-id') art = articles.objects.get(pk = id) first = articles.objects.order_by('-id')[:1] three = articles.objects.order_by('-id')[:4] is_liked = False if post.likes.filter(id=request.user.id).exists(): is_liked = True context = { 'art': art, 'add': add, 'post': post, 'first': first, 'three': three, 'is_liked': is_liked, 'total_likes': post.total_likes(), } return render(request, 'home/article.html', context) urls.py url(r'article/(?P<id>\d+)/$', views.show_article, name='show_article'), -
Send file as a response not file path. How to Send xlsx file as a response in python
I have read data from mysqldb and write into xlsx file and stored into directory using xlsxwriter. Now i want to send a response as a xlsx file not file path. Can you please anyone help me to do this. cursor.execute(query) filter_data = _cursor.fetchall() workbook = xlsxwriter.Workbook('report.xlsx') worksheet = workbook.add_worksheet() for row, x in enumerate(total_data): for col, y in enumerate(x): worksheet.write(row, col, str(y)) workbook.close() I want to send a response as a xlsx file in python. I tried like below response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="report.xlsx"' return response The above statement i have used. But am getting the following error didn't return an HttpResponse object. It returned None instead. -
How to get past this warning -> RemovedInDjango110Warning: Operator '=' is deprecated and will be removed in Django 1.10. Use '==' instead
I was trying to create a user instance in Django. newuser = User.objects.create(username = username, email = email) and got this warning and stuck here with a user created in the database. project/new_env/lib/python3.6/site-packages/django/template/smartif.py:168: RemovedInDjango110Warning: Operator '=' is deprecated and will be removed in Django 1.10. Use '==' instead. I am using Django 1.9.5 and python3.6.6. -
How to create a custom action endpoint that corresponds to put and executes a function in the model class?
Am using Django Rest Framework: v3.7 and Django v1.11 and Dynamic Rest v1.9.2 I have the following in my MyModel Class: class MyModel(): # .. fields declared here.. def change_status(self): #... other code not crucial allowed = self.status in possible_new_states if allowed: return self.save() return True I have the following ViewSet class MyModelViewSet(DynamicModelViewSet): """ VendorQuotations API. """ permission_classes = (IsAuthenticated,) queryset = MyModel.objects.all() serializer_class = MyModelSerializer @action(detail=True, methods=['put'], name='Change Status', url_path='change-status', url_name='change_status') def status(self, request, pk=None): """Update the status.""" And the following Serializer: class VendorQuotationSerializer(DynamicModelSerializer): The DynamicModelSerializer inherits from serializers.ModelSerializer and the DyanmicModelViewSet inherits from viewsets.ModelViewSet I wanted to have an endpoint like /my_models/:id/change_status to point at the status method in the viewset which in turn somehow execute the change_status method at the model level. I looked at django rest docs and did copy the example for the change_password but I am not sure how to connect the dots between the viewset and the model. Please advise -
How to migrate particular table in django
In model file already some of table migration and added records to that tables. Now, I tried to add a additional tables but its not migrating. class Ranking(object): id=models.AutoField(primary_key=True, unique=True) name= models.TextField() user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) model = models.ForeignKey(DecisionModel, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) How can i makemigration & migrate particular table? Thanks for the solution in advance. -
Django: Should I use LocMemCache caching?
I am using this QR code generator. There is a specific part in the documentation about caching. I read that LocMemCache should not be used in production. Is that also the case for these QR codes? Is there a caching that you can recommend instead, or is that approach fine at the beginning with a smaller page? CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', }, 'qr-code': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'qr-code-cache', 'TIMEOUT': 3600 } } QR_CODE_CACHE_ALIAS = 'qr-code' -
Django refuses to use DB view
I have the following scenario: I have defined the right view in the database, taking care that the view is named according to the django conventions I have made sure that my model is not managed by django The view is working fine by itself. When triggering the API endpoint, two strange things happen: the request to the database fails. I have logging enabled at the postgres level, and copy-pasting the exact same request into a db console client works, without modifications whatsoever. the request to the DB gets retried lots of times (more than 30?). Why is this happening? Is there a django setting to control this? (I am sending the request to the API just once, manually with curl) -
Bound task in celery is not able to access instance variable in django project
I have setup celery in my django project using official documentation at http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html#using-celery-with-django So my MyApp/tasks.py have content from celery import shared_task class Someclass(): def __init__(self, x, y): self.x = x self.y = y @shared_task(bind=True) def func1(self): '''This does not work''' return self.x + self.y @shared_task(bind=True) def func2(self, a, b): '''This works well''' return a + b When I run In [9]: o = Someclass(3, 4) In [10]: o.func1.delay() Out[10]: <AsyncResult: afc6b151-d71c-4f46-a916-6917f98c681f> I get the error AttributeError: 'func1' object has no attribute 'x' When I run In [11]: o.func2.delay(3, 4) Out[11]: <AsyncResult: 3b227f00-8d9c-472b-b7d8-8b4b6261f689> This works perfectly How can I make func1 working so that it can use instance variables e.g. x and y? -
Django: Caching solution
My Django application is running via Heroku and I am now looking into adding caching. I found many different solutions such as MemCachier, Amazon ElastiCache [...]. Can you recommend one or the other? What do you use for caching? -
Django how to save formset with a foreign key?
I have two models employee and child(Enfant) related by a foreignkey, like models.py class Enfant(models.Model) : id_emp = models.ForeignKey(Employee, on_delete=models.CASCADE) id_Enfant=models.IntegerField(blank=True,primary_key=True) views.py form = EmployeeForm(request.POST or None) form_EnfantForm_formset =formset_factory(EnfantForm, formset=EnfantFormSet) if request.method == 'POST' if form.is_valid() : #pdb.set_trace() new_employee=form.save() EnfantForm_formset0 = form_EnfantForm_formset.save(commit=False) EnfantForm_formset0.employee= new_employee EnfantForm_formset0.save() I need to save employee record and enfant records -
In Django app, get File from some specific Folder and save it to Database table
I have a Django app and in one of my function, I want to read some files from the Specific folder and Save it into the Database. I want to save those uploaded files to my MEDIA_ROOT folder only. My Model class look like. class EmailTemplates(models.Model): templates = models.FileField(validators=[validate_file_extension]) def __str__(self): return str(self.templates) I am trying to read some file from some specific folder and save it to the database. fa = open(template_addr + '/mail_html.html', 'w') email_templates_instance=EmailTemplates.objects.create(templates=File(fa)) I want to read the file and then save it to my EmailTemplates table and create uploaded folder in my MEDIA_ROOT. What is going wrong here? If someone can suggest me something then please suggest me. -
Wrong authentication of password
I am working on a form which is like a user login form but without default django's default authorisation. so it takes parameters and check that whether password entered is correct or not . def clean(self): form_data=self.cleaned_data LoginUsername=form_data['Username'] LoginPassword=form_data['Password'] if DiaryUser.objects.filter(Username=LoginUsername): UserCredentials=DiaryUser.objects.filter(Username='LoginUsername') for UserCredential in UserCredentials: if UserCredential.Password !=LoginPassword: raise ValidationError("The Password is not correct ") else: self._errors["Username"]="The User Credentials entered is not present in our database" del form_data['Username'] return form_data But when User enters wrong password it keeps on redirecting to success page. what is wrong with above code snippet. -
Django App installed from Git but not found
I want to install some apps I have developed and are hosted on my own git service but since it appears they have been correctly installed, when I add them to INSTALLED_APPS throws me a ModuleNotFoundError This is my setup file for the app setup( name='my-teams', version='0.1', packages=find_packages(), include_package_data=True, license='GPL', description='Teams app', long_description=README, url='https://<url>/my-teams', author='...', author_email='...', classifiers=[ ... ], install_requires=[requirements], ) This is my settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'my_teams', ] And this is what I've added to my requirements.txt file: -e git+https://<url>/my-teams.git@master#egg=my_teams When I install requirements.txt it seems to be okay: Found existing installation: my-teams 0.1 Uninstalling my-teams-0.1: Successfully uninstalled my-teams-0.1 And it appears when I execute pip freeze -e git+https://<url>/my-teams.git@cfa8cbf84d8d91ce573f33da3156e8f7f241d63a#egg=my_teams Finally, when I run python manage.py runserver it throws me the exception: ModuleNotFoundError: No module named 'my_teams' Could you please tell me what I'm doing wrong or what I'm missing? Thank you! -
Combine models and send to template
I want multiple data to be sent from two different model to a template class UserListView(generic.ListView): model = UserProfile template_name = 'users/users.html' context_object_name = 'users' class UserListView(generic.ListView): model = User template_name = 'users/users.html' context_object_name = 'users' -
Django Rest Framework I can't use Serializer save model of have foreign key
I'm a Django Rest Framework and Django newbie i can use random data to make stages but i can't use serializer to add new stages. My model and serializer class Stage(models.Model): class Meta: db_table = 'stage' stage_id = models.AutoField(primary_key=True) stage_name = models.CharField(max_length=64, null=False) company = models.ForeignKey( Company, db_column='id', on_delete=models.CASCADE, ) class StageSerializer(ModelSerializer): stage_id = IntegerField(read_only=True) class Meta: model = Stage fields = [ 'stage_id', 'stage_name', 'company', ] def update(self, instance, validated_data): pass def create(self, validated_data): # create stages stage = create_stage(**validated_data) return stage view.py class StageListAPIView(APIView): def post(self, request, company_id): data = request.data.copy() company = get_company_by_id(company_id) data['company'] = company.pk serializer = StageSerializer(data=data) if not serializer.is_valid(raise_exception=True): return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) new_data = serializer.validated_data serializer.save(company=company) return Response(new_data, status=HTTP_200_OK) request.data <QueryDict: {'stage_name': ['kAkSdKq9Gt'], 'company': [6]}> i will receive error: TypeError: Object of type Company is not JSON serializable i can't understand it and i don't know how to use serializer to save foreign key. -
Check ValueError before saving form
I’ve got an EventForm for my Event Model and in this event form I add some custom_questions, which have their own model CustomQuestions. I add those questions to my event form like: CustomQuestion.add_fields(self, self.program, instance=kwargs.get('instance'), scope='event') the add_fields function basically creates a small form for those questions. Now when I create or edit my Event, I always call CustomQuestion.save_changes(form, program=self.get_program(), instance=form.instance) in the event_create or event_edit methods. The save_changes has a check that validates the answers for my custom questions like: @staticmethod def save_changes(form, program, instance): (..) if not custom_question.validate_answer(custom_answer_value): raise ValueError("The value of '{}' is not a valid choice for the question '{} (type: {})'.".format(custom_answer_value, custom_question, custom_question.type)) It works fine and I receive a ValueError when they’re wrong, but is it somehow possible to do a check in my event Form for this ValueError and show an error message to the user that something went wrong and NOT save the form? I know I can show an message AFTER the form was saved in my event_create or event_update method, but I don’t want to repeat the code twice and also it only shows the messages after everything was saved. My event form looks like this: class EventForm(forms.ModelForm): (..) def … -
How to create common folder for css and js files in Django?
setting before any change. STATIC_URL = '/static/' here I want to create one static files folder rather than assigning them to each every app by creating there name as directory and then I have to assign. So I want one common folder for all JS and Css which can be reflected in each and every template rather than defining all of them at different places. -
How to create rotation log in Django?
I want to create a logger that will work in the following way: I want to limit the log file size to - X mb, and when the file is full, I want that it to continue putting new logs to end of file, but erasing the older logs from beginning of the file. Is this something possible to achieve? I tried to use RotatingFileHandler but it doesn't seem to work, because the file exceeded the max size. Here is how I configured the handlers section in LOGGING dictionary, in my settigns file: 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': '/home/ubuntu/logs/django.log', }, 'request_file_info': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': '/home/ubuntu/logs/request_configuration.log', 'formatter': 'verbose' }, },