Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to change email settings in django dynamically
I want to make an email sender app that took user email and password and send an email to multiple recipients. I am not sure whether it is possible to do because we have to provide Email_HOST_USER in settings. If anyone can help me with explanation please? -
dropdown is not showing html css
i have the attr data-toggle= dropdown on the {{form.query}} which is the search input but it just wont show, any solutions? bootstrap/jquery links in head section <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> js in body <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script> hmtl code <form class="dropdown" method="get"> {{form.query}} <ul class="dropdown-menu col-12 pl-2" role="menu" aria-labelledby="menu" id="list"> <li role="presentation"> <a href="#" role="menuitem" tabindex="-1">Django</a></li> <div class="dropdown-divider"></div> <li role="presentation"> <a href="#" role="menuitem" tabindex="-1">Potato</a></li> <div class="dropdown-divider"></div> <li role="presentation"> <a href="#" role="menuitem" tabindex="-1">Sleep</a></li> </ul> {{form.category}} <input type="submit" value="Search" class="btn btn-lg btn-primary col-12 my-2"> </form> -
I was trying to add templates to my Django project but it returns an error: TemplateDoesNotExist at /
I get a mistake when tying to add templates to my Django project. settings.py : TEMPLATE_DIRS = ( os.path.join(os.path.dirname(__file__), 'templates'), ) views.py: def index(request): a = models.User.objects.get() return render(request, "main/list.html", {"list": a}) and list.html: {% extends "base.html" %} {% block title %}Chats{% endblock %} {% block content %} {% if list%} {% for i in list%} <h2>{{i.usrname}}</h2> {% endif %} The project folder itself looks like this: Main folder is app. Thanks for your help! -
How to dynamically update Twitter meta tags using Django model object fields
all. I am trying to create Twitter cards dynamically by filling in "content=" values with Django model object fields that I can update using the admin panel. My HTML header code looks like this: <meta name="twitter:card" content="{{ lesson.twitter_card_type }}"> <meta name="twitter:description" content="{{ lesson.twitter_description }}"> <meta name="twitter:title" content="{{ lesson.twitter_title }}"> <meta name="twitter:site" content="{{ lesson.twitter_site }}"> <meta name="twitter:image" content="{{ lesson.twitter_image }}"> <meta name="twitter:creator" content="{{ lesson.twitter_creator }}"> Replacing the variables with static values passes the Twitter card validator checks. When using variables, the browser inspector displays the proper meta tags, but I get the following output from the Twitter card validator log: INFO: Page fetched successfully INFO: 13 metatags were found ERROR: Invalid card name (Card error) According to this answer Twitter card meta tags work in index.html, not in React Helmet and this answer Dynamically adding meta tags using javascript or jquery [twitter cards], it seems that there might be an issue using variables in meta tags; however, this site https://www.ordinarycoders.com/blog/article/how-to-add-django-meta-tags states using Django model objects should work. Unfortunately, I need to create cards dynamically the way my site is set up so hard-coding is not an option. Thanks in advance to anyone who can offer any insight! -
By using transaction.atomic, are all ACID properties met?
This is a theoretical question I'm trying to work out. I'm working on a Django-based web application and I'm wanting to make my Django database transactions ACID compliant. However I'm wondering if this is fully achieved by using transaction.atomic? Obviously, Atomicity is achieved here but are the other 3 properties also achieved? If not, what steps can I take to achieve those 3 properties? Any thoughts and explanations would be much appreciated, thank you! -
All data gets deleted after deploying new version in Elastic Beanstalk
So I am hosting my Django website on the elastic beanstalk. Whenever I deploy a new version the older data gets deleted. Though upon deploying a newer version, it says it uses S3 bucket yet all my data and images are deleted. .ebextensions/db-migrate.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: ebdjango/wsgi.py settings.py .... DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': str(BASE_DIR / 'db.sqlite3'), } } ... STATIC_URL = '/static/' STATIC_ROOT = 'static' MEDIA_URL = '/uploads/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/uploads') ... -
DRF convert string of Ids to related model objects in serializer
Trying to write up a Model/Serializer/View with DRF to provide a rest_framework.viewsets.ModelViewSet that includes the appropriate EmpList based on the string of user-ids in Publication.author. Only need the objects to be serialized for output, no need to create new EmpList objects. # Would a model manager help here? class Publication(models.Model): # The author is stored as a string "user-id1, user-id2, user-id3" # This storing as a string of multiple ids can't change author = models.TextField() ... class PublicationSerializer(serializers.ModelSerializer): # Would I add code here to override list? class PublicationViewSet(rest_framework.viewsets.ModelViewSet): queryset = Publications.objects.all() serializer_class = PublicationSerializer # EmpList is a model on top of an SQL View, so there's no real model level connection in the tables class EmpList(models.Model): # This ID matches up with "user-id1" found in Publication.author id = models.CharField() name = models.CharField() ... class EmpListSerializer(serializer.Serializer): class Meta: model = EmpList fields = ["__all__"] This seems pretty possible, I just can't seem to figure out how to wire things up correctly. Any thoughts are appreciated, thanks. -
database_table locked during automated tests with selenium django
I use django==3.1.2 and selenium and selenium==3.141.0. I have a test file with 12 tests and when I execute them like so: python3 manage.py test myapp.tests --settings=app.settings_test 2 of the tests fail. When I execute them singly like so python3 manage.py test myapp.tests.MyTests.test_this --settings=app.settings_test they don't fail. The errors are usually something like django.db.utils.OperationalError: database table is locked: visitors_person The above exception was the direct cause of the following exception: myapp_cars ... django.core.management.base.CommandError: Database file:memorydb_default?mode=memory&cache=shared couldn't be flushed. Possible reasons: * The database isn't running or isn't configured correctly. * At least one of the expected database tables doesn't exist. * The SQL was invalid. Hint: Look at the output of 'django-admin sqlflush'. That's the SQL this command wasn't able to run. or django.db.utils.OperationalError: database table is locked: myapp_drivers It always errors on different models of the database. My database in settings_test.py looks like this: DATABASES['default'] = { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(tempfile.gettempdir(), 'db_test.sqlite3'), 'OPTIONS': { 'timeout': 20, } } During these tests I create about 120 entries spread over 12 tests, the fixtures install about 20 entries. So not that much. After googling the error I added the timeout and I added time.sleep(1) after each MyModal.objects.create() to see if this … -
Change django model fields on the basis of other fields value
I have a query that can we achieve something like this. This is not a model. This is just a plot of what I want to achieve. I want to change field input type on the basis of other field value. x=models.BooleanField(default=true) if x: name =models.CharField(max_length=100, null=True, blank=True, default='abc') else: name=models.ForeignKey(SomeModel,on_delete=models.CASCADE) -
Please help, no code changed but now not working
I have a django Post model with a user foreign key. When I create a post it normally would work and fill the user with the requested user as instructed in the serializer but on postman I get: { "user": [ "This field is required." ] } here is the API view: class PostViewset(viewsets.ModelViewSet): queryset = Post.objects.all() serializer_class = PostSerializer permission_classes = [IsOwnerOrReadOnly] def perform_create(self, serializer): serializer.save(user=self.request.user) here is the serializer: class PostSerializer(serializers.ModelSerializer): user_name = serializers.SerializerMethodField() class Meta: model = Post fields = ['user', 'id', 'title', 'body', 'user_name'] def get_user_name(self, obj): try: return obj.user.user_name except: pass -
Django: datetime.now() not saving to database from view.py
I am trying to save the date time in my view on form submission. models: class Request(models.Model): email = models.EmailField(max_length=200) percentage = models.FloatField( default=0, validators=[MinValueValidator(0), MaxValueValidator(100)]) fee = models.FloatField(default=0, validators=[ MinValueValidator(0), MaxValueValidator(100000)]) updated_at = models.DateTimeField(db_index=True, auto_now=True) requested_at = models.DateTimeField(null=True) approved_at = models.DateTimeField(null=True) confirmed_at = models.DateTimeField(null=True) view: if form.is_valid(): instance = form.save(commit=False) instance.requested_at = datetime.now() instance.save() The form saves fine except for the requested_at date time which isn't saving. Think I am missing something simple but I cannot figure it out... -
Is there a way to use reverse outside of a Django App?
Long story short, I need to call a python script from a Celery worker using subprocess. This script interacts with a REST API. I would like to avoid hard-coding the URLs and django reverse seems like a nice way to do that. Is there a way to use reverse outside of Django while avoiding the following error? django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I would prefer something with low-overhead. -
How do I update fields in MongoDB document using djongo?
how can I update a document fields with Djongo MongoDB Model exemple { id: ObjectId(6deer3096f0efae5c49b9983f) email:"email@gmail.com" password:"pass" username:"user" } Request made { email:"newemail@gmail.com" password:"newpass" username:"newuser" } Here is my code @api_view(['GET', 'POST', 'DELETE']) def user_detail(request, id): try: user = User.objects.get(_id=ObjectId(str(id))) user_serializer = UserSerializer(data=user, many=False) except User.DoesNotExist: return JsonResponse({'message': 'The user does not exist'}, status=status.HTTP_404_NOT_FOUND) if request.method == 'POST': edited_user = JSONParser().parse(request) edited_user_serializer = UserSerializer(data=edited_user) if edited_user_serializer.is_valid(): for key in edited_user_serializer.data: user.key = edited_user_serializer.data[key] user.save() return JsonResponse({'edited': edited_user_serializer.data}, status=status.HTTP_200_OK) else: return JsonResponse({'error': "an error occured"}, status=status.HTTP_400_BAD_REQUEST) If I had done: user.username = "newusername" It would work, but inside this for loop it doesn't Thank you for your help ! . -
Django - admin: how can i override admin/helpers
I want to override Class in admin/helpers, exactly FieldSet. I want to add __ getitem __ attribute to get elements by their name. I know how i can modify template, ModelAdmin. But there is any solution to override only this helper? -
Django form textarea set innerHTML
I have a django form: class newArticleForm(forms.Form): title = forms.CharField(label="", widget=forms.TextInput(attrs={'placeholder': 'Title'})) article = forms.CharField(label="", widget=forms.Textarea(attrs={'style': 'margin-top: 0px; margin-bottom: 0px; height: 184px;', 'placeholder': "Article content (markdown supported!)"})) and I want to change the innerHTML content of the textarea article. now, why can't I use value? because the text I want to put in is more than one line. any help is appreciated -
GeoDjango error, makemigrations fail with : OSError: [WinError 127] The specified procedure could not be found
I've install OSGeo4W64 express web, specify in myapp/settings.py : from pathlib import Path import os # Geo lib if os.name == 'nt': import platform OSGEO4W = r".\external_components\OSGeo4W" if '64' in platform.architecture()[0]: OSGEO4W += "64" assert os.path.isdir(OSGEO4W), "Directory does not exist: " + OSGEO4W os.environ['OSGEO4W_ROOT'] = OSGEO4W os.environ['GDAL_DATA'] = OSGEO4W + r"\share\gdal" os.environ['PROJ_LIB'] = OSGEO4W + r"\share\proj" os.environ['PATH'] = OSGEO4W + r"\bin;" + os.environ['PATH'] # ... INSTALLED_APPS = [ # ... 'django.contrib.gis', ] # ... DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.spatialite', 'NAME': BASE_DIR / 'db.sqlite3', } } # ... I've installed GDAL 3.2.1 cp38 win amd64 as I use Python 3.8 (on a Windows 10 environnement), tried a lot of solutions but everytime when I try to run python manage.py makemigrations, I got this error : D:\...\myproject\venv\Scripts\python.exe D:/.../myproject/manage.py makemigrations Traceback (most recent call last): File "D:/.../myproject/manage.py", line 22, in <module> main() File "D:/.../myproject/manage.py", line 18, in main execute_from_command_line(sys.argv) File "D:\...\myproject\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "D:\...\myproject\venv\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "D:\...\myproject\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "D:\...\myproject\venv\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "D:\...\myproject\venv\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\...\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, … -
TemplateDoesNotExist at /hobbies/
This question is the sequel of my previous question - Reverse for 'hobbieswithCSS.html' not found. 'hobbieswithCSS.html' is not a valid view function or pattern name I have moved from one error (in the title of previous question) to another, (in the title of this question) but hopefully this one will not be that much difficult to solve. I have this anchor tag on my homepage - <a href="{% url 'hobbieswithCSS' %}"> I have this view in my views.py file - def hobbieswithCSS(request): return render(request,'hobbieswithCSS.html') And these are my urlpatterns - urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^admin/', admin.site.urls), url(r'^basic_app/',include('basic_app.urls')), url(r'^logout/$',views.user_logout,name='logout'), url(r'^hobbies/$', views.hobbieswithCSS, name='hobbieswithCSS'), ] Can anyone help me please? Thank You very much in advance. -
Azure Web App for Django Deployment Not Working
I'm trying to deploy my Django React web app using Azure, but it's not running. I'm using GitHub to push the code onto Azure, so I think the issue is in my settings.py file. For security reasons, I stored the SECRET_KEY, DATABASES, ALLOWED_HOSTS, and DEBUG settings in a .env file and did not push that onto GitHub. On the Azure app, I went into the application settings and tried to add those variables in but I think there's an issue with that. Does anyone know how to properly add those environmental variables, especially the DATABASES settings for a MySQL server? -
OBJECT admin_url in Django Admin Sidebar
I have a model: class ContentSection(models.Model): section_heading = models.CharField(max_length=30, blank=True, null=True, default="") section_desc = models.CharField(max_length=200) class Meta: ordering = ['section_heading'] verbose_name_plural = 'Content Section' def __str__(self): return f"{self.section_heading}" And I registered that model in admin.py: class ContentSectionAdmin(admin.ModelAdmin): list_display = ('section_heading', 'section_desc') inlines = [ PostInline, ] admin_site.register(ContentSection, ContentSectionAdmin) So in my output, the item "Content Section" appears in the Django Admin: image But instead of "Content Section" I want the items INSIDE the ContentSection Model to appear in my Django Admin Dashboard. The Model has 3 items: Section 1, Section 2, and Section 3. I want my Django Admin Menu in my Dashboard to include both 3 sections but not as a dropdown, as items on their own INSTEAD of the ContentSection general item which groups the 3 sections. image of the 3 sections which should be in the admin sidebar instead of "Content Section" My template looks like this: {% for app in app_list %} <div class="sidebar-wrapper"> <div class="app-{{ app.app_label }} module{% if app.app_url in request.path %} current-app{% endif %}"> <div> <!--<caption> <a href="{{ app.app_url }}" class="section" title="{% blocktranslate with name=app.name %}Models in the {{ name }} application{% endblocktranslate %}">{{ app.name }}</a> </caption>--> {% for model in app.models %} … -
How to restrict access to certain groups in django class based view
My views.py have a mix of def and ClassViews: @login_required(login_url='login') @allowed_users(allowed_roles=['Admin', 'Staff', 'Lite Scan']) def litescan(request): filteredOutput = Stock.objects.all() val = {}... @method_decorator(login_required(login_url='login'), name='dispatch') class HomeView(ListView): model = Post template_name = 'community.html' ordering = ['-id'] And here's my decorators.py if that is helpful: from django.shortcuts import redirect from django.http import HttpResponseRedirect def unauthenticated_user(view_func): def wrapper_func(request, *args, **kwargs): if request.user.is_authenticated: return redirect('home') else: return view_func(request, *args, **kwargs) return wrapper_func def allowed_users(allowed_roles=[]): def decorator(view_func): def wrapper_func(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group in allowed_roles: return view_func(request, *args, **kwargs) else: url = ('/forbidden') return HttpResponseRedirect(url) return wrapper_func return decorator I found out that @login_required and @allowed_users give out an error when used with ClassView. So i used @method_decorator which brings me to the login page before redirecting to the page. However, I can not find a way to restrict access to only certain groups like Admin, Staff, Lite Scan with my ClassView. Little help will be appreciated. Thanks! -
How to fix this: Reverse for 'post_detail' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['(?P<slug>[-a-zA-Z0-9_]+)/$']?
From the error message it would appear to me that a dictionary variable is required: {'slug': ''}' . Even if this supposition is correct, I am not sure what variable is being sought nor where. Additional, possibly relevant data: this is based on the https://tutorial.djangogirls.org/en/. Also attempting to include comments based on https://djangocentral.com/creating-comments-system-with-django/ and slugs based on https://medium.com/tech-insights/how-to-create-django-seo-friendly-url-using-slugs-fa2bbc098690. Code to date: Models.py from django.conf import settings from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from django.utils.text import slugify class PageSubject(models.Model): page_subject = models.CharField(max_length=200) class Meta: # Gives the proper plural name for class called subject verbose_name_plural = "Subjects" def __str__(self): return self.page_subject class Post(models.Model): author = models.ForeignKey(User, default=1, on_delete=models.SET_DEFAULT, related_name='blog_posts') date_added = models.DateTimeField(auto_now_add=True) page_subject = models.ForeignKey(PageSubject, verbose_name='PageSubject', default=1, on_delete=models.SET_DEFAULT) slug = models.SlugField(default='', editable=False, max_length=200, null = False) title = models.CharField(max_length=200, unique=True) content = models.TextField() def get_absolute_url(self): kwargs = { 'slug': self.slug } return reverse('post_detail', kwargs=kwargs) def save(self, *args, **kwargs): value = self.title self.slug = slugify(value, allow_unicode=True) super().save(*args, **kwargs) class Meta: ordering = ['-date_added'] def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey(Post, default=1, on_delete=models.SET_DEFAULT, related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() made_on = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) class Meta: … -
Some of my tools not working on my Heroku Website while working on localhost
I have developed my first Heroku website and I can successfully enter the website and use one of the tools I have coded but I can not use the two other tools. Every time that I click on those buttons, there writes "Application error". (All of the tools work on localhost) I call the tools by buttons directing the user to another page like: views.py : class Example(TemplateView): template_name = 'example.html' ... urls.py: urlpatterns = [ path('example', views.Example.as_view(), name='example'), ... I call the codes in the same way as seen, but why some of them work and some don't? -
how to make django post accept str rather than pk
I have relational DB and a file info to post in it. DB provides 3 entities holding ForeignKey in some attributes. Entities are: File, WorkFile and WorkFileStage. My issue is, when I post info of specific file, I must post on those endpoints, but e.g. WorkFile holds attribute file = ForeignKey(File) - it's an id filed. Which makes me POST all the File data, then GET it for acquring IDs, then POST on WorkFile with those IDs. THIS IS A LOT OF POSTINGGETINGITERATINGANDPROMISING (as my request are done with axios on react). What I've tried, is for POST data construct object with just a file=file_name, then search it in the DB on the django side and serialize.save(). But POST requiers pk rather than str for foreignKeys. With this though process I ended up with axios.post().then(axios.get().then(axios.post(then)))). Is there any easy/good practice way of doing it? -
ERROR : Microsoft Visual c++ 14.0 required, thrown while pip installing Numpy
While pip installing numpy version 1.19.2 (via pycharm) below error is thrown ERROR : Microsoft Visual c++ 14.0 required I have tried the workarounds given in the sites nothing seems to be working -
Django, views, when I import the model it won't take the method "objects"
I have done the makemigrations and the migrate and I see the tables created in postgresql, but the function in the view will not pick the .objects(all) method This is one snippet of the models class Donor(models.Model): thename = models.CharField(max_length=30, unique=False) city = models.CharField(max_length=30, unique=False) VIEWS from django.shortcuts import render from .models import Donor Create your views here. def index(request): list = Donor.objects.all() #The word objects gets highlighted bc it is not accepted as method return render(request, 'home.html', {'lista':thelist}) UPDATE: The refreshingg of the page won't happen will give error