Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
tailwind sheet not showing up django
I just can't connect it! I used the CDN and it worked but I need it to have files offline as well so, I need the files natively as well. HTML and file structure below! Thanks :) My HTML : {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>#title</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="{%static "/css/style.min.css"%}"> </head> <body class= "bg-red-800"> <h1 class = "something">This can be edited using tailwind</h1> {% comment %} {% include "schedule/navbar.html" %} {% endcomment %} {% block content %} {% endblock %} </body> </html> File structure: -
Removing a field from a django model form breaks the formatting in the HTML
Removing a field from my forms.py django form removes formatting although form works fine. If I remove "useremail" (as this is now paired up with the standard django User model email), all of the formatting / placeholders etc is removed from all of the fields in the HTML. This happens if I remove any of the 4 fields. All of the forms work, although it loses any control over attributes and styling. Picture 1 shows the html with everything below (this works fine). If I remove "useremail" from the forms.py, the formatting breaks as seen in picture 2. No error messages flag in the console forms.py class SafezoneForm(forms.ModelForm, admin.ModelAdmin): name = forms.CharField(label='Safezone name',widget=forms.TextInput (attrs={'id': 'name', 'label': 'Name of Safezone', 'class': 'form-inputs'})) useremail = forms.CharField(label='Your Email', widget=forms.EmailInput (attrs={'id': 'useremail','class': 'form-inputs',"placeholder": "mike@xyz.com"})) latitudecentre = forms.FloatField(label='Marker Latitude',widget=forms.TextInput (attrs={'id': 'latitudecentre','class': 'form-inputs', 'readonly': True})) longitudecentre = forms.FloatField(label='Marker Longitude',widget=forms.TextInput (attrs={'id': 'longitudecentre','class': 'form-inputs', 'readonly': True})) class Meta: model = Safezone models.py class Safezone(models.Model): userid = models.OneToOneField(User, on_delete=models.CASCADE, null=True) useremail = models.EmailField(User, null=True) name = models.CharField(max_length=100, null=True) latitudecentre = models.FloatField(null=True) longitudecentre = models.FloatField(null=True) latcorner1 = models.FloatField(null=True) def save(self, *args, **kwargs): self.latcorner1 = self.latitudecentre + 0.1 super(Safezone, self).save(*args, **kwargs) def __str__(self): return str(self.userid) or '' Views.py def collapsecard(request): if … -
Django Querysets: Ordering posts by number of similar tags
Let's say I have a Django model for : Post - Representing a blog post Tag - Representing a canonical Tag. Let's pretend it's a hashtag. PostTag - A foreign key intermediary between Posts and Tags. Now let's say I have 5 posts with these tags: #food #story #recepie #gardening #entree #food #story #recepie #ham # sandwich #food #story #flowers #fish #sushi #food #story #computer #keyboard #mouse #food #coffee #vitamins #basil #citrus -- Given Post 1 with it's 5 tags, how can I get N number of other posts with the most similar tags? Posts.objects.filter(publish_at__gte=somedatetime).order_by("similarity") -
Run Django in production or development mode and let variables depend on it
I'm working on a Django project and in one of my functions I'm redirecting the user to a redirect url which is different in production and development. When the project is running in production, it's starting up the server with the wsgi.py file and gunicorn. When I'm developing I start up the server with python manage.py runserver. So I figured I can just initialise environment variable 'DEVELOPMENT_MODE'='FALSE' and then evaluate os.environ.get('DEVELOPMENT_MODE') in the py file where I have the redirect url, since this environment variable will not be initialised with python manage.py runserver. This doesn't seem to be working though and I'm looking for a solution. This is my first project in Django. -
Django charfield problem not returning value of text
`from django.db import models class Topic(models.Model): """A topic the user is learning about""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def str(self): """Return a string representation of the model""" return self.text` So the above code contains variable text which stores the 'Topic' name but as i enter the topic name in django site admin it never shows the text rather than it stores and display "object(1) is successfully stored" -
Django template context not working with date template tag
I'm passing the date as an entire string as below: def template_test(request): context = { 'day': '2021-04-19T03:00:00Z', } return render(request, 'date_test.html', context=context) date_test.html {% extends 'base.html' %} {% block content %} <p>Here is the day {{ day|date:"l, j M y" }}</p> {% endblock %} Does anyone know why when I add a date template tag on my day variable it doesn't work? If I remove it, the day variable is showing normally but with filter not. -
How to increment a column by 1 for each time a link is clicked on a webpage (Django)?
Background: The website displays a list of products that all have a link to an external site. I would like to create a counter that adds 1 to the column "views" for each time the products link is clicked. This is to see which product has been clicked the most. I would appreciate any help? The "views" column stores the number of times the link is clicked. models.py class T_shirt(models.Model): Images = models.ImageField() Titles = models.CharField(max_length=250, primary_key=True) Prices = models.CharField(max_length=250) Link = models.CharField(max_length=250) Website = models.CharField(max_length=250) Brand = models.CharField(max_length=250) views = models.IntegerField(default=0) HTML <ul class="products"> {% for v in owner_obj %} <div class="container"> <a href={{ v.Link }} target="_blank" rel="noopener noreferrer"> <img src={{ v.Images }} width="150" height="150"> </a> <figcaption> {{ v.Titles }} </figcaption> <figcaption> <b>{{ v.Prices }} </b></figcaption> </div> {% endfor %} </ul> -
Django Rest Framework sending email but template doesnt load CSS
I am sending an email from Django Rest using django.core.mail module. Views.py from django.core.mail import send_mail from django.template.loader import render_to_string from django.utils.html import strip_tags ... ## Send the email somewhere in the viewset html_mail = render_to_string('emails/invitation.html', {'email': email, 'url': url, 'invitation_code': invitation_code}) mail_template = strip_tags(html_mail) send_mail( 'You are invited!', mail_template, [sender_mail], [email], fail_silently=False, ) return Response({'message': 'Invitation email sent to ' + email},200) I have template path in the settings, TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates') ], And on the template I have the regular HTML template with a bunch of CSS code. Example Email Template: <!DOCTYPE html> <html lang="en" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office"> <head> <meta charset="utf-8"> <meta name="x-apple-disable-message-reformatting"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="format-detection" content="telephone=no, date=no, address=no, email=no"> <!--[if mso]> <xml><o:OfficeDocumentSettings><o:PixelsPerInch>96</o:PixelsPerInch></o:OfficeDocumentSettings></xml> <style> td,th,div,p,a,h1,h2,h3,h4,h5,h6 {font-family: "Segoe UI", sans-serif; mso-line-height-rule: exactly;} </style> <![endif]--> <title>Default email title</title> <link href="https://fonts.googleapis.com/css?family=Montserrat:ital,wght@0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,200;1,300;1,400;1,500;1,600;1,700" rel="stylesheet" media="screen"> <style> .hover-underline:hover { text-decoration: underline !important; } @keyframes spin { to { transform: rotate(360deg); } } @keyframes ping { 75%, 100% { transform: scale(2); opacity: 0; } } @keyframes pulse { 50% { opacity: .5; } } @keyframes bounce { 0%, 100% { transform: translateY(-25%); animation-timing-function: cubic-bezier(0.8, 0, 1, 1); } 50% { transform: none; animation-timing-function: … -
Docker: a web service built but failed to execute
I`m trying to build a Django web service with docker. The docker file is ENV DockerHOME=/home/xs1_glaith/cafegard RUN mkdir -p $DockerHOME WORKDIR $DockerHOME ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 the docker-compose file is like this version: "3.9" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgress - POSTGRES_USER=postgress - POSTGRES_PASSWORD=postgress web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/home/xs1_glaith/cafegard ports: - "8000:8000" depends_on: - db COPY . $DockerHOME RUN pip install --upgrade pip RUN pip install -r $DockerHOME/requirements.txt EXPOSE 8000 CMD python manage.py runserver finally, the result is Starting cafegard_db_1 ... done Creating cafegard_web_run ... done Error response from daemon: OCI runtime create failed: container_linux.go:367: starting container process caused: exec: ".": executable file not found in $PATH: unknown ERROR: 1 I dont really understand whats the problem or what`s make the problem!!! -
Django multi tenany one domain for one or more users
I'm working on a small project using Django/Rest with multi tenancy package : https://django-tenants.readthedocs.io/en/latest/install.html and i would like to know if there is any way to have one domain for multiple users -
how to use SearchVector SearchRank with icontain in Django?
I'm trying to use SearchVector in Django. I read from here that how to use SearchVector with icontains. but I can't seem to find any information on how to use SearchVector and SearchRank and check if string contains the desired string. here is my models.py class Tag(models.Model): Name=models.CharField(max_length=20) def __str__(self): return self.Name class data(models.Model): FirstName = models.CharField(max_length=20) LastName = models.CharField(max_length=20) tag = models.ManyToManyField(to=Tag,blank=True,null=True) def __str__(self): return self.FirstName+" "+self.LastName here is my views.py def searchView(request): if request.method == "POST": form=NameForm(request.POST) if form.is_valid(): vector = SearchVector("FirstName",weight="A")+SearchVector("tag__Name",weight="C")+SearchVector("LastName",weight="B") query = SearchQuery(form.cleaned_data["name"],search_type="phrase") rank = SearchRank(vector, query, weights=[0.8, 0.6, 0.4, 0.2]) data=data.objects.annotate(rank=rank).filter(rank__gte=0.1).order_by('rank') else: data= [] form = NameForm() return render(request, "pdf.html", context={"data": data,"form":form}) else: data=[] form=NameForm() return render(request, "pdf.html", context={"data": data,"form":form}) -
Django 3 - How to create many pages and then show them on menu?
I am new in python Django and practicing it. I have a Wordpress site and I want to migrate it to Django. I can create blogs, pages etc on Django but the problem is I have to make 20+ pages of that site if I move it to Django. And to show them like parent and children of pages. I can create single pages in Django and show them in template. But I want to make it from admin panel. So me and in future, my client can create new pages easily and I want them to automatically view on navigation. I want it just like wordpress, create a page, save it and boom, it will be live on frontpage(if configured in settings). I searched for the help or right direction but cant find anywhere. Please someone point me which is the best way to achieve this ? -
Cannot access "instance" or detail view of an object from react frontend with Django rest framework backend
So, I have this view for my models, on a django-rest-framework project class GenreViewSet(viewsets.ModelViewSet): queryset = Genre.objects.all() serializer_class = GenreSerializer permission_classes = [permissions.AllowAny] This is my serializer: class GenreSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Genre fields = ('name', 'artist', 'albums') depth = 2 On urls: router = routers.DefaultRouter() router.register(r'genre', views.GenreViewSet) urlpatterns = [ path('rest-framework/', include(router.urls)), ] Now, I have a react based frontend app, to access this object, if I access the recordset, meaning, the list of all the objects, then I'm perfectly able to do it, but, if for example, I want to access, just one of the objects in database, something like: path/to/url:8000/object/id Then I got this error, but only from the frontend, the react app: Access to fetch at 'http://127.0.0.1:8000/rest-framework/genre/2' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. Actually, I do have django-cors-headers installed, and also configured on my settings.py file. As I said, I can access the object list, listing all the objects into db, just not the detail. On my settings.py I have: CORS_ORIGIN_ALLOW_ALL = True … -
I am very confused on what to do
I am currently deploying an app on the heroku website on django. I had been combatting multiple errors, and I managed to pass through the static files and I got stuck on the preparing wheel metadata. I would like to ask what I should do to bypass this error. Here is the error: Installing build dependencies: started Installing build dependencies: finished with status 'done' Getting requirements to build wheel: started Getting requirements to build wheel: finished with status 'done' Preparing wheel metadata: started Preparing wheel metadata: finished with status 'error' ERROR: Command errored out with exit status 1: command: /app/.heroku/python/bin/python /app/.heroku/python/lib/python3.9/site-packages/pip/_vendor/pep517/_in_process.py prepare_metadata_for_build_wheel /tmp/tmpa6ent96x cwd: /tmp/pip-install-v0czirbb/pywinpty Complete output (6 lines): Checking for Rust toolchain... Cargo, the Rust package manager, is not installed or is not on PATH. This package requires Rust and Cargo to compile extensions. Install it through the system's package manager or via https://rustup.rs/ ---------------------------------------- ERROR: Command errored out with exit status 1: /app/.heroku/python/bin/python /app/.heroku/python/lib/python3.9/site-packages/pip/_vendor/pep517/_in_process.py prepare_metadata_for_build_wheel /tmp/tmpa6ent96x Check the logs for full command output. ! Push rejected, failed to compile Python app. ! Push failed -
ElasticBeanstalk Deployment Failed: WSGI cannot be loaded as Python module
I am facing Django deployment issues related wsgi configuration and wanted to see if everything is fine from project setup and EBS side i.e. correct WSGI, python version. I am following standard project structure: [dhango_project]/ ├── [dhango_project]/ │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py | |── [blog] |── [static]/ | ├── [css] | ├── [Javascript] | └── [Images] | |── [templates] |── manage.py └── requirements.txt dhango_project/.ebextensions/django.config option_settings: "aws:elasticbeanstalk:container:python": WSGIPath: "dhango_project/wsgi.py" "aws:elasticbeanstalk:container:python:staticfiles": "/static/": "static/" I am seeing error : apps.populate(settings.INSTALLED_APPS) [Fri Apr 30 13:26:27.696673 2021] [:error] [pid 28548] [remote xxxxx] File “/opt/python/run/venv/local/lib/python3.6/site-packages/django/apps/registry.py”, line 83, in populate [Fri Apr 30 13:26:27.696676 2021] [:error] [pid 28548] [remote xxxxx] raise RuntimeError(“populate() isn’t reentrant”) [Fri Apr 30 13:26:27.696688 2021] [:error] [pid 28548] [remote xxxxx] RuntimeError: populate() isn’t reentrant [Fri Apr 30 13:26:38.189812 2021] [:error] [pid 28548] [remote xxxxx] mod_wsgi (pid=28548): Target WSGI script ‘/opt/python/current/app/dhango_project/wsgi.py’ cannot be loaded as Python module. [Fri Apr 30 13:26:38.189855 2021] [:error] [pid 28548] [remote xxxxxx] mod_wsgi (pid=28548): Exception occurred processing WSGI script ‘/opt/python/current/app/dhango_project/wsgi.py’. [Fri Apr 30 13:26:38.189952 2021] [:error] [pid 28548] [remote xxxxxx] Traceback (most recent call last): [Fri Apr 30 13:26:38.189977 2021] [:error] [pid 28548] [remote xxxxxx] File “/opt/python/current/app/dhango_project/wsgi.py”, line 16, in [Fri Apr … -
how to connect oracle database in python django instead of sqlite
I want to make a DBMS projects on Topic Railway Management System for that I choose django framework , but as a database for me it is requires to use oracle 19c as database. So please if someone can help mw how I can remove sqlite from django and install oracle database in it. -
Django - content_type_id not recognised when running test on models using postgresdb
I have a two models Actor and User in my project. Actor is a superset of User with the usage of ContentType. The issue is that, I have two projects same. One using sqlite and other built in docker running postrgres db. The sqlite3 with the same code pass all the tests but the one with postgresql is stuck with a test error ContentType when I try to test the creation of an Actor object. models.py from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey from django.db import models # for testing Actor and ContentType: class Actor(models.Model): """ Actor: the superset for User and Applicant """ choices = models.Q(app_label='core', model='user') content_type = models.ForeignKey(ContentType, limit_choices_to=choices, related_name='entity_types', on_delete=models.CASCADE, null=True) entity_id = models.PositiveIntegerField( null=True) content_object = GenericForeignKey('content_type', 'entity_id') company_id = models.IntegerField() created_at = models.DateTimeField() created_by = models.CharField(max_length=255) def __str__(self): return '{0}'.format(self.content_type) class User(models.Model): actor_id = models.ForeignKey(Actor, on_delete=models.CASCADE) # having issues to relate two models created_at = models.DateTimeField() created_by = models.CharField(max_length=255) def __str__(self): return '{0}'.format(self.actor_id) tes_models.py from django.contrib.contenttypes.models import ContentType from django.contrib.auth.models import Permission from django.test import TestCase from core.models import Actor, User """ get content_type to get its id in test_actor_relationship() """ CONTENT_TYPE_HELPER = ContentType.objects.get_for_model(User) class TestModels(TestCase): def test_actor_get_entity(self): #<=== PASS """ test if … -
Can I add a form in django in HTML
I want to add comments form a specific html which has it's separate views and models and I don't want to create a new form.html just to display the form and its views. But I'm stuck. I can add comments manually from the admin page and it's working fine, but it seems that I have to create another url and html file to display the comment form and for users to be able to add comments(btw I'm trying to build a sports related website). Thanks in advance! My models.py: class Transfernews(models.Model): player_name = models.CharField(max_length=255) player_image = models.CharField(max_length=2083) player_description = models.CharField(max_length=3000) date_posted = models.DateTimeField(default=timezone.now) class Comment(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) transfernews = models.ForeignKey(Transfernews, related_name="comments", on_delete=models.CASCADE) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.transfernews.player_name, self.user.username) My forms.py : class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('body',) My views.py : def addcomment(request): model = Comment form_class = CommentForm template_name = 'transfernews.html' My urls.py: path('comment/', views.addcomment, name='comment'), My transfernews.html: <h2>Comments...</h2> {% if not transfernew.comments.all %} No comments Yet... {% else %} {% for comment in transfernew.comments.all %} <strong> {{ comment.user.username }} - {{ comment.date_added }} </strong> <br/> {{ comment.body }} <br/><br/> {% endfor %} {% endif … -
ModelSerializer write with a field and read with other fields
I POST to an API and relate the created Bar object to an existing Foo object. I use the name of Foo, for example: self.client.post('/app/bar/', data={ 'username': 'nikko123', 'foo': 'Nikko' }, In my Bar Serializer, the Foo field has a ModelSerializer to relate it with, class FooSerializer(serializers.ModelSerializer): name = serializers.StringRelatedField() link = serializers.SerializerMethodField() class Meta: model = Foo fields = ('name', 'link') def to_internal_value(self, data): # Get name of Foo foo = Foo.objects.get(name=data) return {'foo': foo} def get_link(self, object): print('req', object.id) if object.id and request: return request.build_absolute_uri( '/app/foo/{}'.format(object.id)) return None class BarSerializer(serializers.ModelSerializer): foo = FooSerializer(source='*') ... class Meta: model = Bar My problem is that the response from Bar, I get empty from Foo. {'id': 2, 'username': 'nikko123', 'foo': {'link': None}, # name is also missing } I have tested the Bar object and it saved the Foo, however it is not serializing. What could be the problem here? -
I want to represent a django table header as a checkbox
I'm making a django table using django-tables2. What I want is to create a header cell as a checkbox but the problem is django-tables2 doesn't seem to render html when passed as verbose. Here is my table code : class AllTable(tables.Table): CHECKBOX_TEMPLATE = ' <input id="forms_check" type="checkbox" name="forms_check" pk="{{record.pk}}" /> ' _ = tables.TemplateColumn(CHECKBOX_TEMPLATE) _.verbose_name = "<input type='checkbox'>" class Meta: model = models.All template_name = "django_tables2/bootstrap.html" fields = ("_","id","name") The result i'm getting is as follow : What I want is a checkbox instead. Please if anyone knows the way can you guide me through this. Thanks. -
Limiting the amount of decimals displayed, django
So i have an issue, which is basically i am displaying a model with decimal fields and i cant limit how many zeros are displayed, basically it looks like there is too many of then, and i was wondering how to limit it? Here is the template code, <table class="table table-striped table-dark" width="100%"> <thead> <th>Posicao</th> <th>Marca</th> <th>Modelo</th> <th>Ano</th> <th>Média de lucro</th> </thead> {%for q in query4 %} <tr> <td>{{forloop.counter}}</td> <td>{{q.marca}}</td> <td>{{q.modelo}}</td> <td>{{q.ano}}</td> <td>{{q.medias}} %</td> </tr> {% endfor%} </table> The query backend, query4=DataDB.objects.values('marca','modelo','ano').annotate(medias=Avg('margem_de_lucro')).order_by('-medias') The modals being called marca=models.CharField(max_length = 30,error_messages={'required':'Favor inserir uma marca'}) modelo=models.CharField(max_length = 60,error_messages={'required':'Favor inserir um modelo'}) ano=models.IntegerField( validators=[MinValueValidator(1960,'Favor inserir acima 1960.'), MaxValueValidator(2023,'Favor inserir abaixo 2023.')], error_messages={'required':'Favor inserir uma ano'}) margem_de_lucro=models.DecimalField(max_digits= 12,decimal_places=3,max_length= 12) -
django databaseerror on apache2 with uwsgi
It is a project that deloyed two years ago(no changes for about two years). But today it was reported crash. got the log as below(I replaced real project path with 'PATH/TO/PROJECT'). django.request - INFO - OK: / Traceback (most recent call last): File "/PATH/TO/PROJECT/venv/lib/python3.5/site-packages/django/contrib/sessions/backends/base.py", line 189, in _get_session return self._session_cache AttributeError: 'SessionStore' object has no attribute '_session_cache' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/PATH/TO/PROJECT/venv/lib/python3.5/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/PATH/TO/PROJECT/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/PATH/TO/PROJECT/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/PATH/TO/PROJECT/apps/home/views.py", line 6, in index return render(request, 'index.html') File "/PATH/TO/PROJECT/venv/lib/python3.5/site-packages/django/shortcuts.py", line 36, in render content = loader.render_to_string(template_name, context, request, using=using) File "/PATH/TO/PROJECT/venv/lib/python3.5/site-packages/django/template/loader.py", line 62, in render_to_string return template.render(context, request) File "/PATH/TO/PROJECT/venv/lib/python3.5/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/PATH/TO/PROJECT/venv/lib/python3.5/site-packages/django/template/base.py", line 171, in render return self._render(context) File "/PATH/TO/PROJECT/venv/lib/python3.5/site-packages/django/template/base.py", line 163, in _render return self.nodelist.render(context) File "/PATH/TO/PROJECT/venv/lib/python3.5/site-packages/django/template/base.py", line 937, in render bit = node.render_annotated(context) File "/PATH/TO/PROJECT/venv/lib/python3.5/site-packages/django/template/base.py", line 904, in render_annotated return self.render(context) File "/PATH/TO/PROJECT/venv/lib/python3.5/site-packages/django/template/defaulttags.py", line 302, in render match = condition.eval(context) File "/PATH/TO/PROJECT/venv/lib/python3.5/site-packages/django/template/defaulttags.py", line 876, in eval return self.value.resolve(context, ignore_failures=True) File "/PATH/TO/PROJECT/venv/lib/python3.5/site-packages/django/template/base.py", line 671, in resolve obj = self.var.resolve(context) File … -
Django internal server error - No module decouple
I am trying to deploy some basic django app on linode but I get error 500 whenever I try to access my website. Here are the files and logs tail -200 mysite-error.log [Mon May 03 17:00:53.788104 2021] [wsgi:error] [pid 10477:tid 139635748644416] [remote 85.68.32.122:57733] mod_wsgi (pid=10477): Failed to exec Python script file '/var/www/GreatKart/greatkart/wsgi.py'. [Mon May 03 17:00:53.788180 2021] [wsgi:error] [pid 10477:tid 139635748644416] [remote 85.68.32.122:57733] mod_wsgi (pid=10477): Exception occurred processing WSGI script '/var/www/GreatKart/greatkart/wsgi.py'. [Mon May 03 17:00:53.789344 2021] [wsgi:error] [pid 10477:tid 139635748644416] [remote 85.68.32.122:57733] Traceback (most recent call last): [Mon May 03 17:00:53.789422 2021] [wsgi:error] [pid 10477:tid 139635748644416] [remote 85.68.32.122:57733] File "/var/www/GreatKart/greatkart/wsgi.py", line 16, in <module> [Mon May 03 17:00:53.789429 2021] [wsgi:error] [pid 10477:tid 139635748644416] [remote 85.68.32.122:57733] application = get_wsgi_application() [Mon May 03 17:00:53.789439 2021] [wsgi:error] [pid 10477:tid 139635748644416] [remote 85.68.32.122:57733] File "/usr/local/lib/python3.9/dist-packages/django/core/wsgi.py", line 12, in get_wsgi_application [Mon May 03 17:00:53.789443 2021] [wsgi:error] [pid 10477:tid 139635748644416] [remote 85.68.32.122:57733] django.setup(set_prefix=False) [Mon May 03 17:00:53.789452 2021] [wsgi:error] [pid 10477:tid 139635748644416] [remote 85.68.32.122:57733] File "/usr/local/lib/python3.9/dist-packages/django/__init__.py", line 19, in setup [Mon May 03 17:00:53.789456 2021] [wsgi:error] [pid 10477:tid 139635748644416] [remote 85.68.32.122:57733] configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) [Mon May 03 17:00:53.789464 2021] [wsgi:error] [pid 10477:tid 139635748644416] [remote 85.68.32.122:57733] File "/usr/local/lib/python3.9/dist-packages/django/conf/__init__.py", line 82, in __getattr__ [Mon May 03 17:00:53.789468 2021] [wsgi:error] … -
Pycharm - is there a key shortcut to stop automatic closure of brackets?
I'm currently playing around with Django using Pycharm and have never used this IDE for Django development before as I usually just used Visual Studio Code or Atom etc. Pycharm has a useful feature for auto closing brackets and expressions, for example, if I type '{%', it will produce '{% %}' with my cursor in the middle. The problem is sometimes I might not want this to happen say, if I'm editing code rather than writing it. What I'm wondering is, is there a way to temporarily over-ride this feature by pressing a key? I don't want to disable the feature entirely as it is otherwise useful. Any help would be much appreciated. Thanks again everyone. -
AttributeError at /dashboard/2650/files/ 'DashModelDetailFilesView' object has no attribute 'object'
I want to create a page with the class based view that inherit views DetailView and FormView but get the error. Here's the code of the view: views.py class DashModelDetailFilesView(DetailView,FormView): template_name = 'dashboard/dashboard-files.html' queryset = DashModel.objects.all() form_class = AddFile success_url = '/dashboard/search-models/' context_object_name = 'dashmodelFile' def form_valid(self,form): form.save() return super().form_valid(form)``` forms.py class AddFile(forms.ModelForm): class Meta: model = DashModelFile fields = '__all__' widgets = { 'file': forms.FileInput, } I created dashmodelfile model to upload multiple filed for the main model. models.py class DashModelFile(models.Model): file = models.FileField(null=True, blank = True) dashmodel = models.ForeignKey(DashModel, on_delete=models.CASCADE, related_name='files')