Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to ship my python app to none programmers, and without preinstalled python
i have been trying this for a long time and i couldn't find a solution, i used Docker and it didn't done the thing that i want. so my question is, How to build an app in python and ship it to none programmers, my idea is i wanna build a GUI app with PyQt5 and i wanna use Django framework and Sqlite3 and a lot other python modules, and i wanna put them all into a container that will work without any preinstalled Docker or even python, and it will work just fine and lightweight.... is this even possible?! Thanks. -
Django migrations not working from GitHub Actions
I have the command heroku run -a ${{ secrets.HEROKU_APP_NAME }} python manage.py migrate set to run after pushing master to Heroku. It runs without errors (below is it's the output): Running python manage.py migrate on ***... ? Running python manage.py migrate on ***... done But the migrations don't actually run. What could be the problem? -
Is there a faster approach than caching data between request? (heroku django app)
I have a question regarding caching and performance for my django app on heroku. django 2.2.9 python 3.7 In my django-app I use different ajax request which use the same queryset (first request is number of results according to the filter set, then it requests a table, then pictures). For performance reasons I use a cache on server side instead of quering each time the database. In development I used the LocMemCache of Django, which is really fast and convenient. On heroku it is really slow (I dont know why actually). so I changed to memcached which is recommended by django and by heroku. I tried "MEMCACHED CLOUD" and "MemCachier" (both heroku addons). but they are very slow, also when I use them locally (locmem: < 1 sec; memcached: > 5sec) Questions: Should I use different approach instead of caching? (I thought of sessions, but there I cannot store querysets. and Im not sure if its really faster, as it saves on the database or in cache) If caching is the right approach. How can I speed it up? Thank you! #settings CACHES = { 'default': { 'BACKEND': 'django_bmemcached.memcached.BMemcached', 'TIMEOUT': 60 * 60, 'LOCATION': os.environ['MEMCACHEDCLOUD_SERVERS'].split(','), 'OPTIONS': { 'username': os.environ['MEMCACHEDCLOUD_USERNAME'], 'password': … -
Conflicts in in migration files while doing makemigrations
I have 3 instances of django running on live dev/live/production,Now Due to some colleague's work I got Conflicts errors due to diff branches (I have 6 branches so some have slightly diff migrations files and on pull request creating mess) And only solution which I found was resetting migrations. after that I deleted all migrations except init file . Now I am thinking to add migrations to gitignore file .As It will save further conflicts as my colleague is new and making mess as I don't have much time to go and fix evey time. So Question is there any issue of doing this ? Or is it harmful in near future ? Kindly before giving down vote read it and tell me why you are down voting As it is not my code I started on this project in half way -
How to solve "No Python interpreter configured for the module"? in Android Studio?
How to solve "No Python interpreter configured for the module"? in Android Studio? I am trying to use python and django framework in android studio . My MainActivity is in kotlin. i dont know how to solve this, any ideas? -
I don't really understand how STATICFILES_DIRS and STATIC_ROOT Django settings works
I have some troubles understanding how static files works on Django 3.0.7 In my settings.py file, I wrote this: STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),) STATIC_ROOT = os.path.join('static') Here is what I understood. So correct me if I'm wrong. This is the whole point of my question. STATIC_URL = '/static/' This one is quite self explanatory. It's the URL root to the static files. This way I can reach my picture.jpg in my /static/ folder via my browser by typing the http://<ip-or-domain>/static/picture.jpg. But I have some troubles with the two others. STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),) This parameter tells Django I want to use all the folders called static as static folder where Django will collect every file to put them in the main static folder with the command python3 manage.py collectstatic. The first argument gives the root where Django should start searching and the second argument is the name of the folder which be identified as app static folder. STATIC_ROOT = os.path.join('static') And this parameter is the one which indicate the path of the main static folder where the collected static files will be put. Am I right until now ? So here is my issue. When I launch … -
Media Files in database not found
Created database in django where I upload media files under the object Beat, and specify tags for each object However, whenever I try to display on the front end of the website, I receive an error that my media files were not found at the exact location I've placed them to in. Does anybody know what could be causing this issue? Error [12/Jun/2020 15:45:00] "GET /media/artwork/san-diego-skyline-green-1_1.jpg HTTP/1.1" 404 2190 Not Found: /media/beats/Free_J_Cole_Type_Beat_-_Divinity.mp3 [12/Jun/2020 15:45:00] "GET /media/beats/Free_J_Cole_Type_Beat_-_Divinity.mp3 HTTP/1.1" 404 2199 ``` index.html <!DOCTYPE html> {% for beat in beats %} <p>{{beat}}</p> <audio controls> <source src="{{beat.beatFile.url}}" type="audio/mpeg"/> </audio> <a><img src="{{beat.artwork.url}}" class="img-responsive"/></a> <p>{{beat.beatFile.url}}</p> <p>{{beat.artwork.url}}</p> {% for tag in beat.tags.all %} {{tag}} {% endfor %} {% endfor %} Models.py class Beat(models.Model): """Contents of Beat (name, file, and artwork)""" name = models.CharField(max_length = 255, null=True) artwork = models.FileField(upload_to='artwork') beatFile = models.FileField(upload_to='beats') def __str__(self): """Return a string representation of name.""" return self.name views.py # Create your views here. def index(request): return render(request=request, template_name="index.html", context={"beats": Beat.objects.all}) -
error: (-215:Assertion failed) dims <= 2 && step[0] > 0 in function 'cv::Mat::locateROI'
when I use this function it sends me a error enter image description here # 图片膨胀处理 def dilate_and_erode(img): src = cv2.imread(img) kernel = np.ones((5, 5), np.uint8) erosion = cv2.erode(src, kernel) dst = cv2.dilate(erosion, kernel) # cv2.imshow('origin', src) # cv2.imshow('after erosion', erosion) name = img.split('.')[0] + '_dilate_erode.jpg' cv2.imwrite(PATH + name, dst) # cv2.imshow('after dilate', dst) return 'img/' + name -
Django rest framework, format url by user name
I have a small messaging API built with DRF which sends messages between users in the system. My messages view contains several extra actions: class MessagesViewSet(ModelViewSet): """ A simple ViewSet for viewing and editing the messages associated with the user. """ authentication_classes = [TokenAuthentication, ] permission_classes = [IsAuthenticated] serializer_class = MessageSerializer filter_backends = [DjangoFilterBackend] filterset_fields = [MessageFields.MARK_READ] def get_user(self): user = self.request.user return user def get_queryset(self): return Message.objects.filter(sent_to=self.get_user()) @action(detail=True) def sent_messages(self, request, pk): """ Return all messages sent by the user. """ queryset = Message.objects.filter(sender=self.get_user()) serialized_data = MessageSerializer(queryset, many=True) return Response(serialized_data.data, status=HTTP_200_OK) @action(detail=True) def last_50_messages(self, request, pk): """ Return the user's 50 last messages """ queryset = Message.objects.filter(sent_to=self.get_user()) serialized_data = MessageSerializer(queryset, many=True) return Response(serialized_data.data, status=HTTP_200_OK) Urls file: from .views import MessagesViewSet messages_router = DefaultRouter() messages_router.register(r'messages', MessagesViewSet, basename='messages') urlpatterns = [ url('', include(messages_router.urls)) ] Right now the only way to access the two custom methods is opening one of the message instances and then add it to the URL line and it'll work. How can format the url for each method so it will be via the username? right now: http://127.0.0.1:8000/api/messages/1/sent_messages/ I looking for something like: http://127.0.0.1:8000/api/messages/#request.user.username/sent_messages/ -
How to set variable inside django template with javascript and pass it to views.py?
I want to add a dark mode option to my django website, when you press a button I want to set a variable dark-mode to True and when you press again it sets dark-mode to False using javascript, and at views.py it will set the template-name as home-dark.html or home-light.html according to the dark-mode variable, how can I achieve this? In case you need to know, I use Materialize CSS Thanks from now -
can you use a function to set a field when creating a model (django)
I have created a model called 'Video' and in the Video class there is a field called videoID. I want videoID to be a randomly generated string but in my solution, there has been some errors. Here is my solution: models.py from django.db import models from django.contrib.auth.models import User from other.video import generateVideoID class Video(models.Model): videoID = models.TextField(default=generateVideoID(),editable=False) author = models.ForeignKey(User,on_delete=models.CASCADE, null=True) As you can see in the videoID field I have set the default value to a function that returns a random string. This doesn't work because every time I create an object the videoID has the same string. This is the 'generateVideoID' function: def generateVideoID(): import random,string chars = string.ascii_letters+string.digits+"_-~" videoID = "" for i in range(12): videoID += random.choice(chars) return videoID I have tried to use the 'init' method to set the videoID but that doesn't work. Can anyone help me? -
GeoDjango PointField overwrite default widget
This is how the form looks when I do (forms.Form). #This one is not linked to a model but the map renders correctly. class OsmPointWidget(floppyforms.gis.PointWidget, floppyforms.gis.BaseOsmWidget): pass class ContactForm(forms.Form): fields = ('User', 'Residential', 'Location') User = forms.CharField(widget=forms.TextInput()) Residential = forms.CharField(widget=forms.TextInput()) Location = floppyforms.gis.PointField(widget=OsmPointWidget(attrs={ 'map_width': 300, 'map_height': 300, })) This is how the form looks when I do (model.ModelForm). #This one is linked to a model but the map renders incorrectly. class OsmPointWidget(floppyforms.gis.PointWidget, floppyforms.gis.BaseOsmWidget): pass class ContactForm(forms.ModelForm): class Meta: model = Property fields = ('User', 'Residential', 'Location') Location = floppyforms.gis.PointField(widget=OsmPointWidget(attrs={ 'map_width': 300, 'map_height': 300, })) I have attempted to overwrite the default widget. Either that hasn't worked. Or that is not the correct solution for my problem. from django.contrib.gis.admin import OSMGeoAdmin from properties.models import Property from django.contrib import admin from django.contrib.gis.db import models from properties.forms import OsmPointWidget #In the brackets put the name of the model you are importing #In localhost/admin they will add an S onto all the model names admin.site.register(Property) class PropertyAdmin(OSMGeoAdmin): formfield_overrides = { models.PointField: {'widget': OsmPointWidget}, } list_display = ('name', 'location') -
Does django serializer method field function gets called if the object to be serilized already having that field?
I am having a object which already contains the field value which is to be found using serializer method field function. Does the get_'function'() for that field still gets called. If yes how to forbid it ? -
Django-Rest-Framework: JSON parse error - Expecting property name enclosed in double quotes: line 11 column 5 (char 257)"
I am following a course on the Django Rest Framework. I seem to have copied the code verbatim, however, there seems to be some error which I am unable to zero down on. What possibly could be causing this error? Basically, I am testing the model serializer. I am trying to post the following data. { "id": 1, "author": "John Doe", "title": "Happy Birthday", "description": "20 years of ISS", "body": "Fancy content", "location": "Earth", "publication_date": "2020-06-11", "active": false, } My serializer class looks: class ArticleSerializer(serializers.ModelSerializer): time_since_publication = serializers.SerializerMethodField() class Meta: model = Article fields = '__all__' def get_time_since_publication(self, object): publication_date = object.publication_date now = datetime.now() time_delta = timesince(publication_date, now) return time_delta And my model is : class Article(models.Model): author = models.CharField(max_length=50) title = models.CharField(max_length=120) description = models.CharField(max_length=200) body = models.TextField() location = models.CharField(max_length=120) publication_date = models.DateField() active = models.BooleanField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.author} {self.title}" The error thrown is a 400 BAD REQUEST error: { "detail": "JSON parse error - Expecting property name enclosed in double quotes: line 13 column 1 (char 214)" } -
Django Rest Framework have a to_representation on a foreignKey with source
I have a nested relation on a key that has a different name from the name that the key in the DB has. I am able to do both, just not if they are combined. I need the api name to be countryOfOrigin and the source is country_of_origin. However the only I get to work is either [ { "articleIdOwn": "1234abc", "articleNameOwn": "1234abc", "countryOfOrigin": "DE" } ] where the serializer looks like this: class ProductSerializer(serializers.ModelSerializer): articleIdOwn = serializers.CharField(source='article_id_own') articleNameOwn = serializers.CharField(source='article_name_own') countryOfOrigin = serializers.PrimaryKeyRelatedField(source='country_of_origin', read_only=True) class Meta: model = User_Product fields = ['articleIdOwn', 'articleNameOwn','countryOfOrigin'] Or this: [ { "articleIdOwn": "1234abc", "articleNameOwn": "1234abc", "country_of_origin": { "isoCode": "DE", "country": "Deutschland" } } ] where the serializer looks like this: class HS_CountriesSerializer(serializers.ModelSerializer): isoCode = serializers.CharField(source='iso_code', read_only=True) country = serializers.CharField(read_only=True) class Meta: model = HS_Countries fields = ['isoCode', 'country'] class ProductSerializer(serializers.ModelSerializer): articleIdOwn = serializers.CharField(source='article_id_own') articleNameOwn = serializers.CharField(source='article_name_own') class Meta: model = User_Product fields = ['articleIdOwn', 'articleNameOwn', 'country_of_origin'] def to_representation(self, instance): self.fields['country_of_origin'] = HS_CountriesSerializer(read_only=True) return super().to_representation(instance) I however want it to look like this: [ { "articleIdOwn": "1234abc", "articleNameOwn": "1234abc", "countryOfOrigin: { "isoCode": "DE", "country": "Germany" } } ] -
How do I customize the Admin page of a Django project?
Greetings admired senior developers! Newbie developer here to ask for some help! I'm currently using Django as my framework program to build a website that gathers movie data from a certain search engine's api and provide users with movie recommendations based on reviews and rank. The basic structure of the project will be as follows; Movie app, which receives movie data from an api and stores them, and Accounts app, an app that takes care of all the tasks regarding user activities such as signups and logins. As for the maintenance of the server, my plan is to use the well-designed Admin page of Django to apply changes and updates to user data as well as movie data. The problem here is that the default Admin page doesn't include the feature that allows me to get movie data from a specific api and apply it to the database of the Movie app (into the Movie model, that is). Therefore, I'm thinking I would need to customize the Admin page itself and this is the very part where I need your help. I've been searching all over starting off from official Django websites to other people's blogs and articles to find … -
Accessing Django CreateForm input with JavaScript before submission
With Function Based Views in Django, I can use the <input> html tag with the v-on:input parameter to update JavaScript variables dynamically based on user input. When I use the Django CreateView Class Based View template, I can access Django variables using 'id_variablename' but this only gives me the default value from the Django model. Is there any way to update the 'id_variablename' JavaScript variable to match the user input and display the typed in value before submitting the form? -
Django admin on adding a new FK show in modal instead of a popup
Hello I am wondering how to make the add_form to show in modal instead of a popup when adding a new foreign key instance of a field in the django admin. Explanation. When pressing the + button on FK I want the form in a modal instead of a popup -
Django many-to-one create parent ("one") entry if not already exist
I have a comparable setup as the documentation of django describes for a many to one scenario. https://docs.djangoproject.com/en/3.0/topics/db/examples/many_to_one/ from django.db import models class Reporter(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField() def __str__(self): return "%s %s" % (self.first_name, self.last_name) class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateField() reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) def __str__(self): return self.headline class Meta: ordering = ['headline'] I have situations where the Reporter does not yet exist, but Article can be created for a non-existing reporter, so I want the Article model to make a Reporter if it doesn't exist yet. I guess what I need is a check if the Reporter already exists and if not create a new one. Is this the best way? Or does Django have a better, build in, method for this? Al reporters will have specific ID that is I very new to Django and have trouble finding resources about this, probably because I'm missing terminology, so I some can point me in the right direction I would already be helped! -
How to make a div appear only once in a loop?
I've created a model Team in models.py in Django for which I've created in views.py the following code: def team(request): obj = Team.objects.all().order_by('?') context = {'team': obj} return render(request, 'website/team.html', context) In HTML I've created a team loop which is displaying all the team members available. {% for team in team %} <div class="member animated delay1" data-effect="fadeInUp"> <div class="team-image"> <div class="teamDescription"> <p>{{ team.description }}</p> </div> <img src="{{ team.picture.url }}"> </div> <div class="blueLine"></div> <div class="team-name-function animated delay1" data-effect="fadeInUp"> <h5>{{ team.name }} {{ team.surname }}</h5> <p>{{ team.title }}</p> </div> </div> {% endfor %} In this loop, I need to make available one div with the numbers of team members, which has to appear only once and randomly as team members. Currently I have <div class="number">{{ team.count }}</div> outside the loop. How do I integrate the members counting in the loop and make it appear only once? Thank you in advance for any solution! -
Waiting for another request in Django view
The title is pretty much self explaining, I need for one of my views to wait for another view to be called or timeout. It would look something like this: class WaitingView(APIView): def post(self, request): ...do_things called = wait_for_DeblockingView_or_timeout() if called: return Response(200) return Response(408) class DeblockingView(APIView): def post(self, request): ...do_things send_some_signal_to_unlock() return Response(200) I already have tried to use the Event object of the threading module, making use of its wait() and set() methods, but either I'm doing it wrong either it's just not the way to go for this use case. More about that attempt here. -
Main dask task with subtask stuck when finished if runned from django view
I have a django view that should submit a task in dask. This scope of this task to unzip a filefield of a model and then run some other tasks that require the unzipped filepath as argument. The following code is not the real one, but I have same issue also on this minimalist example. The code to run the main task in django view is quite simple because is just a fire and forget: dask_client = Client("tcp://scheduler:8786") fire_and_forget(dask_client.submit(unzip_then_run, object)) The unzip_then_run code is made following instructions def unzip_then_run_basic(dump, es_url): dask_client = get_client() secede() tasks = [] for i in range(10): task = dask_client.submit(run_basic, i) tasks.append(task) results = dask_client.gather(taks) rejoin() The final subtask code is: def run_basic(random): time.sleep(random * 2) return 0 Everything works until the rejoin(), the subtasks end successfully but then nothing happen. Everything seems to be waiting and I don't have information or issues on my worker logs: The reason why I need to wait for subtasks is that I want to update the model with a completed status. If I use fire_and_forget also in the main task everything works fine but then I don't easily know when the task is completed. All the code is running … -
Django Attribute Error: 'NoneType' object has no attribute 'videofile'
I am following this tutorial to create a video uploader in my Django project and have run into this error: ..src/video/views.py", line 9, in showvideo videofile= lastvideo.videofile AttributeError: 'NoneType' object has no attribute 'videofile' I'm sure I am missing something obvious and have been looking for the answer for a while now. Would be grateful for any help. views.py from django.shortcuts import render from .models import VideoUpload from .forms import VideoForm def showvideo(request): lastvideo= VideoUpload.objects.last() videofile= lastvideo.videofile form= VideoForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() context= {'videofile': videofile, 'form': form } return render(request, 'video.html', context) forms.py from django import forms from .models import VideoUpload class VideoForm(forms.ModelForm): class Meta: model = VideoUpload fields = ["name", "videofile"] models.py from django.db import models class VideoUpload(models.Model): name= models.CharField(max_length=500) videofile= models.FileField(upload_to='videos/', null=True, verbose_name="") def __str__(self): return self.name + ": " + str(self.videofile) from django.conf import settings from django.contrib import admin from django.urls import path from django.conf.urls.static import static from video.views import ( showvideo, ) urlpatterns = [ path('showvideo', showvideo, name='showvideo'), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) FYI I updated the name of the model to 'VideoUpload' vs the tutorial. -
The best way to inject social auth to django oauth toolkit
i want to use django-oauth-toolkit and i need to use both social auth (e.g google) and regular django-oauth-toolkit token at the same time. but i do not have idea for handle these two at the same time. -
automatic refreshing <div> with django
I have a form that when it is posted the content of console.html gets changed. for refreshing the page I used the following code but this does not refresh console.html javascript function autorefresh() { // auto refresh page after 1 second setInterval('refreshPage()', 1000); } function refreshPage() { var container = document.getElementById("console"); container.innerHTML= '<object type="text/html" data="../../templates/snippets/console.html" ></object>'; //this line is to watch the result in console , you can remove it later console.log("Refreshed"); } index.html <script>autorefresh()</script> <div id="console" > {% include 'snippets/console.html' %} </div> view.py def index(request): if request.method == "GET": return render(request, 'index.html') if request.method == "POST": # If the form has been submitted... form=InputForm(request) form.do_function() return render(request, 'index.html')