Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Having issues with static file storage when deploying a django 4.2 project
I am having issues with deploying a django 4.2 project. When I push it to Heroku I get an application error that reads, "An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail." When I inspect the logs I believe the issue is boiling down to this, " django.core.exceptions.ImproperlyConfigured: STATICFILES_STORAGE/STORAGES are mutually exclusive." I believe I have done something wrong in my settings.py file as the tutorial I was watching used an older version of Django and there were updates made to the syntax on define storage in settings.py in this version of Django. However, I am confused because I am not using "STATICFILES_STORAGE" anywhere. I tried to follow along with the tutorial while also reading the new documentation to handle this correctly. I must have used some old syntax, but am unsure where I did that. Here is my settings.py from pathlib import Path import django_heroku import dj_database_url from decouple import config # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - … -
Difficulty in dealing with response from promise in React frontend
I'm having a hard time getting actual values from Django objects I created using API calls on the React frontend (and I believe my issue is with frontend). I'm trying to set an array to values from an API response to then be displayed on the frontend. I'm fairly new to this stuff so I apologize if I leave out something relevant It seems, based on console logs I've done, that an array I create to eventually use to display these things gets populated with something but not what I'm expecting. In my component I have this provisions array that I am referencing and use to display values on the frontend: this.state = { provisions: [], }; Next in the componentDidMount() method I call the method that will make the API call: componentDidMount() { this.provisionsRequest(); } and then the provisions request method: provisionsRequest(){ Api.getProvisions().then((resp) => { this.setState({ provisions: resp, }); }); } For the time being, I'm just checking the length of the provisions array, which happens to be 6. The issue though is that in the console log once I deploy the testing site, its an array of 6 'category' objects with null values: Array(6) 0: {category: null} 1: … -
Modifying a table in django admin panel by editing another table
I want to be able to delete some elements in a model after editing the name of a field and answering a question. This are my models: class Cursuri(models.Model): id_curs = models.CharField(max_length=50) titlu_curs = models.CharField(max_length=50) an = models.IntegerField() semestru = models.IntegerField() credite = models.IntegerField() class Meta: verbose_name_plural = "Cursuri" class Note(models.Model): nr_matricol = models.CharField(max_length=20) id_curs = models.CharField(max_length=50) valoare = models.IntegerField() data_notare = models.DateField(auto_now=False, auto_now_add=False) class Meta: verbose_name_plural = "Note" When i edit the name of the field "titlu_curs" i want to delete the elements from "Note" that have the same "id_curs" as the one modified in "Cursuri" I tried doing this: class CursuriAdmin(admin.ModelAdmin): list_filter = ("an","semestru","credite", ) list_display=("id_curs","titlu_curs","an","semestru","credite",) def change_view(self, request, object_id, form_url='', extra_context=None): if request.method == 'POST': new_name = request.POST.get('titlu_curs') old_name = Cursuri.objects.get(id=object_id).titlu_curs id_curs = Cursuri.objects.get(id=object_id).id_curs Cursuri.objects.get(id=object_id).titlu_curs=new_name if new_name != old_name: return render(request,'vizualizare/confirmare_subiect.html',context={ 'new_name': new_name, 'old_name': old_name, "id_curs":id_curs, } ) return super().change_view(request, object_id, form_url, extra_context) and this is the template: {% extends 'base.html' %} {% block content %} <form action="admin/vizualizare/cursuri/<int:pk>/change" method="POST"> {% csrf_token %} <h2>Is the new subject "{{ nume_nou }}" related to the previous subject "{{ nume_vechi }}"?</h2> <input type="submit" value="Yes, it is related" name="Yes"/> <input type="submit" value="No, it is not related" name="No"/> </form> {% endblock %} I … -
django saving the wrong time in database
so it's my how I updated my code: journal.update(**new_) and new_ is a dictionary with name of the fields which I want to update but when I set the dictionary something like: new_ = {'symbol': <Symbols: btc>, 'status': 'o', 'side': 'l', 'open_date': datetime.datetime(2023, 6, 1, 11, 52), 'entry_price': '995945994564156'} it's setting the wrong time on the database for this example it's setting it as 2023-06-01 08:22:00 which is -3:30 less than what I sent... the timezone I used is UTC+3:30 and it's the field in my Journal model: open_date = models.DateTimeField(default=timezone.localtime(timezone.now()), editable=False) I tried changign the format of the datetime but still didn't work... -
Django ModuleNotFoundError "django" module
I just started back in Django (so I am back from scratch) and now I'm trying the tutorials from Django for now and I am getting moduleError thingy. For some reason, I cannot import anything thru urls.py and I haven't found a way to resolve it. Is it in the local folder I created in project? or is there something that needs to be added to PATH (which I believe I already did)? Also if I check the terminal logs, it shows this relating to "django": Any suggestions how to make them work? -
Django ModelForm Validation: Is it a security risk to set an object field before validating the dependent form data
I have two questions regarding Django ModelForm validation behavior that has perplexed me. Issue 1: Manually Assinging Model Field Before Form Validation: I have a Listing model set up for an e-commerce app: Models.py from django.contrib.auth.models import AbstractUser from django.db import models from django.core.validators import MinValueValidator, DecimalValidator from decimal import Decimal class User(AbstractUser): pass class Listing(models.Model): CATEGORY_CHOICES = [ ("APPAREL", "Apparel"), ("COLLECTIBLES", "Collectibles"), ("COMICS", "Comics"), ("MEMORABILIA", "Sports Memorabilia"), ("SNEAKERS", "Sneakers"), ("TRADING_CARDS", "Trading Cards"), ("OTHER", "Other") ] title = models.CharField(max_length=80) description = models.CharField(max_length=800) starting_bid = models.DecimalField(max_digits=11, decimal_places=2,validators=[MinValueValidator(Decimal('0.00'))]) current_bid = models.DecimalField(default=0, max_digits=11, decimal_places=2,validators=[MinValueValidator(Decimal('0.00'))]) image = models.URLField(blank=True) category = models.CharField(max_length=40, choices=CATEGORY_CHOICES, blank=True) def __str__(self): return f"{self.title}" I am excluding current_bid from my ModelForm, as I am setting current_bid equal to the starting_bid value entered into the form by the user for each new Listing. Originally, I did this (per below) repeating the .save() command, which seemed to be a poor solution – though Django's docs does this in certain examples: views.py – Validating Form Before Manually Assigning Field def create_listing(request): class NewListingForm(ModelForm): template_name = "auctions/form_template.html" class Meta: model = Listing exclude = ["current_bid"] widgets = { "description": forms.Textarea(attrs={"placeholder": "Enter a description for your new listing..."}), "title": forms.TextInput(attrs={"placeholder": "Enter new listing title..."}), "starting_bid":forms.NumberInput(attrs={"placeholder": "Minimum … -
axios can't receive cookies from django
I have a Django API application deployed on AWS EC2 with the domain name 'https://example.xyz', and a React frontend application deployed on Netlify with the domain name 'https://example.com.tr'. In my backend application, I'm using the drf-social-oauth2 library to authenticate users with JWT and save their access_token and refresh_token in HTTP-Only cookies. When I post appropriate data to the 'https://example.xyz/api/users/login' endpoint, I can get the cookies. However, when I log in to my domain 'https://example.xyz' and send a post request to the 'https://example.xyz/api/users/login' endpoint via axios, I can't get the cookies. Everything was working smoothly on localhost before deploying. Is there anyone who can help me with this issue? Here is the code I have: Settings.py: ALLOWED_HOSTS = [ 'example.xyz', 'example.com.tr', ] # Cors Settings CORS_ALLOWED_ORIGINS = [ 'https://example.xyz', 'https://example.com.tr', ] CORS_ALLOW_CREDENTIALS = True CORS_EXPOSE_HEADERS = ['Content-Type', 'X-CSRFToken'] CORS_COOKIE_SAMESITE = None SESSION_COOKIE_SECURE = True SESSION_COOKIE_SAMESITE = None # CSRF Settings CSRF_COOKIE_SECURE=True CSRF_COOKIE_HTTP_ONLY=True CSRF_TRUSTED_ORIGINS = [ 'https://example.xyz', 'https://example.com.tr', ] CustomMiddleware.py class CookieAuthenticationMiddleware(MiddlewareMixin): def process_request(self, request): token = request.COOKIES.get('access_token') refresh = request.COOKIES.get('refresh_token') if not token and refresh: data = { 'grant_type': 'refresh_token', 'client_id': os.environ.get('MAIN_AUTH_KEY'), 'client_secret': os.environ.get('MAIN_AUTH_SECRET'), 'refresh_token': refresh } headers = { 'Content-Type': 'application/x-www-form-urlencoded', } response = requests.post('https://example.xyz/api/users/login/', data=data, headers=headers) if response.status_code == … -
Docker container running but not working on local port
When I run docker run -p 8000:8000 containername the container server runs but I can't access it on localhost:8000. This is my first experience using Docker and every fix I'm finding online hasn't worked for my very simple project. I used Django and this was Dockerfile that I found online. Dockerfile: FROM python:3 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt . RUN pip install -r requirements.txt COPY . . ENV PORT=8000 EXPOSE 8000 CMD ["python", "manage.py", "runserver"] For the docker-compose.yml file I wasn't sure what exactly to put so any tips would help. docker-compose.yml services: web: build: context: app target: builder ports: - '8000:8000' -
Automatic showing of objects on a website
so basically I have a table with 16 objects. I want to show only four of them on my website and want it to automatically rotate every week to another four and so on. I was thinking maybe a cronjob would do it, but I rather ask here before I take any action. Here is my models.py class Liturgicketexty(models.Model): id = models.AutoField(primary_key=True) text = models.CharField(max_length=45) url = models.URLField(max_length=200, blank=True, null=True) class Meta: verbose_name_plural = 'Liturgické texty' def __str__(self): return self.text and here is the part in html where I use this table. <div id="table"> <table> <thead> <tr> <th>Čtení na neděli</th> </tr> </thead> <tbody> {% for l in liturgicketexty %} <tr> <td><a href="{{ l.url }}">{{ l.text }}</a></td> </tr> {% endfor %} </tbody> </table> </div> If someone needs it. Like I said. I tried to research some solution, but found nothing promising. If you find or know something I will be more than grateful. -
Django database error when checking exist email on databese mongodb using djongo engine
I made a function to check if email is exist on database, but after accessing on browser with email that already exist in database it show database error but the connection with database isn't the problem. How to solve it? url: http://127.0.0.1:8000/api/check-email/?email=adrianbadjideh02@gmail.com error: DatabaseError at /api/check-email/ Request Method:GETRequest URL:http://127.0.0.1:8000/api/check-email/?email=adrianbadjideh02@gmail.comDjango Version:4.1.9Exception Type:DatabaseErrorException Location:C:\Users\xdead\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\djongo\cursor.py, line 81, in fetchoneRaised during:UserApps.views.check_emailPython Executable:C:\Users\xdead\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\python.exePython Version:3.11.3Python Path:['D:\\api_enchant', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.11_3.11.1008.0_x64__qbz5n2kfra8p0\\python311.zip', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.11_3.11.1008.0_x64__qbz5n2kfra8p0\\DLLs', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.11_3.11.1008.0_x64__qbz5n2kfra8p0\\Lib', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.11_3.11.1008.0_x64__qbz5n2kfra8p0', 'C:\\Users\\xdead\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\\LocalCache\\local-packages\\Python311\\site-packages', 'C:\\Users\\xdead\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\\LocalCache\\local-packages\\Python311\\site-packages\\win32', 'C:\\Users\\xdead\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\\LocalCache\\local-packages\\Python311\\site-packages\\win32\\lib', 'C:\\Users\\xdead\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\\LocalCache\\local-packages\\Python311\\site-packages\\Pythonwin', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Pyt This is my code: #views.py from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from rest_framework.parsers import JSONParser from django.http.response import JsonResponse from UserApps.models import Users from UserApps.serializers import UserSerializer # Create your views here. @csrf_exempt def userApi(request, id=0): if request.method == 'GET': users = Users.objects.all() user_serializer = UserSerializer(users, many=True) return JsonResponse(user_serializer.data, safe=False) elif request.method == 'POST': user_data = JSONParser().parse(request) user_serializer = UserSerializer(data=user_data) if user_serializer.is_valid(): user_serializer.save() return JsonResponse("Added Successfully", safe=False) return JsonResponse("Failed to Add", safe=False) elif request.method == 'PUT': user_data = JSONParser().parse(request) user = Users.objects.get(userid=user_data['userid']) # Updated here user_serializer = UserSerializer(user, data=user_data) if user_serializer.is_valid(): user_serializer.save() return JsonResponse("Updated Successfully", safe=False) return JsonResponse("Failed to Update", safe=False) elif request.method == 'DELETE': user = Users.objects.get(userid=id) # Updated here user.delete() return JsonResponse("Deleted Successfully", safe=False) @csrf_exempt def get_user(request, … -
How to display selected choices from a field of a Django ModelForm, on the basis of attribute value of choice object?
As part of a Django web app, I am working on a page that would show the user a list of jobs that can be filtered by category and/or subcategory. Each category has several subcategories, each subcategory has only one category. A job can have several categories/subcategories. So, the idea is to get a filtering form that looks like in the image below: Below is what I have tried so far. In models.py: class Category(models.Model): name = models.CharField(max_length=30, default='') class Meta: verbose_name_plural = u'categories' def __str__(self): return self.name class Subcategory(models.Model): name = models.CharField(max_length=30, default='') category = models.ForeignKey(Category, null=True, on_delete=models.SET_NULL) class Meta: verbose_name_plural = u'subcategories' def __str__(self): return self.name class Job(models.Model): title = models.CharField(max_length=150, null=True, blank=True) categories = models.ManyToManyField(Category, null=True, blank=True) subcategories = models.ManyToManyField(Subcategory, null=True, blank=True) def __str__(self): return self.title In forms.py: class JobModelForm(forms.ModelForm): class Meta: model = Job fields = ['categories', 'subcategories'] widgets = {} for field in fields: widgets[field] = forms.CheckboxSelectMultiple In HTML template: Method 1: <form method="get"> {% csrf_token %} {% for category in form.categories %} <div> {{ category }} {% for subcategory in form.subcategories %} <div style="text-indent: 2em"> {{ subcategory }} </div> {% endfor %} </div> {% endfor %} <input type="submit" value="Search"> </form> Because the subcategories are … -
How to make a checkbox inside ModelMultipleChoiceField filled depending on the value in the DB Django
The Plugins model contains information about existing plugins. The UserPlugins model contains summary information about which user has which plugins activated, the activation of the user's plugins depends on the isActive field. IisActive field has the value True or False, depending on whether the user has activated the plugin or not. How do I change the checkbox value to checked in ModelMultipleChoiceField if isActive is True in the DB? models.py class Plugin(models.Model): plugin_name = models.CharField(null=False, blank=True) plugin_description = models.TextField(null=True, blank=True) isDisplay = models.BooleanField(default=True) def __str__(self) -> str: return f"{self.plugin_name}" class UserPlugins(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) plugins = models.ForeignKey(Plugin, on_delete=models.CASCADE) isActive = models.BooleanField(default=True) forms.py class UserPluginForm(forms.Form): model = UserPlugins fields = ['plugins', 'isActive'] plugins = forms.ModelMultipleChoiceField( queryset=Plugin.objects.all(), widget=forms.CheckboxSelectMultiple(), ) I tried using initial in views, but in the end nothing worked. When going to another page and returning back, the values are reset views.py def userPluginsSettings(request): form = UserPluginForm(request.POST, initial={ 'plugins': [idx for idx in UserPlugins.objects.all()] }) if request.POST.get('plugins'): plugins_id_list = request.POST.getlist('plugins') plugins = UserPlugins.objects.all() for plugin in plugins: if str(plugin.plugins_id) in plugins_id_list: plugin.isActive = True else: plugin.isActive = False plugin.save() context = {'form':form} return render(request, "profile/plugin_list.html",context) template.html <form method="POST" class="home_main_unit" style="flex-direction:column;"> {% csrf_token %} {{ form.plugins }} <input type="submit" name="submit_btn" … -
NoReverseMatch at / Reverse for 'story' with keyword arguments '{'id': ''}' not found. 1 pattern(s) tried: ['story/(?P<id>[0-9]+)\\Z']
I'm getting this error: NoReverseMatch at / Reverse for 'story' with keyword arguments '{'id': ''}' not found. 1 pattern(s) tried: ['story/(?P<id>[0-9]+)\\Z'] For this line in my template: . When I am trying to print it to the screen ({{ subject.list.0.id }}) it prints the id without any problem, but for some reason when I am trying to pass it here <a href="{% url 'story' id=subject.list.0.id %}">, it doesn't work. the url: path("story/<int:id>", views.story, name="story"), the view: def story(request, id): story = Story.objects.get(id=id) last_post = story.posts.all()[::-1][0] return render(request, "story.html", { "posts": story.posts.all(), "deadline": last_post.deadline, }) The page view: def index(request): user = User.objects.get(id=request.user.id) user_genre = user.genres.all() stories = [{'list': Story.objects.order_by("-likes").all()[0:20], 'popular': 'true'}, {'list': Story.objects.all()[::-1][:20], 'new': 'true'}, ] for genre in user_genre: stories.append({'list': Story.objects.filter(genres=genre)[0:20], "genre": genre}) print(stories) return render(request, "homepage.html", { "genres": Genre.objects.all(), "user": User.objects.get(id=request.user.id), "stories": stories }) *The 'subject' in the homepage template is from {% for subject in stories %}. What can be the problem? What am I missing? I will appreciate any help! -
Reverse for 'post_comment' with keyword arguments '{'kwargs': {'pk': 1}}' not found. 1 pattern(s) tried: ['post/(?P<pk>[0-9]+)/\\Z']
I have this comment section that allows users to comment, but the problem I have is that I want users to stay on the same page after commenting. And that is giving me a headache about how to go about it. I wanted to redirect using 'post-detail," but because I have a slug in there, it doesn't work. The second option is to use "post_comment," and this is the error I'm getting. I need to redirect either by using post-detail or post_comment. views.py class PostDetailView(DetailView): """ show the detail of a specific post """ model = Post template_name = 'blog/post_detail.html' slug_field = 'slug' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['author'] = lowercase_first_name(self.object.author) context['tags'] = self.object.tags.all() # context['comments'] = self.object.comment.all() context['comments'] = Comment.objects.filter(blog=self.object) context['pk'] = self.kwargs.get('pk') return context def post_comment(request, pk): blog = Post.objects.get(pk=pk) comment = Comment( user_comment=request.user, comment =request.POST['comment'], blog=blog) comment.save() return redirect('post_comment', kwargs={'pk': pk}) urls.py urlpatterns = [ path('', views.post_list, name='home'), path('<author_slug>/<slug:slug>/<int:pk>/', views.PostDetailView.as_view(), name='post-detail'), path('post/<int:pk>/', views.post_comment, name='post_comment'), ] -
how to condition use with field in django using python
Why does it not ap class opportunity(models.Model): lead_id = models.AutoField(primary_key=True) title = models.CharField(max_length=200) TYPE_CHOICES = [ ('...', '...'), ('Individual', 'Individual'), ('Company', 'Company'), ] type = models.CharField(max_length=20, choices=TYPE_CHOICES, default='...') if type == 'Individual': name = models.CharField(max_length=200) elif type == 'Company': Company = models.CharField(max_length=200) pear field based on the selection? nothing showed up Is the condition correct? -
Static files such as videos and images take time to load in production
The video and images loaded faster when I opened the website in the local server. After hosting it, the video in the homepage takes time to load and the images retrieved from the database also take time to load. I have used AWS light sail to host the website on the internet. Please let me know what I can do to load the video and images faster when the user opens the website. I have followed the steps to load the static files in django, but the load time is very slow. -
Django with SQLAlchemy
can someone tell me why i am getting this error when importing my models in django? django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. i dont know what to register in my installed_apps section. i created a new project and registered it like this INSTALLED_APPS = [ 'smashbook.apps.SmashbookConfig', ... ] i import my models like this: from models import players i have a python file "mockdata.py" which i want to use to fill my postgresql database with data using sqlalchemy. can anyone help me? Thanks in advance! -
How to make your own pagination Django
I have some json data from 3rd party API which has params like 3rd_party.com/API?NumberOfItemsOnPage=5&PageNumber1 NumberOfItemsOnPage - how many items will be on one page and PageNumber - current page. This json has items, info about current page, how many items on page and how many pages in general And i want to know how can i paginate trough that json using paginate_by in class ListView class myView(ListView) paginate_by = 5 def get_queryset(self, ...): queryset = [] page_number = self.request.GET.get('page') request = f'3rd_party.com/API?NumberOfItemsOnPage=5&PageNumber{page_number}' <- this might be wrong but i doesnt rly care bcs i need to know how to paginate using default django pagination queryset = request.json() return queryset I guess i need to override django Paginator class but i dont know how to do that bcs django paginator paginates will trough only first page and wont get anothers -
How to set codemirror to highlight multiple languages in Django admin?
For one of my pet projects, I needed to use syntax highlighting for one of the TextField fields. Codemirror is great for this. After trying several “django-batteries” with widgets, I decided to abandon external dependencies and install codemirror myself. Models have TbTemplate with fields for describing templates. From there, the backend takes templates for rendering, and the TextField itself with the template is szJinjaCode. I do it like this. admin.py: class TemplateAdminForm(forms.ModelForm): class Meta: model = TbTemplate fields = "__all__" widgets = { 'szJinjaCode': forms.Textarea(attrs={'class': 'jinja2-editor'}) } # Template admin @admin.register(TbTemplate) class AdminTemplate(admin.ModelAdmin): class Media: # set for codemirror ON css = { 'all': ( # '/static/codemirror-5.65.13/doc/docs.css', '/static/codemirror-5.65.13/lib/codemirror.css', '/static/codemirror-5.65.13/addon/hint/show-hint.css', '/static/codemirror-5.65.13/addon/lint/lint.css', '/static/codemirror-5.65.13/theme/rubyblue.css', ) } js = ( '/static/codemirror-5.65.13/lib/codemirror.js', '/static/codemirror-5.65.13/addon/hint/show-hint.js', '/static/codemirror-5.65.13/addon/hint/xml-hint.js', '/static/codemirror-5.65.13/addon/hint/html-hint.js', '/static/codemirror-5.65.13/mode/xml/xml.js', '/static/codemirror-5.65.13/mode/javascript/javascript.js', '/static/codemirror-5.65.13/mode/css/css.js', '/static/codemirror-5.65.13/mode/htmlmixed/htmlmixed.js', '/static/codemirror-5.65.13/mode/jinja2/jinja2.js', # '/static/codemirror-5.65.13/addon/runmode/colorize.js', # '/static/codemirror-5.65.13/addon/hint/html-hint.js', # '/static/codemirror-5.65.13/addon/lint/lint.js', # '/static/codemirror-5.65.13/addon/lint/html-lint.js', '/static/js/codemirror/init_jinja2.js' ) # set form TemplateAdminForm form = TemplateAdminForm # other description for admin TbTemplate # ... # ... As you can see from the code, you also need to run the initialization file /static/js/codemirror/init_jinja2.js into statics-files. Actually, he took from the recipe and changed it a little: /static/js/codemirror/init_jinja2.js (function(){ var $ = django.jQuery; $(document).ready(function(){ $('.jinja2-editor').each(function(idx, el){ function getSelectedRange() { return { from: editor.getCursor(true), to: editor.getCursor(false) }; … -
Want to create folder in Django...the user wants to create subfolders
`In my Django Application....I want to create an directory in that directory I want to create an subdirectory in that particular subdirectory I want to create another subdirectory like that the user how long wants like that they want to create an directory Example Code in Django` -
Why does Heroku search inside '/app/static' and not in the folder 'static'?
Context I'm deploying a project through Heroku and I get the following warning: ?: (staticfiles.W004) The directory '/app/static' in the STATICFILES_DIRS setting does not exist. This happens I run the command heroku run python manage.py migrate . Note: I don't get this warning when I try to migrate locally. Only while deploying, which I can actually do. Question I don't understand why Heroku is searching under '/app/static' when I specify in the settings.py file STATICFILESDIRS = [BASE_DIR / "static"]. Code My 'django/settings.py' file looks like this: # django_project/settings.py INSTALLED_APPS = [ ... "whitenoise.runserver_nostatic", "django.contrib.staticfiles", ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", ... ] STATIC_URL = "/static/" STATICFILES_DIRS = [BASE_DIR / "static"] STATIC_ROOT = BASE_DIR / "staticfiles" This is my file tree. ├── .env ├── .gitignore ├── .venv ├── accounts │ ├── __init__.py │ ├── __pycache__ │ ├── admin.py │ ├── apps.py │ ├── migrations │ ├── models.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── django_project │ ├── __init__.py │ ├── __pycache__ │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── db.sqlite3 ├── manage.py ├── Procfile ├── requirements.txt ├── runtime.txt ├── static │ ├── css │ └── js ├── staticfiles │ └── admin │ … -
Calling .env variables in a JS script in a Django template
I have my following credentials stored in a .env file: #Google Drive API GOOGLE_DRIVE_API_KEY='XX' GOOGLE_DRIVE_API_CLIENT_ID='XX.apps.googleusercontent.com' GOOGLE_DRIVE_APP_ID='XX' In my Django template, I would like to call these variables to initiate the Google Drive File Picker: <script> var API_KEY = 'xx'; var CLIENT_ID = 'xx.apps.googleusercontent.com'; var APP_ID = 'xx'; // Scope to use to access user's Drive items. var SCOPES = 'https://www.googleapis.com/auth/drive'; </script> Since it's absolutely not secure to put these credentials directly inside the JS script, do you know how I can call these credentials (like os.getenv() in Python)? -
How to filter one model by another if it doesnt have relation
I have 2 models and model ObjectList has m2m field to CounterParty but i need to show info from CounterParty model filtered by object How am i suppose to do it? class CounterParty(models.Model): name = models.CharField(max_length=150, verbose_name='Наименование') class ObjectList(models.Model): name = models.CharField(max_length=250, verbose_name='Наименование') contractor_guid = models.ManyToManyField(CounterParty, related_name='object_contractor',default=None, blank=True) I know this is not right but it should look like this object = ObjectList.objects.get(id=1) a = CounterParty.objects.filter(object_contractor=object) -
Websocket issue in Python Django
The console shows that the websocket is connected in the inbox, but the real-time notification is not received import json from channels.generic.websocket import AsyncWebsocketConsumer from channels.db import database_sync_to_async from .models import ChatRoom, Message, Notification from django.contrib.auth import get_user_model from asgiref.sync import async_to_sync from channels.layers import get_channel_layer class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] formatted_timestamp = await self.save_message(message) await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message, 'sender': self.scope['user'].username, 'formatted_timestamp': formatted_timestamp, } ) async def chat_message(self, event): message = event['message'] sender = event['sender'] formatted_timestamp = event['formatted_timestamp'] await self.send(text_data=json.dumps({ 'message': message, 'sender': sender, 'formatted_timestamp': formatted_timestamp, })) @database_sync_to_async def save_message(self, message): chat_room = ChatRoom.objects.get(name=self.room_name) sender = self.scope['user'] new_message = Message(chat_room=chat_room, sender=sender, content=message) new_message.save() formatted_timestamp = new_message.formatted_timestamp() participants = chat_room.participants.exclude(id=sender.id) for participant in participants: notification = Notification(user=participant, chat_room=chat_room, message=new_message) notification.save() return formatted_timestamp @database_sync_to_async def get_or_create_room(self, user_ids): users = get_user_model().objects.filter(id__in=user_ids) chat_room = ChatRoom.get_or_create_chat_room(users) return chat_room class NotificationConsumer(AsyncWebsocketConsumer): async def connect(self): print("NotificationConsumer Connected") print('connected') print(self.scope['user'].username) self.room_group_name = '%s_notifications' % self.scope['user'].username print(self.room_group_name) await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard( self.room_group_name, … -
Unable to change password in Django with custom user model
I have been trying to get the default Django authentication system to work with custom users. I am able to create the user types, login and logout. However, when it comes to changing the password, I get logged out and then the password is not changed. I also tried to see if by resetting the password through email anything would change, yet I still can't change the password. My app name is account. This is my custom user model, I tried adding the set_password method to make sure it could change the password. I have removed the managers for readability : class CustomUser(AbstractUser): username = None email = models.EmailField(_("email address"), unique=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = [] objects = UserManager() def set_password(self, raw_password): self.password = make_password(raw_password) self._password = raw_password class Student(CustomUser): student = StudentManager() class Meta: proxy = True class Teacher(CustomUser): teacher = TeacherManager() class Meta: proxy = True For the rest I use all the default Django authentication urls and views but i have tried modifying the password change view to make sure I don't log out, however the issue persists : urlpatterns = [ path('password_change/', CustomPasswordChangeView.as_view(), name='password_change') path('', include('django.contrib.auth.urls')), ] CustomPasswordChangeView : class CustomPasswordChangeView(auth.views.PasswordChangeView): template_name = "registration/password_change_form.html" success_url …