Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
There are 34 other sessions using the database
I normally run tests like this: python manage.py test --keepdb path.to.MyTestCase This command is stuck, does nothing so I decided to run without --keepdb, I get the following error: Destroying old test database for alias 'default'...Got an error recreating the test database: database "test_myproject" is being accessed by other users DETAIL: There are 34 other sessions using the database. My assumption, my previous 34 test commands hang on the command line. What can I do at this point? -
Django models.CASCADE does not delete ForeignKey object
I'm trying to figure out why my Files objects are not getting deleted if I delete a Artist object. All models seemd to be related correctly class Artist(models.Model): objects = RandomManager() id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) title = models.CharField(verbose_name="Artist Title", blank=True, null=True, editable=False, unique=True, max_length=255) class Playlists(models.Model): objects = RandomManager() id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) class Files(models.Model): objects = RandomManager() id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) playlists = models.ForeignKey(Playlists, on_delete=models.CASCADE, verbose_name="Playlist", blank=True, null=True, db_index=True) backend = models.ForeignKey(Backend, on_delete=models.CASCADE, related_name='bafiles_relation', db_index=True) class MusicAlbums(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) artist = models.ForeignKey(Artist, on_delete=models.CASCADE, related_name='music_artist_relation', db_index=True) album_artist = models.ManyToManyField(through='AlbumArtist', to='Artist', db_index=True) backend = models.ForeignKey(Backend, on_delete=models.CASCADE, related_name='backend_music_album_relation', db_index=True) genre_relation = models.ManyToManyField(through='GenreMusicAlbum', to='Genre', db_index=True) class AlbumArtist(models.Model): artist = models.ForeignKey(Artist, on_delete=models.CASCADE, blank=False, null=False, db_index=True, related_name='album_artist_relations') album = models.ForeignKey(MusicAlbums, on_delete=models.CASCADE, blank=False, null=False, db_index=True) class Genre(models.Model): objects = RandomManager() id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) name = models.CharField(verbose_name="Genre", blank=True, null=True, editable=False, unique=True, max_length=255) class GenreMusicAlbum(models.Model): objects = RandomManager() music_album = models.ForeignKey(MusicAlbums, on_delete=models.CASCADE, blank=True) genre = models.ForeignKey(Genre, on_delete=models.CASCADE, blank=False, null=False) class MusicTracks(models.Model): objects = RandomManager() id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) file = models.ForeignKey(Files, on_delete=models.CASCADE, related_name='music_track_file_relation', db_index=True) artist = models.ForeignKey(Artist, on_delete=models.CASCADE, related_name='music_track_artist_relation', db_index=True) album = models.ForeignKey(MusicAlbums, on_delete=models.CASCADE, related_name='music_track_album_relation', db_index=True) class Backend(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, … -
Module of side-script, which is imported in django views.py can not find weights file with tensorflow's load_weights func
I have a django application, which contains activation an imported side-script from another project, when it gets an image file in POST-request. Side-script calls another script, which uses tensorflow function load_weights to load pre-trained weights and apply a super-resolution trained model to image, then i expect to return enchanced version of it in views.py and transfer back to html page in response. The problem, however, is that for some reason module of side-script can not find weights file (no such file or directory error), while if i run it directly (not calling from django project) it finds it perfectly fine. Does anyone have a solution? Error text: Unable to open file (unable to open file: name = 'weights/edsr-16-x4/weights.h5', errno = 2, error message = 'No such file or directory', flags = 0, o_flags = 0) Python version 3.7 tensorflow version 2.3.1 Django version 3.2.19 I have tried to move weights file to script's folder so it wouldn't be necessary to give it full path anymore, just a file name, but it did not work, so i can not figure any solution for now. P.S. couldn't figure out how to put multiple code blocks, so i put all three files in … -
how to add my function to values parameters?
I have a function 'is_recently' that checks how long the item I added has been hanging, and if 30 minutes have not passed yet, then write that it is recently on sale. I decided to optimize queries in the database, and I cannot add this function to the parameters of the values function, is it possible to do this at all? Forgive me in advance if I wrote with errors, I'm not English speaking. def index(request): data = ( Product .objects.select_related('category') .filter(is_on_main=True) .values('name','price','pk','date') ) Maybe there are some other functions? Or I don't understand something -
How to improve Django's collectstatic command performance in Docker?
I'm working on a Django project that's containerized using Docker, and I've noticed that the collectstatic command has very poor performance during the Docker image build process. The collectstatic command in Django works by comparing the timestamps of files from the source and destination. Based on this comparison, it determines whether a file should be copied, deleted and copied, or skipped. This behavior significantly affects the performance of the collectstatic command. I realized that the issue was due to the timestamps of my static files not being preserved during the Docker build process, causing collectstatic to perform unnecessary operations. Is there a way to preserve the original timestamps of my static files when building a Docker image for a Django application, and thereby improve the performance of the collectstatic command? -
How to web scrape an svg of site(Hackerrank) using Django [closed]
I want to scrape and display or store svg of the hackerrank website. Hackerrank robots.txt: User-agent: * Disallow: /x/tests/ Disallow: /x/interviews/ Disallow: /x/settings/ Disallow: /*download_solution$ Disallow: /tests/ Disallow: /work/embedview/ User-agent: AhrefsBot Disallow: / User-agent: MauiBot Disallow: / User-agent: ia_archiver Disallow: / User-agent: DuckDuckBot Crawl-Delay: 3 User-agent: Bingbot Crawl-Delay: 3 User-agent: YandexBot Crawl-Delay: 3 User-agent: MJ12Bot Crawl-Delay: 3 Sitemap: https://cdn.hackerrank.com/s3_pub/hr-assets/sitemaps/sitemap.xml.gz I tried using beautifulsoup but it only extracts the svgs tags and not the styles or the resources. I am willing to use other scraping software -
in my code send_bulkledger call many time ,but i called it only once
if main1['res']['message']['module']=='bulk_ledger_save': ledger_list=await self.save_bulk_ledger(main1) # returns a list print('6000') msgdict= {"msg":"bulk_legder_return","ledger_list": ledger_list} await self.channel_layer.group_send( self.room_group_name, { "type":"send_bulkledger", 'msg':msgdict }) async def send_bulkledger(self, event): print(event,'7000') data=event['msg'] await self.send(text_data=json.dumps({ "msg":data })) This code belongs to Django Channels While running above code 6000 is printing only once but 7000 is printing multiple times because of this getting data in frontend many times