Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error connecting Django 3.0.6 and Mysql with mysql-connector 2.2.9
I am trying to connect Django and MySQL, but I am getting the error below Error Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/amitgupta/env1/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 16, in <module> import MySQLdb as Database ModuleNotFoundError: No module named 'MySQLdb' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Users/amitgupta/env1/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/amitgupta/env1/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/Users/amitgupta/env1/lib/python3.7/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/Users/amitgupta/env1/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/Users/amitgupta/env1/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/amitgupta/env1/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/amitgupta/env1/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/Users/amitgupta/env1/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/amitgupta/env1/lib/python3.7/site-packages/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, … -
How to test if it is a list or a value in a Django template?
In a template in Django I am importing a list of dicts and in one of the keys (tested) I can have either a single value or a list of values depending on the case. My context dict in the template looks something like this: context_dicts.append({'url': p.url, 'type_': p.type, 'error': error, 'tested': p.tested}) In the html template I want to if test the tested key to do something if it is a single value and something else if it's a list. So when looping through the dicts, if I use {% if value|length > 1% } it will give me the string size of the value when it's just a value and the length of the list when it's a list. How can I test the if to tell me if it's a "list of one value" or more? -
how to find issue in Django TemplateDoesNotExist - basic code
I cannot find issue that causing TemplateDoesNotExist. urls in main project folder from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('quality.urls')) ] urls in quality app from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', view.index, name='index') ] and views from django.shortcuts import render def index(request): return render(request, 'index.html') -
Django - ImportError: cannot import name Attribute
Hello guys I've been developing a project with django in which I'm having this error. File "/home/naqi/Documents/projects/revolution-master-v2/revolution-master/calculation_engine/models.py", line 3, in <module> from asset_herarchi.models import Attribute ImportError: cannot import name 'Attribute' I've got two apps: asset_herarchi calculation_engine code for asset_herarchi/models.py : from djongo import models import uuid from django.core.exceptions import ValidationError from calculation_engine.models import AttributeCalculationConfiguration class Attribute(models.Model): DATA_TYPE_CHOICES = (("Double", "Double"), ("String", "String"), ("Boolean", "Boolean"), ("Float", "Float")) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=100, blank=False, null=False) description = models.CharField(max_length=500, blank=True, null=True) dataType = models.CharField(choices=DATA_TYPE_CHOICES, null=False, blank=False, default="Double", max_length=20) loggingFlag = models.BooleanField(default=False) calculatedAttribute = models.BooleanField(default=False) def __str__(self): return self.name def clean(self): if self.calculatedAttribute: try: print(self.attribute_calculation_configuration) except(KeyError, AttributeCalculationConfiguration.DoesNotExist): print("doesnot exist") code for calculation_engine/models.py: from djongo import models import uuid from asset_herarchi.models import Attribute # Create your models here. class AttributeCalculationConfiguration(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) variables = models.ManyToManyField(Attribute, related_name="as_calculation_variable", null=False, blank=False) expression = models.CharField(max_length=250, null=False, blank=False) attribute = models.OneToOneField(Attribute, on_delete=models.CASCADE, related_name="attribute_calculation_configuration") The problem is when I remove the import inside asset_herarchi/models.py that is "from calculation_engine.models import AttributeCalculationConfiguration" the error goes away but I need the import inside asset_herarchi/models.py to perform a custom validation when saving a new object of Attribute. Can anyone help? -
Django, how to group models by date?
Lets say that I have MyModel that has created_at and name fields. created_at is DateTime. Lets say that I have models with that kind of values: <id: 1, name: A, created_at: 04.06.2020T17:49> <id: 2, name: B, created_at: 04.06.2020T18:49> <id: 3, name: C, created_at: 05.06.2020T20:00> <id: 4, name: D, created_at: 06.06.2020T19:20> <id: 5, name: E, created_at: 06.06.2020T13:29> <id: 6, name: F, created_at: 06.06.2020T12:55> I want to make query that will return to me these models in this order: [ 04.06.2020: [<id: 1, name: A, created_at: 04.06.2020T17:49>, <id: 2, name: B, created_at: 04.06.2020T18:49>], 05.06.2020: [<id: 3, name: C, created_at: 05.06.2020T20:00>] 06.06.2020: [<id: 4, name: D, created_at: 06.06.2020T19:20>, <id: 5, name: E, created_at: 06.06.2020T13:29>, <id: 6, name: F, created_at: 06.06.2020T12:55>] ] I want to group all models by created_at field, but only using Date part of DateTime field. I know that I can make that kind of result just by using python loops, but are there any Django ORM way to solve this problem? -
Does cutting down code to different files cost more ressources and reduce performance?
I'm developing a Flask app, I got concerned about splitting out a python script to several files where they going to have repeated imports because of that. My current directory tree: ├───MyApp │ ├───routes.py │ └───app.py │ └───models.py │ └───forms.py routes.py import simplejson as json from flask import Blueprint, render_template, url_for, redirect, request, session, jsonify from flask_login import login_user, logout_user, current_user, login_required from forms import LoginForm from models import User users_blueprint = Blueprint( 'users_blueprint', __name__, static_folder='templates' ) posts_blueprint = Blueprint( 'posts_blueprint', __name__, static_folder='templates' ) # Function to get user details... @users_blueprint.route('/api/users/get', methods=['GET']): @login_required def get_users(): response = {} args = request.args # ... # Ban user, admin only can use. @users_blueprint.route('/api/users/ban', methods=['POST']) @login_required def ban_user(): # checks then ban given id # ... # ... # Function to get posts details given id or without id... @posts_blueprint.route('/api/posts/get', methods=['GET']): # ... # ... My desired directory tree: ├───MyApp │ ├───routes │ │ └───api │ │ └───users.py │ │ └───posts.py │ └───app.py │ └───models.py │ └───forms.py routes.api.users import simplejson as json from flask import Blueprint, render_template, url_for, redirect, request, session, jsonify from flask_login import login_user, logout_user, current_user, login_required from forms import LoginForm from models import User users_blueprint = Blueprint( 'users_blueprint', __name__, static_folder='templates' … -
Adding A Section To Admin Page
Ive changed certain parts of my admin page and played around extending the templates (so I have the file structure set up and working). I now want to go a bit further. I want to add a column next to the 'recent activity' column on the admin page which would list all the most recent django-notifications the admin has received. I am guessing I'd extend the base.html and add my notifications there. My first question is is this the best place to do this? The next, bigger thing is that I would need to modify the original views.py file to do this. Surely this isnt a good idea? Poking around in the Django Admin views.py sounds like a terrible idea and makes me think that this kind of thing shouldnt be done, however id still like to know for sure before I give up on it. I can find information on adding views to Django Admin, but nothing on adding content like this to the admin front page. Thank you. -
How to pass in variable into Django Form?
I've been reading lots of questions like this on stackoverflow but none seem to work. All I want to do is make a filtered form dropdown. I'm not sure how do go about doing it. I get the error that main is not defined... but I'm sure that's because it's not initialized or something? I'm very confused lol. My form code looks like this: class AssignForm(ModelForm): class Meta(): model = Address fields = ['overseer','publisher', 'status'] def __init__(self, *args, **kwargs,): super(AssignForm, self).__init__(*args, **kwargs) self.fields['publisher'].queryset = Publisher.objects.filter(service_group=main) Here is my View: def assignment(request, pk_a): assign = Address.objects.get(id=pk_a) num = request.user.overseer.publisher_set.first() main = num.service_group.id print(main) I would like to use the variable: main inside my form dropdown so I can limit the dropdown relative to the overseer. How can this be accomplished? Thanks! form = AssignForm(main, request.POST, instance=assign) context = {'form':form,} return render(request, 'sms/assign.html', context ) -
Storing and rewriting a constant variable (session key) in Django
Need advice. I have a program that sends a request for getting data to an external service. In order to receive data from this service, I must have a session key that is valid for 24 hours. A prerequisite for this service is to receive the key once a day. I created a constant in settings.py for key storage AUTHENTICATION_KEY = "" I created a task that makes a request for a key clock.py from apscheduler.schedulers.blocking import BlockingScheduler import os from django.conf import settings from clients.authentication import get_session_id # session key request function sched = BlockingScheduler() os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_project.settings') @sched.scheduled_job('cron', hour=0, minute=0, timezone='Europe/Kiev') def sess_id(): settings.AUTHENTICATION_KEY = get_session_id() return settings.AUTHENTICATION_KEY sched.start() Then I execute this program on Heroku. Of course, at first I performed this task at intervals and checked that the request for the key was successful, but when I call this key in another part of the program (where the request for data is received, session key comes with a request), the key variable (settings.AUTHENTICATION_KEY) is empty. As I understand it, rewriting a constant variable does not occur? Any suggestions on how to rewrite this variable globally? Perhaps there are other options how to get the key once a … -
Checked rows are not being deleted from HTML table/ Database (Django)
I created an html table in a django template <form action="/delete_team/" method="POST" > {% csrf_token %} <input type="submit" name = "delete" class="btn btn-danger float-right" value="Delete"> <table> <thead> <tr> <th><input type="checkbox" class="checkAll" name="checkAll"></th> <th>Team ID</th> <th>Male</th> <th>Female</th> <th>Officer</th> <th>Deadline</th> </tr> </thead> <tbody> {% for team in teams %} <tr> <td><input type="checkbox" name="check" class="case"></td> <td>{{ team.team_id}}</td> <td>{{ team.male }}</td> <td>{{ team.female }}</td> <td>{{ team.officer }}</td> <td>{{ team.date }}</td> </tr> {% endfor %} </tbody> </table> </form> here is the code that i wrote in my views.py: def delete_team(request): if request.method == "POST": pkm = request.POST.getlist("check") selected_objects = mtch_tbl.objects.filter(team_id__in=pkm) selected_objects.delete() return HttpResponseRedirect("/main/") now when i check a row and click delete nothing happens...i only get returned to my page again with the same data. Kindly point out my mistake, i can't figure out how to write the views -
Django shell_plus: How to access Jupyter notebook in Docker Container
I am trying to access a Jupyter Notebook created with the shell_plus command from django-extensions in a Docker container. docker-compose -f local.yml run --rm django python manage.py shell_plus --notebook My configuration is based on the answers of @RobM and @Mark Chackerian to this Stack Overflow question. I.e. I installed and configured a custom kernel and my Django apps config file has the constant NOTEBOOK_ARGUMENTS set to: NOTEBOOK_ARGUMENTS = [ '--ip', '0.0.0.0', '--port', '8888', '--allow-root', '--no-browser', ] I can see the container starting successfully in the logs: [I 12:58:54.877 NotebookApp] The Jupyter Notebook is running at: [I 12:58:54.877 NotebookApp] http://10d56bab37fc:8888/?token=b2678617ff4dcac7245d236b6302e57ba83a71cb6ea558c6 [I 12:58:54.877 NotebookApp] or http://127.0.0.1:8888/?token=b2678617ff4dcac7245d236b6302e57ba83a71cb6ea558c6 But I can't open the url. I have forwarded the port 8888 in my docker-compose, tried to use localhost instead of 127.0.0.1 and also tried to use the containers IP w/o success. It feels like I am missing the obvious here … Any help is appreciated. -
How to access the model class object in form_valid in django's create view?
the below code is for my model: class Book(models.Model): name = models.CharField(max_length=50) picture = models.ImageField() author = models.CharField(max_length=30, default="Anonymous") email = models.EmailField(blank=True) describe = models.TextField(default="Good Book") user = models.ForeignKey(User, on_delete=models.CASCADE,null=True) def __str__(self): return self.name the below is my form: class BookCreate(ModelForm): class Meta: model = Book exclude = ('user',) the below is my Create View here's the problem: i want to access the modal object , that's why i did the self.modal object but it seems to be giving none . Isn't that's how you access it ? How can i access it? class Upload(CreateView): model = Book form_class = BookCreate template_name = "libraryapp/upload_form.html" success_url = reverse_lazy('libraryapp:index') def form_valid(self, form): print("The model object =",self.object) return super().form_valid(form) -
djongo, cannot connet to server on mongodb.com
i think below setting will work for the djongo to connect to the remote mongodb on mongodb.com but, the error message shows its still trying to connect to the localhost DATABASES = { 'default': { 'ENGINE': 'djongo', 'HOST': 'mongodb+srv://<username>:<password>@cluster-name/<dbname>?retryWrites=true&w=majority', } below is the error traceback Traceback (most recent call last): File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check_migrations() File "venv/lib/python3.6/site-packages/django/core/management/base.py", line 453, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "venv/lib/python3.6/site-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "venv/lib/python3.6/site-packages/django/db/migrations/loader.py", line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File "venv/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 73, in applied_migrations if self.has_table(): File "venv/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 56, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "venv/lib/python3.6/site-packages/django/db/backends/base/introspection.py", line 48, in table_names return get_names(cursor) File "venv/lib/python3.6/site-packages/django/db/backends/base/introspection.py", line 43, in get_names return sorted(ti.name for ti in self.get_table_list(cursor) File "venv/lib/python3.6/site-packages/djongo/introspection.py", line 47, in get_table_list for c in cursor.db_conn.list_collection_names() File "venv/lib/python3.6/site-packages/pymongo/database.py", line 856, in list_collection_names for result in self.list_collections(session=session, **kwargs)] File "venv/lib/python3.6/site-packages/pymongo/database.py", line 819, in list_collections _cmd, read_pref, session) File "venv/lib/python3.6/site-packages/pymongo/mongo_client.py", line 1454, in _retryable_read read_pref, session, address=address) File "venv/lib/python3.6/site-packages/pymongo/mongo_client.py", line 1253, in _select_server server = topology.select_server(server_selector) … -
django-heroku and psycopg2 installed but shows "import django_heroku ModuleNotFoundError: No module named 'django_heroku'"
Firstly i installed psycopg2 then django_heroku. setting.py import django_heroku import os --- --- django_heroku.settings(locals()) Here are my requirements which are installed in virtual environments. requirements.txt asgiref==3.2.7 certifi==2020.4.5.1 chardet==3.0.4 dj-database-url==0.5.0 Django==3.0.5 django-contrib-comments==1.9.2 django-heroku==0.3.1 gunicorn==20.0.4 idna==2.9 psycopg2==2.7.5 pytz==2020.1 requests==2.23.0 six==1.15.0 sqlparse==0.3.1 urllib3==1.25.9 whitenoise==5.1.0 After pushing in heroku master it shows. Activity Log File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/tmp/build_e4e9cada1e303d2ab0fdd618bffc8af4/covid19/covid19/settings.py", line 13, in <module> import django_heroku ModuleNotFoundError: No module named 'django_heroku' ! Error while running '$ python covid19/manage.py collectstatic --noinput'. See traceback above for details. You may need to update application code to resolve this error. Or, you can disable collectstatic for this application: $ heroku config:set DISABLE_COLLECTSTATIC=1 https://devcenter.heroku.com/articles/django-assets ! Push rejected, failed to compile Python app. ! Push failed Other Problem arrives here that, "ModuleNotFoundError: No module named 'covid19.wsgi'". But I used it in my Procfile. Procfile web: gunicorn covid19.wsgi -
Why is button not toggling
i am working on a website where users can send friend request, accept request and cancel request. I have a problem on button toggling, when a user send me a friend request the botton on my side displays 'follow back', when i click on the 'follow back' button the button supposed to change to 'following', but it does not. I will attached an image to make my question a bit more specific. Note: Both images are from different template and views, the first image is where the problem is at. As you can see in my first image, the button still remain on FOLLOW BACK when it is clicked, when clicked the button should change to FOLLOWING but it not. What am i missing in my code? Model: class FriendRequest(models.Model): to_user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, related_name='to_user') from_user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, related_name='from_user') date = models.DateTimeField(auto_now_add=True, null= True) class Meta: verbose_name = 'Friend request' verbose_name_plural = 'Friend requests' ordering = ['-date'] def __str__(self): return "from {}, to {}".format(self.from_user.username, self.to_user.username) Views.py: @login_required def following_view(request, username): p = FriendRequest.objects.filter(from_user__username=username).exclude( Q(from_user__profile__friends__blocked_by__user__username=username)| Q(from_user__profile__blocked_users__user=request.user)| Q(to_user__profile__blocked_users__user=request.user)) all_profile_users = [] button_status_list = [] for user_obj in p: u = user_obj.to_user all_profile_users.append(u) friends = Profile.objects.filter(user=request.user, friends__id=user_obj.id).exists() button_status = 'none' if not friends: button_status … -
Django upload file mechanism
I'm trying to upload files use a different FileStorage system other than the default provided by Django. But i need to understand which protocol does django follow while uploading files using FileField. From request to saving files to the file system. -
Using Django Rest Framework how to generate PDF files from Html Template
I have a template HTML file, that I will populate with data from a model. I need an endpoint to : Create those pdf, I'll be looping on each model and apply the generate pdf function. download single pdf ( detail view ) download bulk ( all pdf ) views.py class GeneratePdf(View): def get(self, request, *args, **kwargs): data = { 'today': datetime.date.today(), } pdf = render_to_pdf('pdf/report.html', data) return HttpResponse(pdf, content_type='application/pdf') urls.py router.register('pdf', GeneratePdf.as_view, basename='pdf' error : AttributeError: 'function' object has no attribute 'get_extra_actions' Question : Why do I get this error? is this the right way to do it? Thanks ! -
javascript pop up form with django inlineformset
i want to submit child form with javascript pop up ,if number_of_cars = 3 it will pop up a form with 3 input fields for Car car_name , i have dont it from front end , but i dont know to add them to the pop up form class Car(models.Model): car_name = models.CharField(max_length=20,unique=True) owner = models.ForeignKey(Creator,on_delete=models.CASCADE) class Creator(models.Model): owner = models.CharField(max_length=15,unique=True) number_of_cars = models.IntegerField(default=1) forms.py class CarForm(ModelForm): class Meta: model = Car fields = ['car_name'] class Creator(ModelForm): class Meta: model = Creator fields = '__all__' InlineformsetCarNames = inlineformset_factory = (Creator,Car,form=CarForm,extra=1) and this is my views.py inside CreatView def get_context_data(self,*args,**kwargs): context = super(CreateCarView,self).get_context_data(*args,**kwargs) if self.request.POST: context['car_name'] = InlineformsetCarNames(self.request.POST) else: context['car_name'] = InlineformsetCarNames() return context def form_valid(self,form): context = self.get_context_data() context = context['car_name'] with transaction.atomic(): self.object = form.save() if context.is_valid(): context.instance = self.object context.save() return super(CreateCarView,self).form_valid(form) and this my template <form method="POST">{% csrf_token %} <div class=" col-12 "> <div class="col-12 col-sm-9 col-md-12 divColor mt-2 mx-auto row " > <div class=" col-12 col-sm-9 mx-auto row p-0"> <div class="col-12 col-md-6 p-0 mx-auto text-center"> <br> {{form.owner | add_class:'form-control col-12 col-sm-10 mx-auto'}} {{form.number_of_cars | add_class:'form-control col-12 col-sm-10 mx-auto' | attr:'id:qua'}} <input type="button" class="btn btn-light col-12 col-sm-10 mx-auto" name="" id="CARBTN" value="CAR" data-target="#CAR" data-toggle="modal"> </div> </div> <button class="col-4 … -
Django detail view test model gives AssertionError: 404 != 200 in django test, but works fine in the browser
I am new to Django and test-driven approach, I am trying below shown test.py file but it gives Assertion Error. But code runs fine on web browser chrome. My backend is PostgreSQL. Whats is the problem with my code. Test.Py from django.contrib.auth import get_user_model from django.test import TestCase from django.urls import reverse from .models import Post from django.test import Client class BlogTests(TestCase): def setUp(self): self.client = Client() self.user = get_user_model().objects.create_user( username='testuser', email='test@email.com', password='secret' ) self.post = Post.objects.create( title='A good title', body='Nice body content', author=self.user, ) def test_post_detail_view(self): response = self.client.get('/post/1/') no_response = self.client.get('/post/100000/') self.assertEqual(response.status_code, 200) self.assertEqual(no_response.status_code, 404) self.assertContains(response, 'A good title') self.assertTemplateUsed(response, 'post_detail.html') I am receiving this error on shell : AssertionError: Creating test database for alias 'default'... System check identified no issues (0 silenced). .F.. ====================================================================== FAIL: test_post_detail_view (blog.tests.BlogTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "D:\\tests.py", line 50, in test_post_detail_view self.assertEqual(response.status_code, 200) AssertionError: 404 != 200 ---------------------------------------------------------------------- Ran 4 tests in 0.894s FAILED (failures=1) Destroying test database for alias 'default'... Below shown is my views.py file : views.py from django.views.generic import ListView, DetailView from .models import Post class BlogListView(ListView): model = Post template_name = 'home.html' class BlogDetailView(DetailView): model = Post template_name = 'post_detail.html' And this si the urls.py … -
What are the default namespaces for django authentication URLs?
I changed my app's urls.py to have a namespace app_name = 'somename'. And then did these, Changed reverse('url-name') to reverse('somename:url-name'). Changed {% url 'url-name' %} to {% url 'somename:url-name' %}. Changed a {% if request.resolver_match.url_name == "url-name" %} to {% if request.resolver_match.url_name == "somename:url-name" %}. For accounts app, I only have two custom views for login and signup. So a reverse like reverse('accounts:login') is working but reverse('accounts:password_reset') (part of default django auth) is not working. Here is what I tried, Replaced reverse('accounts:password_reset') with reverse('auth:password_reset'). Replaced reverse('accounts:password_reset') with reverse('password_reset'). Solution 1 did not work. Solution 2 is working. I also tried changing path('accounts/', include('django.contrib.auth.urls')) in my project's urls.py to path('accounts/', include('django.contrib.auth.urls', namespace='auth')) and path('accounts/', include('django.contrib.auth.urls, namespace='accounts')). Neither worked. project/urls.py urlpatterns = [ path('', include('core.urls')), path('admin/', admin.site.urls), path('accounts/', include('accounts.urls')), path('accounts/', include('django.contrib.auth.urls')), path('books/', include('library.urls')) ] accounts/urls.py app_name = 'accounts' urlpatterns = [ path('signup/', views.CustomSignup.as_view(), name='signup'), path('login/', views.CustomLogin.as_view(), name='login'), ] Why namespacing password_reset with accounts and auth fail? Is there a documentation page that has default namespaces that can be used? -
Uploading Images from Ckeditor to Google Drive
I am using Django Google Drive Storage from this repo to store and serve my media files in Django. I am using this because i want to deploy it on Heroku but don't have a credit card for Amazon S3 account. I did the setup exactly as they said in the documentation. The images I upload through ImageField models are working fine but those I send through Django-Ckeditor are not getting sent. I am using a Ckeditor RichTextUploadingField to store the images in a uploads folder. This is my settings.py file with the necessary configuration This is the traceback of the error produced [04/Jun/2020 15:28:10] "POST /ckeditor/upload/ HTTP/1.1" 200 156 Internal Server Error: /media/uploads/2020/06/04/opera-snapshot_2020-06-04_151851_127001.png Traceback (most recent call last): File "C:\Users\Lenovo\.conda\envs\tensor\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Lenovo\.conda\envs\tensor\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Lenovo\.conda\envs\tensor\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Lenovo\.conda\envs\tensor\lib\site-packages\django\views\static.py", line 37, in serve if fullpath.is_dir(): File "C:\Users\Lenovo\.conda\envs\tensor\lib\pathlib.py", line 1348, in is_dir return S_ISDIR(self.stat().st_mode) File "C:\Users\Lenovo\.conda\envs\tensor\lib\pathlib.py", line 1158, in stat return self._accessor.stat(self) File "C:\Users\Lenovo\.conda\envs\tensor\lib\pathlib.py", line 387, in wrapped return strfunc(str(pathobj), *args) OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'C:\\Users\\Lenovo\\PycharmProjects\\LeafyAI(GDrive)\\https:\\drive.google.com\\drive\\folders\\1spvHiP6Im3xiMvrGGoVqO2o8IRC8caed\\uploads\\2020\\06\\04\\opera-snapshot_2020-06-04_151851_127001.png' [04/Jun/2020 15:28:10] "GET /media/uploads/2020/06/04/opera-snapshot_2020-06-04_151851_127001.png … -
How do I tell python to use a variable with the name of the value of another variable?
In my code I define multiple variables with names that are equal to the value I get when calling field.name, so I though that I could pass them in with this for loop: if formReminders.is_valid(): needsImprovement = formReminders.cleaned_data["needsImprovement"] hasFallacies = formReminders.cleaned_data["hasFallacies"] hasEmotionalDeficiency = formReminders.cleaned_data["hasEmotionalDeficiency"] isNecessaryToObtain = formReminders.cleaned_data["isNecessaryToObtain"] doesAReallyCauseB = formReminders.cleaned_data["doesAReallyCauseB"] areAllStepsPresent = formReminders.cleaned_data["areAllStepsPresent"] isCauseSufficient = formReminders.cleaned_data["isCauseSufficient"] areAllClausesIdentified = formReminders.cleaned_data["areAllClausesIdentified"] isCausalityCertain = formReminders.cleaned_data["isCausalityCertain"] languageIsEnglish = formReminders.cleaned_data["languageIsEnglish"] isTautologyPresent = formReminders.cleaned_data["isTautologyPresent"] for field in ImprovementAbstraction._meta.fields: need.field.name = field.name so if field.name is equal to "needsImprovement" I want to use the variable needsImprovement, how can I achieve this in python? -
Dynamic django serializer
im learning to use DRF and i realize there's alot of code that is being repeated within the serializer , and im wondering if im doing the right thing. Here's an example. I have 2 main models : The 2 main models class SalesProject(models.Model): sales_project_name = models.CharField(max_length=100) customer_information = models.ManyToManyField('CustomerInformation') sales_department = models.ForeignKey('SalesDepartment', on_delete=models.CASCADE) #bunch of isolated fields not stated here class Ticket(models.Model): title = models.CharField(max_length=255) customerInformation = models.ForeignKey('CustomerInformation', null=True , blank = True, on_delete = models.CASCADE) salesProject = models.ForeignKey('SalesProject', null=True , blank = True, on_delete = models.CASCADE) #bunch of isolated fields not stated here These models have varying depth which i wish to access in different scenarios. For example , When wanting to access the detail page for Ticket i would wish to exclude certain infomation i would otherwise get from using a general serializer that i defined for SalesProject and CustomerInfomation. This would then lead me to my issue , which is to rewrite a specialized foreign key serializer for SalesProject , of which all i am doing is just excluding the fields from the main general serializer for SalesProject. As illustrated here : class SalesProjectDetailSerializer(serializers.ModelSerializer): #general serializer which contains all fields and has depth of 2. This … -
DRF Serializer Prevent Instance Update if Foreign Keys aren't Updated Properly
I have a model serializer for a model with some foreign keys. My understanding is that to add objects to the foreign fields, you first save your instance and then add the fields. However, if I happen to have an error in the data I am adding to the foreign keys, this will save the updated instance but not the foreign key data (obviously, as it has an error). But if the foreign key doesn't save, I don't want the updated instance to save either. Do I have to verify the proper data before calling serializer.save()? Example: In the code below, I have a MatchModel that contains foreign keys of MatchResultVote and MatchTeams. If a match is started, I send a put request with updated data that changes isAvailable to false, isStarted to true and adds a MatchTeam The code below works fine, but if I end up accidentally passing bad data for the MatchTeam I want to add, it will still update the instance (i.e. changing isAvailable to false and isStarted to true) even though I don't want this to happen unless the MatchTeam data is also valid I'm thinking I am probably supposed to validate the MatchTeam data … -
Write XML Python - Special characters error in list of string
I have a list of string which I want to write in a XML file. My code looks like this : from jinja2 import Environment, PackageLoader, select_autoescape import os env = Environment(loader = PackageLoader(path), autoescape = select_autoescape(['html', 'xml'])) list_data = ['<managedObject class="test" operation="test"/>', '<managedObject class="test" operation="test"/>'] template = env.get_template('template.xml') output_from_parsed_template = template.render(scripts=list_data) path = os.path.join("output_file.xml") with open(str(path), "wb") as fh: fh.write(output_from_parsed_template.encode('utf-8')) My template.xml looks like this : <?xml version="1.0" encoding="UTF-8"?> {% for script in scripts %} {{ script }} {% endfor %} And I get the following error in the output_file.xml : <?xml version="1.0" encoding="UTF-8"?> &lt;managedObject class=&#34;test&#34; operation=&#34;test&#34;/&gt; &lt;managedObject class=&#34;test&#34; operation=&#34;test&#34;/&gt; Do you know how to write all special characters (double quotes and inf/supp sign) in the XML ? I'm using the same function to write a txt file and I don't have this problem. Thanks for your help