Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django unittest - How to disable console logging only
I have a test in django (v2.2) that generates an error on purpose to check that errors are logged in the proper log files. But I get also a print in the console which is kind of annoying, I was looking for a way to hide the message. If I disable logging with logging.disable(logging.CRITICAL), it will not log the error in the files. I also tried to use with self.settings(LOGGING=logging) after removing the console handler from the loggers (see settings below) but it does not seem to be taken into account. Also, setting disable_existing_logger to False does not help. Do you have some ideas how to do that? my settings: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'msg_filter': { '()': MessageFilter, 'strings_to_be_ignored': [ 'Not Found: /favicon.ico' ], } }, 'formatters': { 'verbose': { 'format': '_____________________________________________________________' '\n%(asctime)s - [%(levelname)s|%(name)s] %(message)s\n' }, 'simple': { 'format': '%(asctime)s - [%(levelname)s|%(name)s] %(message).50s' }, }, 'handlers': { 'warning': { 'level': 'WARNING', 'class': 'logging.FileHandler', 'filename': '/some_folder/warning.log', 'formatter': 'verbose', 'filters': ['msg_filter'] }, 'warning_simple': { 'level': 'WARNING', 'class': 'logging.FileHandler', 'filename': '/some_folder/warning.log', 'formatter': 'simple', 'filters': ['msg_filter'] }, 'info': { 'level': 'INFO', 'class': 'logging.handlers.RotatingFileHandler', 'filename': '/some_folder/info.log', 'maxBytes': 1024 * 1024 * 2, 'backupCount': 9, 'formatter': 'simple', 'filters': ['msg_filter'] }, … -
Validate Post data when not using serializer?
I want to access post data directly in DRF (APIView example): def post(self, request, post_uuid, format=None): used_images = request.data['usedImages'] for image in used_images: print(image) return Response('') The used_images are a simple list containing only strings. I am a little hesitant to access the strings directly since it might be a security risk. Is there any way to validate/clean the strings so that they can be securely used to query the database? Thanks! -
Django: Custom LoginView is not authenticating users
I've made a custom LoginView, only to pass some context variables. But now when I do login, users don't login only redirect to page indicated in the urls.py file: from core import views app_name = "core" urlpatterns = [ path('', views.ScolarteHome.as_view(), name='home'), path("ingresar/", views.LoginView.as_view(template_name='scolarte/registration/login.html', success_url=reverse_lazy('core:home')), name="login"), ] My Custom LoginView: class LoginView(SuccessURLAllowedHostsMixin, FormView): """ Display the login form and handle the login action. """ form_class = AuthenticationForm authentication_form = LoginForm template_name = 'registration/login.html' redirect_authenticated_user = True def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) msg = {'cliente': 'Ingresar como cliente', 'vendedor': 'Ingresar como vendedor'} context['msg'] = msg.get(self.request.GET.get('cliente-o-vendedor'), '') return context forms.py from django import forms from django.contrib.auth.forms import AuthenticationForm from django.forms.widgets import PasswordInput, TextInput class LoginForm(AuthenticationForm): username = forms.CharField(widget=TextInput(attrs={'class': 'span2','placeholder': 'Nombre de usuario'})) password = forms.CharField(widget=PasswordInput(attrs={'class': 'span2','placeholder':'Contraseña'})) -
i am trying to add social media buttons on django template (html file), but bootstrap4 seems to be interfering with the social media icons
I am using bootstrap 4 to style my html pages. And i am using font awesome to add social media icons on the webpage too. <!DOCTYPE html> <html lang = 'en'> <head> <meta charset = 'utf-8'> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <title> Page Title </title> <style> body {background-color: lightcyan} .fa { padding: 20px; font-size: 30px; width: 30px; text-align: center; text-decoration: none; margin: 5px 2px; border-radius: 50%; } .fa:hover { opacity: 0.6; } .fa-linkedin { background: #007bb5; color: white; } .fa-youtube { background: #bb0000; color: white; } </style> </head> <body> <div class = 'container'> <div class = 'row'> <div class = 'col text-center'> <a href="#" class="fa fa-linkedin fa-fw"></a> <a href="#" class="fa fa-youtube"></a> </div> </div> </div> </body> </html> But when i import the bootstrap4 library, the social media icons shape distorts. <!DOCTYPE html> <html lang = 'en'> <head> <meta charset = 'utf-8'> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <title> Action Page </title> <style> body {background-color: lightcyan} .fa { padding: 20px; font-size: 30px; width: 30px; text-align: center; text-decoration: none; margin: 5px 2px; border-radius: 50%; } .fa:hover { opacity: 0.6; } .fa-linkedin { background: #007bb5; color: white; } .fa-youtube { background: #bb0000; … -
Django Global Static Files Not Found
I'm trying to create/use a global css file for my project, it seems to be resolving to the correct location, but it's still not finding the file. The relevant section of my settings.py file is: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATICFILES_DIR = [ os.path.join(BASE_DIR, 'static') ] and I have django.contrib.staticfiles in my installed apps. My file structure is: Project/ ├── Project/ │ ├── __init__.py │ ├── settings/ │ ├── urls.py │ └── wsgi.py ├── App/ │ └── static │ └── App │ └── css │ └── test.css │ └── __init__.py │ └── admin.py │ └── apps.py │ └── models.py │ └── views.py │ ├── manage.py │ ├── static/ │ └── base | └── css | └── test.css └── templates/ └── base.html My base.html simply looks like this: {% load static %} <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="{% static 'base/css/global.css' %}"> <title>Title {% block title %}{% endblock %}</title> </head> <body> {% block content %} <h1>Test</h1> {% endblock %} </body> </html> When I try to access the page I get the following error: [08/Feb/2020 11:26:50] "GET /static/base/css/test.css HTTP/1.1" 404 1683 which indicates that it's pointing to the … -
Unable to retrieve data which is stored in sqldatabase
While saving objects in database.while retriving data from the database unable to retrieve the Stored data in database -
Django DateTimeInput Type 'datetime-local' Not Saving To Database
I'm working on a django app to document trades. All the trade documentation is done on one page with an inline formset that shows all the entries and exits for a trade. All work well up to the datetimeinput field. If I remove the 'type' the form works great but is very non-user friendly. Working entries with no 'type' Non-working entries with 'type': 'datetime-local' So I guess you could say there are several issues datetime-local creates, or maybe it's not datetime-local to blame. I've been stuck on it all day and I'm really not sure where the issue comes from: Entry.date value is not populated into field anymore When a new date and time is selected in datetimepicker it doesn't save datetime-local removes the seconds, we need the seconds models.py from django.db.models.functions import datetime class Entry(models.Model): ENTRY = 'entry' EXIT = 'exit' ENTRY_TYPE_CHOICES = [ (ENTRY, 'Entry'), (EXIT, 'Exit'), ] class Meta: verbose_name = "Entry" verbose_name_plural = "Entries" trade = models.ForeignKey(Trade, on_delete=models.CASCADE) date = models.DateTimeField(null=True, blank=True, default=datetime.datetime.now) amount = models.FloatField(null=True) price = models.FloatField(null=True, blank=True) fee = models.FloatField(null=True, blank=True) entry_type = models.CharField(max_length=5, choices=ENTRY_TYPE_CHOICES, default=ENTRY) forms.py class EntriesForm(ModelForm): class Meta: model = Entry exclude = () widgets = { 'date': forms.DateTimeInput(attrs={'type':'datetime-local', 'class':'form-control'}), … -
Django contrib message, not printing the Box label
I am new to Django, I built a little app, I want to display a message when I click a button. The message display correctly to the web app but it only show the text, it doesn't show the color box (GREEN FOR SUCCESS, AND RED FOR ERROR). I searched a lot on the DOCS, and stackoverflow but didn't find a answer. Thanks you for helping views.py from django.shortcuts import render from .forms import ClientInfo from django.contrib import messages def send_sms(request): if request.method == 'POST': form = ClientInfo(request.POST) if form.is_valid(): try: sms = Client.messages.create( from_="+XXXXXXXXXX", body=mess, to=sms_client ) send = sms.sid messages.add_message(request, messages.SUCCESS, 'Succes! Message has been sent!') except: messages.error(request, 'Error! Message has not been sent!') form.html {% load crispy_forms_tags %} <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> {% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}> {% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}{% endif %} {{ message }} </li> {% endfor %} </ul> {% endif %} <form method="post"> {% csrf_token %} {{ form|crispy }} <br> <button type="submit">ENVOYER</button> <br> </form> </body> </html> settings.py """ Django settings … -
How to remove "unable to load configuration from home/user/project_name/file.py" in django website with PythonAnywhere
I have a running web app in PythonAnywhere now but the main problem with it is the fact that I can't seem to get rid of this error from the server log: 2020-02-08 16:04:11 unable to load configuration from /home/user/project_name/file.py Despite the fact that the file.py exists at the location that is specified above it still keeps throwing the error I have already run the file.py in PythonAnywhere via the Bash shell and it worked successfully. It just doesn't seem to be happening like it did when I hosted it in the dev server. This is how I display the output in the views.py def external(request): inp=request.GET['param'] out=run([sys.executable,'/home/user/project_name/file.py',inp],shell=False,stdout=PIPE) out=out.stdout return render(request,'/home/user/templates/main.html',{'data':out}) What is the problem here? -
[Django]How to fill the form field with the data based on drop down selection of another form field using ajax request
I am Django learner. I want to know how to populate the form field with the data based on drop down selection of another form field belongs to same form in below scenario. Lets suppose, we have 2 Models. 1. ModelRegister 2. ModelGSP ModelRegister used to provide the model details.[fields:model_name,model_no,os_name,chipset_type etc]. This model return model_name. ModelGSP to provide the GSP details for a registered model.[fields:registered_model,model_nos_for_reg_model] Let's suppose we have ModelRegister with below data as shown in screen shot below: [![enter image description here][1]][1] [![enter image description here][1]][1] Models.py: ========= class ModelRegister(models.Model): """ This class is used to register the model. """ FLOAT_CHOICES = [[float(x), float(x)] for x in range(1, 21)] model_name = models.CharField(max_length=128, verbose_name="ModelName") model_no = models.CharField(max_length=128, verbose_name="ModelNo") os_name = models.ForeignKey(OSName, on_delete=models.CASCADE, verbose_name="OSName",default=" ") chipset_type = models.ForeignKey(ChipsetType,on_delete=models.CASCADE, verbose_name="chipsetType") class Meta: verbose_name_plural = "ModelRegisteredList" def __str__(self): return self.model_name class ModelGSP(models.Model): """ This class is used to raise Model GSP request. """ registered_model = models.ForeignKey(ModelRegister,on_delete=models.CASCADE, verbose_name="ModelName") model_nos_for_reg_model = models.ManyToManyField(ModelNumber) model_gsp_requester = models.CharField("Model GSP Requester", max_length=128,default=" ") integrator = models.CharField("Integrator", max_length=100,default=" ") class Meta: verbose_name_plural = "ModelGSPRequests" def __str__(self): return self.model_gsp_requester + self.integrator + str(self.pk) model_name = models.CharField(max_length=128, verbose_name="ModelName") model_no = models.CharField(max_length=128, verbose_name="ModelNo") os_name = models.ForeignKey(OSName, on_delete=models.CASCADE, verbose_name="OSName",default=" ") chipset_type = models.ForeignKey(ChipsetType,on_delete=models.CASCADE, verbose_name="chipsetType") … -
Django (Python) : Django form is not Displaying
I am making my way into Python and Django programming. However, I struggle with displaying a simple form. The only element displayed based on the code below is the button, but not (as intended) the entire form. I have already checked the indentation of my code, but have not been able to display the form. models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Story (models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) audio = models.FileField(default='SOME STRING', upload_to='audio_stories') def __str__(self): return self.title def get_absolute_url(self): return reverse('story-detail', kwargs={'pk': self.pk}) forms.py from django import forms from .models import Story class Story_Creation(forms.ModelForm): class Meta: model = Story fields = ['title','content','audio'] views.py from django.shortcuts import render, get_object_or_404, redirect from django.contrib.auth.models import User from .models import Story from .forms import Story_Creation from django.contrib.auth.mixins import ( LoginRequiredMixin, UserPassesTestMixin ) from django.views.generic import ( ListView, DetailView, CreateView, UpdateView, DeleteView ) def Create_Audio_Story(request): if request.method == 'POST': s_form = Story_Creation(request.POST, request.FILES) if s_form.is_valid(): s_form.save() return redirect('suyuh-home') else: s_form = Story_Creation() context = { 's_form': s_form, } return render (request, 'story/home.html', context) story_form.html {% extends "story/base.html" %} {% load crispy_forms_tags %} {% block content … -
Print a project name in jinja template
I have the following models AcsObject class class AcsObjects(models.Model): object_id = models.IntegerField(primary_key=True) object_type = models.ForeignKey('AcsObjectTypes', db_column='object_type') context = models.ForeignKey('self', blank=True, null=True) security_inherit_p = models.BooleanField() creation_user = models.IntegerField(blank=True, null=True) Projects class class ImProjects(models.Model): project = models.ForeignKey('AcsObjects',related_name='project', on_delete=False, primary_key=True) project_name = models.CharField(max_length=1000) project_nr = models.CharField(max_length=100) project_path = models.CharField(max_length=100) TimesheetTasks class class TimesheetTasks(models.Model): task = models.ForeignKey('Projects', related_name='t_task', on_delete=False, primary_key=True) uom = models.ForeignKey('Categories', related_name='u_uom', on_delete=False) planned_units = models.FloatField(blank=True, null=True) billable_units = models.FloatField(blank=True, null=True) I wrote the following code into views.py file. class TimesheetData(TemplateView): template_name = 'timesheet.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["da"] = TimesheetTasks.objects.all() return context I want to print a project_name but it is giving me a task_id ( task_id and project_id are same) using jinja template. -
How does Django handle the incrementation of the AutoField Primary Key?
In a Django project with postgresql, I once inserted en entry in the db, and one day. Someone else who has access to it, has manually added 36 other rows in the db with pgadmin4. When I want to add new row with the Django project, I got IntegrityError obviously, because Django tries to add 1 to the last entry id added by the Django project (This is what I think it is trying to do). Here is the traceback: duplicate key value violates unique constraint "register_catalog_pkey" DETAIL: Key (id)=(2) already exists. How to tell Django that the last entry id is 36 (the last value manually added with pgadmin4)? I also tried to have the id field in Django Admin so I could edit it, but it did not show up. class RegisterAdmin(admin.ModelAdmin) list_display_links = ['id',] list_display = ('id',) Do I need to remove the primary key handled by Django, and define an IntegerField as primary key? register_id = models.AutoField(primary_key=True) to register_id = models.IntegerField(primary_key=True) -
Django: Passing extra variables to LoginView using GET?
I need to pass 2 variables to my LoginView, I'm using Django 3.0. I've a template with 2 buttons, 1 for clients and 1 for sellers. Based on which one is clicked I need to send the typeofuser in the GET call. This is the template that sends the variables in the GET: {% block content %} <h2>Ingresar con tu cuenta</h2> <p class="lead">Selecciona qué tipo de usuario eres</p> <a href="{% url 'core:login' %}?typeofuser=cliente" class="btn btn-primary btn-lg" role="button">Soy un cliente</a> <a href="{% url 'core:login' %}?typeofuser=vendedor" class="btn btn-secondary btn-lg" role="button">Soy un vendedor</a> {% endblock %} My Custom LoginView: class LoginView(SuccessURLAllowedHostsMixin, FormView): """ Display the login form and handle the login action. """ def get_context_data(self, **kwargs): #context = super(LoginView, self).get_context_data(**kwargs) context = super().get_context_data(**kwargs) msg = {'cliente': 'Ingresar como cliente', 'vendedor': 'Ingresar como vendedor'} context['msg'] = msg.get(self.request.GET.get('typeofuser'), '') return context I've also tried this line to get the context: context = super(LoginView, self).get_context_data(**kwargs) But I'm getting: TypeError: 'NoneType' object is not callable Using this to get the context: context = super(LoginView).get_context_data(**kwargs) Returns 'super' object has no attribute 'get_context_data' -
Attach metadata for the json that rest framework returns
I have the model named station and made API according to django rest framework. class Station(models.Model): name = models.CharField(unique=True,max_length=255) def __str__(self): return self.name class StationSerializer(serializers.ModelSerializer): class Meta: model = Station fields = ('id','name') class StationViewSet(viewsets.ModelViewSet): queryset = Station.objects.all() serializer_class = StationSerializer Now, It returns the Json like this correspond to the cols of table. { [ {id: 1,name:"station1"}, {id: 2,name:"station2"} ] } However I want to attach metadata for this Json like this. { meta : {'time':"2020-02-02 00:00:00:",'apiName:"myapi"}, items :[ {id: 1,name:"station1"}, {id: 2,name:"station2"} ] } Is it possible? or how can I make it?? -
How to render a PDF into a HTML page to look a like native pages
How to render a PDF file into a html page which should look like native feel, but not look like embedded. For example: I want the pdf to look and feel like this, where I can custom html css design at the background. What I dont want to look like is given below, -
Django Celery autodiscovery not discovering all apps
I'm using django cookiecutter for my project. When I try to run beat and worker I get this error. Received unregistered task of type 'test_post'. The message has been ignored and discarded. Did you remember to import the module containing this task? Or maybe you're using relative imports? Please see http://docs.celeryq.org/en/latest/internals/protocol.html for more information. I understood that this is due to celery not recognizing all tasks. In fact, if I run celery -A config.celery_app inspect report I get the following: include: ('myapp.users.tasks', 'celery.app.builtins') but the task I'm trying to run is inside myapp.core.tasks My INSTALLED_APPS: LOCAL_APPS = [ "myapp.core.apps.CoreConfig", "myapp.users.apps.UsersConfig", "myapp.dashboard.apps.DashboardConfig", ] I can't understand why it does only discover tasks from users app and not core. The tasks are inside a file called "tasks.py". -
Sharing with generated tokens and magic url in Django with DRF
I am building a file sharing application similar to dropbox with django and vuejs. It was easy to implement the sharing between users for folders but I am struggling to implement it by generating a unique link and access only to that folder. I have tried using django sesame package and it allows for creation of a tokenized url to access a user permitted page but still the folder permissions are managed by owner of them. I am planning to add a list field to a folder model and store generated tokens in that list so only the ones with a matching token in that list will be able to access to that folder. But I am not sure how to apply it. Any help would be appreciated. -
Django need advice storing and tracking the model activity
I want to create a Model that keep tracking every action made by a user in another Model. First thing that i'm thinking is in which database is better to store that type of data and how to store it. Right now I'm using two database in my project first one is MYSQL(SQL) and second is MongoDB(NOSQL)? If I choose MYSQL how is better to store that data? Using JSON Field or for each action to add another row in that table? -
NoReverseMatch but I pass all the parameters
I am building a function to incremente a model when a user click on a link, but even thought I pass all the parameters, I still cannot resolve this issue. Reverse for 'karma' with keyword arguments '{'token': '503e9db5-daf3-4d3a-83fd-0d28bf923225', 'karma_id': ''}' not found. 1 pattern(s) tried: ['workspace/(?P[^/]+)/karma/(?P[^/]+)$'] Here is my views : def karmaget(request, karma_id, token): karma = karma.objects.get(pk=karma_id) karma.point = +1 karma.author = request.user karma.save() return redirect('workspace-detail', token=token) Here is my url : path('<str:token>/karma/<karma_id>', views.karmaget, name='karma'), And my template : <a href="{% url 'karma' token=token karma_id=karma.pk %}"> -
template does not exist in django
I'm using django 2.2 and I'm getting TemplateDoesNotExist at /register/ This is the traceback that I got: Environment:` Request Method: GET Request URL: http://127.0.0.1:2000/register/ Django Version: 2.2.4 Python Version: 3.7.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'post.apps.PostConfig'] Installed 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'] Template loader postmortem Django tried loading these templates, in this order: Using engine django: * django.template.loaders.filesystem.Loader: /home/wss/Desktop/projects/python/django/manascode/part1/django-blog-basic-master/blog/templates/signup.html (Source does not exist) * django.template.loaders.app_directories.Loader: /home/wss/Desktop/projects/python/django/manascode/part1/django-blog-basic-master/.venv/lib/python3.7/site-packages/django/contrib/admin/templates/signup.html (Source does not exist) * django.template.loaders.app_directories.Loader: /home/wss/Desktop/projects/python/django/manascode/part1/django-blog-basic-master/.venv/lib/python3.7/site-packages/django/contrib/auth/templates/signup.html (Source does not exist) * django.template.loaders.app_directories.Loader: /home/wss/Desktop/projects/python/django/manascode/part1/django-blog-basic-master/blog/post/templates/signup.html (Source does not exist) Traceback: File "/home/wss/Desktop/projects/python/django/manascode/part1/django-blog-basic-master/.venv/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/wss/Desktop/projects/python/django/manascode/part1/django-blog-basic-master/.venv/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/home/wss/Desktop/projects/python/django/manascode/part1/django-blog-basic-master/.venv/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/wss/Desktop/projects/python/django/manascode/part1/django-blog-basic-master/blog/blog/views.py" in register 21. return render(request, 'signup.html', {'form': form}) File "/home/wss/Desktop/projects/python/django/manascode/part1/django-blog-basic-master/.venv/lib/python3.7/site-packages/django/shortcuts.py" in render 36. content = loader.render_to_string(template_name, context, request, using=using) File "/home/wss/Desktop/projects/python/django/manascode/part1/django-blog-basic-master/.venv/lib/python3.7/site-packages/django/template/loader.py" in render_to_string 61. template = get_template(template_name, using=using) File "/home/wss/Desktop/projects/python/django/manascode/part1/django-blog-basic-master/.venv/lib/python3.7/site-packages/django/template/loader.py" in get_template 19. raise TemplateDoesNotExist(template_name, chain=chain) Exception Type: TemplateDoesNotExist at /register/ Exception Value: signup.html And this is the structure of project: blog ├── __init__.py ├── __pycache__ │ ├── __init__.cpython-37.pyc │ ├── settings.cpython-37.pyc │ ├── urls.cpython-37.pyc │ ├── views.cpython-37.pyc │ └── wsgi.cpython-37.pyc ├── settings.py ├── templates │ └── signup.html ├── urls.py … -
How to write unittest for function in Django admin?
class SystemUserAdmin(UserAdmin): list_display = ('get_phone',) def get_phone(self, obj): address = obj.cause.address return address.phone if address else '-' get_phone.short_description = 'Phone' additional_admin_site.register(User, SystemUserAdmin) How can to test function get_phone? Do I need to get instance SystemUserAdmin for User instance? -
Django - save methode not working on overwrite
I'm stuggling since days with the following problem: If I overwrite my postcover (new file upload) neither postcover nor postcover_tn gets save. Only the raw upload gets saved as postcover. If I overwrite that raw upload again postcover and postcover_tn are getting regenerated fine. Creating a Post object initali works also fine so that postcover and postcover_tn are generated properly. In the end only generated version of postcover and postcover_tn should be on my filesystem if I create or change a post object. From my point of view this code seems to be right but always results in this strange behaviour signals.py @receiver(models.signals.pre_save, sender=Post) def post_auto_delete_files_on_change(sender, instance, **kwargs): """ Deletes old file from filesystem when corresponding object is updated with new file. """ if not instance.pk: return False try: old_postcover = sender.objects.get(pk=instance.pk).postcover old_postcover_tn = sender.objects.get(pk=instance.pk).postcover_tn except sender.DoesNotExist: return False if not old_postcover: return new_postcover = instance.postcover new_postcover_tn = instance.postcover_tn if not old_postcover == new_postcover: if os.path.isfile(old_postcover.path): os.remove(old_postcover.path) if old_postcover_tn == new_postcover_tn: if os.path.isfile(old_postcover_tn.path): os.remove(old_postcover_tn.path) models.py def save(self, *args, **kwargs): if self.postcover: if not (self.postcover_tn and os.path.exists(self.postcover_tn.path)): image = Image.open(self.postcover) outputIoStream = BytesIO() baseheight = 400 hpercent = baseheight / image.size[1] wsize = int(image.size[0] * hpercent) imageTemproaryResized = image.resize((wsize, baseheight)) imageTemproaryResized.save(outputIoStream, … -
What is the best way to add extra data to query in django graphene?
I am trying to add extra data to query and my solution works fine but I wonder if I am doing this in right way or maybe I don't know something very obvious My solution class LinkType(DjangoObjectType): class Meta: model = Link class MyLink(graphene.ObjectType): qs = graphene.List(LinkType) qs_length = Int() class Query(graphene.ObjectType): mylinks = graphene.Field(MyLink) def resolve_mylinks(self, info, **kwargs): qs = Link.objects.all() return MyLink(qs=qs, qs_length=qs.count()) GraphQL query query{ mylinks{ qsLength qs{ id url } } } -
How to update Django in anaconda?
I am using Ubuntu 18.04.4 LTS. I use anaconda instead of pip. My Django version was 2.2.1. After I run conda install -c anaconda django in terminal, my Django version is now 2.2.5. How can I upgrade/update it to the current version 3.0.3?