Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django SearchVector
Django SearchVector is giving ok results in command line but it is not working on my localhost:8000. Here's how I put it. def post_search(request): form = SearchForm() query = None results = [] if 'query' in request.GET: form = SearchForm(request.GET) if form.is_valid(): query= form.cleaned_data['query'] results = Post.objects.annotate(search=SearchVector('title', 'body', 'slug')).filter(search='query') context = { 'form' : form, 'query' : query, 'results' : results } return render(request, 'blog/search.html', context) -
UniqueViolation (celery-beat) and DuplicateTable (celery) errors with django_migrations using django/postgresql/celery/celery-beat with DOCKER
I develop a Django app and try to implement asynchronous task for dbbackup stack: django/postgresql/celery/celery-beat and DOCKER (only postgresql is not in a container) I am new with celery and celery-beat When run my project, I have 2 errors with celery and celery-beat I do not understand traces: ... celery-beat_1 | psycopg2.errors.UniqueViolation: ERREUR: la valeur d'une clé dupliquée rompt la contrainte unique « pg_type_typname_nsp_index » celery-beat_1 | DETAIL: La clé « (typname, typnamespace)=(django_migrations_id_seq, 2200) » existe déjà. ... celery_1 | psycopg2.errors.DuplicateTable: ERREUR: la relation « django_migrations » existe déjà celery-beat_1 | django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (ERREUR: la valeur d'une clé dupliquée rompt la contrainte unique « pg_type_typname_nsp_index » celery-beat_1 | DETAIL: La clé « (typname, typnamespace)=(django_migrations_id_seq, 2200) » existe déjà. but all migrations seems to be running correctly for django web app container I try to drop postgresql database before building and running containers so I do not understand how django_migrations table could already exist probably dependencies between containers I set all containers depending of redis version: '3.7' services: web: restart: always container_name: web build: context: ./app dockerfile: Dockerfile.dev restart: always command: python manage.py runserver 0.0.0.0:8000 volumes: - ./app:/usr/src/app ports: - 8000:8000 env_file: - ./.env.dev depends_on: - … -
ImportError: DLL load failed: A dynamic link library (DLL) initialization routine failed; TensorFlow
I'm trying to make an ai that detects object with the help of this(https://gilberttanner.com/blog/tensorflow-object-detection-with-tensorflow-2-creating-a-custom-model) link and I ran into a problem when I finished the installation and was checking for errors using the code python object_detection/builders/model_builder_tf2_test.py My system: Windows 10 Python 3.7.0 TensorFlow 2.4.0 Output: Traceback (most recent call last): File "C:\Users\admin\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 64, in <module> from tensorflow.python._pywrap_tensorflow_internal import * ImportError: DLL load failed: A dynamic link library (DLL) initialization routine failed. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "object_detection/builders/model_builder_tf2_test.py", line 21, in <module> import tensorflow.compat.v1 as tf File "C:\Users\admin\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\__init__.py", line 41, in <module> from tensorflow.python.tools import module_util as _module_util File "C:\Users\admin\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\__init__.py", line 39, in <module> from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow File "C:\Users\admin\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 83, in <module> raise ImportError(msg) ImportError: Traceback (most recent call last): File "C:\Users\admin\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 64, in <module> from tensorflow.python._pywrap_tensorflow_internal import * ImportError: DLL load failed: A dynamic link library (DLL) initialization routine failed. -
best way to implement ManyToManyField check?
Want to create a Song object. How do I check if this Song object is in a particular user's UserProfile to avoid repetition? tried this but threw me an error argument of type 'QuerySet' is not iterable; songs_available = user.userprofile.liked_songs.all() if not song in songs_available: user.userprofile.liked_songs.add(song) models.py class Song(models.Model): track_name = models.CharField(max_length=250) artiste_name= models.CharField( max_length=200) album = models.ForeignKey(Album, on_delete= models.CASCADE, null=True, default=None, related_name = "songs") class Meta: db_table="Song" def __str__(self): return self.track_name class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, default=None , null= True) liked_songs = models.ManyToManyField("Song", null=True , default=None, related_name="users_that_liked_me") class Meta: db_table = "UserProfile" def __str__(self): return self.user.username views.py (part of it) song, created = Song.objects.get_or_create(track_name = track, artiste_name = artist, album = album) wanted to try if created but that only checks for the song model as many users could have the same song, it doesnt really help -
“ProgrammingError at / relation ”posts_post“ does not exist LINE 1: …evious_post_id”, “posts_post”.“next_post_id” FROM “posts_pos…”
I just finished writing a blog app with django which works perfectly locally but on deploying, I'm getting this error "OperationalError at / no such table: posts_post". After installing postgres, the error message changed to "ProgrammingError at / relation "posts_post" does not exist LINE 1: ...evious_post_id", "posts_post"."next_post_id" FROM "posts_pos..." Please what can I do? -
How do I load a youtube video iframe for every video in my django template?
When I load the youtube iframe as seen below, it loads every video: {% for topic in topics %} <div id="video_player" class="col-lg-4 col-md-6 mb-4" style="float: left;"> <div id="player" > <iframe width="100%" height="300px" src="https://www.youtube-nocookie.com/embed/{{ topic.video_id }}?enablejsapi=1&controls=1" frameborder="0"></iframe> </div> <div class="container"> <a href="{% url 'blog:topic' topic.id %}"><h5 class="border-bottom mb-1">{{topic.title}} </h5> </a> <small><h5 class="border-bottom mb-1">{{ topic.category }}</h5> | {{ topic.date_created}}</small> <p>{{ topic.content|safe|slice:"0:80" }}...</p> </div> </div> {% endfor %} But when I use the Youtube Iframe API as seen below, it only loads the first video and does not load the rest: <script> // 2. This code loads the IFrame Player API code asynchronously. var tag = document.createElement('script'); tag.src = "https://www.youtube.com/iframe_api"; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); // 3. This function creates an <iframe> (and YouTube player) // after the API code downloads. var player; function onYouTubeIframeAPIReady() { player = new YT.Player('player', { height: '300', width: '100%', videoId: '{{ topic.video_id }}', events: { 'onReady': onPlayerReady, 'onStateChange': onPlayerStateChange } }); } // 4. The API will call this function when the video player is ready. function onPlayerReady(event) { event.target.playVideo(); } // 5. The API calls this function when the player's state changes. // The function indicates that when playing a video (state=1), // the player … -
Not able to change values in hidden fields
I created a ModelForm in Django and I am having an issue in adjusting the values in some hidden fields. The basic process goes: User fills out form The View looks at the Boolean values and if one is True, then a value is placed in the corresponding field before saving. or, that is what SHOULD be happening. What is happening is that it seems that I am not writing to the hidden fields when the Boolean fields are True in the views.py file. Here is my models.py file information: class ruck_logs(models.Model): date_performed = models.DateField(auto_now=False,auto_now_add=False) rucker_name = models.CharField(max_length=30) ruck_miles = models.PositiveIntegerField() coupon = models.BooleanField() pt = models.BooleanField() ruck_WO_only = models.BooleanField() coupon_multiplyer = models.PositiveIntegerField(default=0) pt_multiplyer = models.PositiveIntegerField(default=0) ruck_workout_multiplyer = models.PositiveIntegerField(default=0) Here is my forms.py information: from django.forms import ModelForm from datalogger.models import ruck_logs from django import forms class DateInput(forms.DateInput): input_type = 'date' class RuckLogsModelForm(ModelForm): class Meta: model = ruck_logs widgets = {'date_performed' : DateInput(), 'coupon_multiplyer' : forms.HiddenInput(), 'pt_multiplyer' : forms.HiddenInput(), 'ruck_workout_multiplyer' : forms.HiddenInput()} fields = ['date_performed', 'rucker_name', 'ruck_miles', 'coupon', 'pt', 'ruck_WO_only', 'coupon_multiplyer', 'pt_multiplyer', 'ruck_workout_multiplyer'] Here is my views.py file information: def rucklogs(request): if request.method == 'POST': form = RuckLogsModelForm(request.POST) if form.is_valid(): ruck_miles = form.cleaned_data.get("ruck_miles") coupon = form.cleaned_data.get("coupon") pt = form.cleaned_data.get("pt") ruck_WO_only … -
Django ORM annotate performance
I'm using Django and Django REST Framework at work and we've been having some performance issues with couple endpoints lately. We started by making sure that the SQL part is optimized, no unnesecary N+1 queries, indexes where possible, etc. Looking at the database part itself, it seems to be very fast (3 SQL queries total, under a second), even with larger datasets, but the API endpoint still took >5 seconds to return. I started profiling the Python code using couple different tools and the majority of time is always spent inside the annotate and set_group_by functions in Django. I tried Googling about annotate and performance, looking at Django docs, but there's no mention of it being a 'costly' operation, especially when used with the F function. The annotate part of the code looks something like this: qs = qs.annotate( foo_name=models.F("foo__core__name"), foo_birth_date=models.F("foo__core__birth_date"), bar_name=models.F("bar__core__name"), spam_id=models.F("baz__spam_id"), spam_name=models.F("baz__spam__core__name"), spam_start_date=models.F("baz__spam__core__start_date"), eggs_id=models.F("baz__spam__core___eggs_id"), eggs_name=models.F("baz__spam__eggs__core___name"), ) qs = ( qs.order_by("foo_id", "eggs_id", "-spam_start_date", "bar_name") .values( "foo_name", "foo_birth_date", "bar_name", "spam_id", "spam_name", "eggs_id", "eggs_name", ) .distinct() ) The query is quite big, spans multiple relatonships, so I was sure that the problem is database related, but it doesn't seem to be. All the select_related and prefetch_related are there, indexes too. I … -
Where to store media files of Django app in order to save them after docker container updating?
I have a Django app where media files are uploading to the my_project_directory/media/images/ (so nothing special, just a common approach). The problem raised after dockerizing my app. Every time i need to update my container after pulling latest docker image, old container is removed(including, of course media files) and the new, empty one is built. So the question is - how to make my Django app stateless and where/how to store media files? Is it possible to store them in a special docker container? If yes, how? if no, what could you suggest? -
DJANGO: How to Render swagger-codegen model objects instead of database model object
I have an existing Django project in which I am trying to separate the backend and frontend of an existing webapp. The idea is to expose the backend functions as a rest api and then also build a webapp that allows users to interact with the api functionality in a graphical way. The api exposes a swagger/openapi document and I have used swagger codegen to generate a client to intereact with that. as a proof of concept I am trying to reimplement a view that used database object directly with one that calls the api to do the same functionality here is the original view def load_mapping_metadata_only_operations(request): mapping_operation_list = MappingOperation.objects.using('metadata') print(mapping_operation_list[1]) context = { 'mapping_operation_list': mapping_operation_list, 'transformation_list': [], 'source_table_list': [], 'destination_table_list': [], } x = render(request, 'migration_core/migation_tool.html', context) print(x.content) return x and here is the view that I am now trying to replace it with. def load_mapping_metadata_only_operations(request): try: mapping_operation_response = api_instance.find_models_by_name() except ApiException as e: print("Exception when calling MappingApi->find_models_by_name: %s\n" % e) print(mapping_operation_response[1]) api_response_dict = context = { 'mapping_operation_list': mapping_operation_response, 'transformation_list': [], 'source_table_list': [], 'destination_table_list': [], } x = render(request, 'migration_core/migation_tool.html', context) print(x.content) return x this is the template that the list is sent to: <li class="nav-item"> <select class="selectpicker mr-sm-2" … -
Why do all fieldset objects have "collapse" class in django admin?
I have a fieldset defined in django admin and it looks as following fieldsets = ( (_('order'), { 'classes': ('col',), 'fields': ('ManualName', ) }), (_('Payment'), { 'classes': ('col',), 'fields': ('name',), }), (_('Delivery'), { 'classes': ('col',), 'fields': ( 'partnumber', 'ean',), }), (_('Gift'), { 'classes': ('col',), 'fields': ('GiftShortDescString', ), }), ) for some reason, instead of displaying in blocks next to each other (as they do in admin for another model) these still display as if they had 'classes': ('collapse',), . The behaviour is the same even if they have no classes eg fieldsets = ( (_('order'), { 'fields': ('ManualName', ) }), would still display collapsed. It behaves like there was the collapse class added by default which moreover overrides all the other specified classes which blows my mind. I hard reloaded the page and tried different browsers. Any hint would be much appreciated -
Django REST Framework API schema generation with same URL prefix
I'm documenting my Django application using get_schema_view() method, but when I open the Swagger UI all the URLs are placed under the same group. My urls.py look like: router = routers.DefaultRouter() router.register(r'stores', StoreViewSet) urlpatterns = [ path('admin/', admin.site.urls), path('api/', include(router.urls)), path('api/register/', UserRegistrationView.as_view(), name='register'), path('api/login/', views.obtain_auth_token, name='login'), # Documentation path('openapi/', get_schema_view( title='Title API', description='Some description goes here...', version='v0.1' ), name='openapi-schema'), path('docs/', TemplateView.as_view( template_name='documentation.html', extra_context={'schema_url': 'openapi-schema'} ), name='docs') ] All the endpoints are placed under a group called api in the Swagger UI. How can I specify the api/ prefix while generating the schema in order to group the endpoints by model? Thanks. -
How to Query data from MySQL database after updating Django model field in Django
After updating posts model field in MySQL database using using Django framework, I'm unable to query posts from the Database. Whenever I run the command python manage.py runserver, all seems to be well with the server. However, when enter the post url to display the list of posts I uploaded on the database before updating the model field, I get 1054, "Uknown column 'start_post.author_id' in the 'field list' I have spent a couple of hours try to figure out why I'm getting the error but I still don't get it. In model.py I had: title = models.CharField () preamble: models.Charfield () body = models.TextField() •••• I updated the above model to: title = models CharField () author = models.ForeignKey(User, on_delete=models.CASCADE) introduction = models.charfield () body = models.TextField() •••• Before updating it everything was working appropriately. But after updating it I'm unable to access the list of posts on browser, from the url start\ as well as the post detail page. I didn't have the author field in the first model but I added it to the updated model. What can I do to solve this problem? -
How to store bitcoin and USD on the same django models field?
To store USD I am using DecimalField: amount = models.DecimalField( max_digits=12, decimal_places=2, ) But what if I want to store bitcoins? Bitcoin's minimal thing is satoshi. One bitcoin = million satoshi. I have 2 options: using DecimalField with decimal_places=6 or using an IntegerField. But I do not want to have a sepperate field for storing this. Is there any way to organize storing bitcoin and USD in the same field? -
how to add a field to models
I have a question of how to inherit a field from the model and display it in the admin panel (and manage it). I am using django-avatar app. Also i have a profile model(not relevant to django-avatar): class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) def __str__(self): return f'{self.user.username} Profile' How can I add an avatar field to the profile model so that in the admin panel in the user's 'profile' section, I can see the avatar for this user? I would be grateful for any help -
probelm at installing channels(django), and importing it's inner packages(channels.layout)
I have the same problem. pyhton(3.9.1). using virtual environmnet (venv). installed django. updated: setuptools: pip install --upgrade setuptools, pip(20.3.3): py -m pip install --upgrade pip wheel: python -m pip install --upgrade pip setuptools wheel (latesed version for today(30/12/20)). Tried to use: python -m pip install -U channels. installed "Microsoft Visual C++ Build Tools" Tried the self installing twisted: https://www.lfd.uci.edu/~gohlke/pythonlibs/#twisted All done, but still not working. Also tried pip install: pip install pytype pip install django-channels. The django-channels, but when runnig on PyCharm, it recognize channels but not: channels.layers. Can anyone help? -
How can I serialize list of booleans in django rest framework serializer?
I'm using Django Rest Framework and I want my data to be stored like this: 'days': [True, True, False, True, False, False, False] as one of the returned fields. I would like to have a seriaizer: class HistorySerializer(serializers.Serializer): days = serializers.BooleanField(many=True) , but serializers.BooleanField doesn't have 'many' argument. I've tried doing this: class DaysListField(serializers.ListField): day = serializers.BooleanField() class HistorySerializer(serializers.Serializer): days = DaysListField() , but it produces: 'days': [{'day': True}, {'day': True}, {'day': False}, {'day': False}, {'day': False}, {'day': False}, {'day': False}]. I also tried doing this: class HistorySerializer(serializers.Serializer): days = serializers.SerializerMethodField() def get_days(self, obj) -> List[bool]: return obj.days but Swagger produces incorrect output of the days type, it says it should be boolean instead of [boolean]. What is the best way to process this list correctly? -
How to run mulitible django python scripts from .py file in VS Code Terminal?
is there a possible way to start my django project with one single call of an .py file in the VS Code Terminal? I need to call the following scipts all the time to run my project : pipenv shell python manage.py runserver python manage.py sass-compiler --watch And I want theme to be all called when I run an start.py script. Thank you -
I cannot register a user using Django-Rest-Framework
I can't add a new user using Django Rest Framework. Here is my code from models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) password = models.CharField(max_length=15, default= None) first_name = models.CharField(max_length=100, validators=[name_validator]) last_name = models.CharField(max_length=100, validators=[name_validator]) email = models.CharField(max_length=100, validators=[mail_validator]) created_at = models.DateTimeField(auto_now_add=True) As you can see I am using models.OneToOneField cause I want to extend the default user to add some more fields. Bellow is my serializers.py file: class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile permissions_classes = [ permissions.AllowAny ] fields = '__all__' The viewset is the following: class UserViewset(viewsets.ModelViewSet): queryset = Profile.objects.all() serializer_class = ProfileSerializer When I go to my endpoints and try to add a new user, I cannot put anything in the "user" field: Click for image I am a beginner and it would be of great help. Everything that I find I don't understand. -
How to search in PostgresSQL and display the values
I am creating a simple Hospital Management system using Python, Django and PostgresSQL as my school project, I have added a page where the user can add/edit/delete/view the records and I want to add a search option. The above topics(add/delete/edit/view) are discussed clearly in the textbook except search.Reading documentation from both Django and PostgreSQL didn't help me much. I am attaching the views.py and the output page of my program and ready to upload further scripts if required. Kindly instruct how to search in PostgreSQL and display the results. from django.shortcuts import render, redirect from Doctor.forms import Doctorform from .models import Doctor # Create your views here. def doctor_list(request): context = {'doctor_list':Doctor.objects.all()} return render(request, 'Doctor/doctor_list.html', context) def doctor_form(request, id=0): if request.method == "GET": if id==0: form = Doctorform() else: doctor = Doctor.objects.get(pk=id) form = Doctorform(instance=doctor) return render(request, 'Doctor/doctor_form.html', {'form':form}) else: if id == 0: form = Doctorform(request.POST) else: doctor = Doctor.objects.get(pk=id) form = Doctorform(request.POST,instance= doctor) if form.is_valid(): form.save() return redirect('/doctors/Doclist') def doctor_delete(request, id): doctor = Doctor.objects.get(pk=id) doctor.delete() return redirect('/doctors/Doclist') Sample Page of my program -
Is there a way to assign question id to inline formset automatically?
Inline formset generates answer field to the number of questions in my model, but I have to specify url for questions (question_id) or assign question manually like question = Question.objects.get(id=1) to do the work. I want to do this in one view which (question_id) in url is not working for me. The second way is also not useful. So, what I want is that when inline formset generating answer fields, it also gives each answer field an id. models.py class Question(models.Model): question = models.CharField(max_length=200) class Question_Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) answer = models.SmallIntegerField(choices=RATING_CHOICES, default=1) views.py def index(request): question = Question.objects.get(pk=1) QuestionFormset = inlineformset_factory(Question, Question_Answer, fields=('answer',), can_delete=False,extra=0 ) if request.method == "POST": formset = QuestionFormset(request.POST, instance=question) if formset.is_valid(): formset.save() else: formset = QuestionFormset(instance=question) context = {'formset': formset} return render(request, 'index.html', context) -
AttributeError: 'WSGIRequest' object has no attribute 'get' while making a get request
I am trying to make a get request to stackoverflow API but I am facing a WSGI error while making the requests through POSTMAN. Here is the code snippet: Views: def search(requests): query = requests.GET["query"] response = requests.get('https://api.stackexchange.com/2.2/search/advanced?order=desc&sort=activity&q=' + query + '&site=stackoverflow') api_Data = response.json() return JsonResponse({"message": api_Data}) URLs: urlpatterns = [ path('search/', views.search, name='search'), ] I have tried I keep getting 'WSGIRequest' object has no attribute 'Get' on django but it did not work. -
Django how do you build it into a model check that if User read articles or not?
First, I have a user model and a article model in Django And each user can write/read any article What i need to want a list of articles that each user has not read. want to check the list of people who have read about a certain article and the list of people who have not read it. How can i build or modify a model? my models are here Cheers class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) name = models.CharField(max_length=20, blank=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(auto_now_add=True) objects = UserManager() class article(models.Model): title = models.CharField(max_length=255, blank=False) content = models.TextField(max_length=1000, blank=False) created_by = models.ForeignKey( User, on_delete=models.CASCADE ) created_at = models.DateTimeField(auto_now_add=True) -
Same code to add email attachment.Different execution time
Code: print(time.strftime("%Y-%m-%d-%H%M%S", time.localtime(time.time()))) att2 = MIMEText(open('C:/Users/olay_Czz/Desktop/test.rar', 'rb').read(), 'base64', 'utf-8') att2["Content-Type"] = 'application/octet-stream' att2["Content-Disposition"] = 'attachment; filename="test.rar"' msg.attach(att2) print('add-ok') print(time.strftime("%Y-%m-%d-%H%M%S", time.localtime(time.time()))) Runtime in Django(compiler:Pycharm): 2020-12-30-175140 add-ok 2020-12-30-175218 Runtime in Script(compiler:sublimetext): 2020-12-30-180242 add-ok 2020-12-30-180242 Why is the execution time gap so wide -
fetching refresh token with django-microsoft-auth
after going through the module code and extensive googling I am still to find a "simplistic" (ie. by not rewriting the whole module) way of acquiring refresh token for azure ad auth. Any suggestions would be appreciated, replacing this module with something different is also something I am looking into atm.