Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible to access the original creation date of an uploaded file with Python/Django?
I am working on a small app, where the user can upload measurement files for post-processing. The upload and storing of the file is done using Django's POST request method. I use a model that contains a field where the upload date is saved as date_uploaded = models.DateTimeField(auto_now_add=True) However the upload date is actually not the most relevant date in this use case. What I would really like to know would be the creation date of the file on the file system of the user. I already searched through Stackoverflow and it seems like it is not possible to obtain the original creation date of a file that is uploaded via http POST. Is this assertion true? Or is there some way to get the original creation date of an uploaded file? -
Django: ThreadPool and TooManyConnections
Context: Django(3) commands, MySQL from django.db import connections ... def func1(a): with connections['second_db'].cursor() as cursor: cursor.execute(statement) def func2(b): with connections['second_db'].cursor() as cursor: cursor.execute(statement) for ...: pool = ThreadPool(processes=2) result1_proc = pool.apply_async(func1, args=(a)) result2_proc = pool.apply_async(func2, args=(b)) pool.close() pool.join() At some point i will get "Too many connections" error from server. If i add "connections['second_db'].close()" at the end of each function, i get the "django.db.utils.InterfaceError: (0, '')". What is wrong? -
I have data in pandas pivot table format as below and I want to plot graph to webpage
Click to see the pandas pivot table and I have to plot the graph to web pages using django -
readonly fields not been sent on post request
Django 2.2 crispy forms I have a form if the status is approved it makes few fields read-only when been render. when I submit the form only the field which is not read-only comes back within the post request, the read-only fields are not returned. which makes the form invalid for submission. how to make read-only fields returned on submission. form is a crispy form using forms.ModelForm -
Boostrap active item does not work properly
I'm trying to create a tab-pane card in which I could choose to see two different graph: revenue-chart and sales-chart. But I have a problem with the active feature. If I set my code in the followig manner: <ul class="nav nav-pills ml-auto"> <li class="nav-item"> <a class="nav-link active" href="#revenue-chart" data-toggle="tab">Storico</a> </li> <li class="nav-item"> <a class="nav-link" href="#sales-chart" data-toggle="tab">Budget</a> </li> </ul> </div> </div><!-- /.card-header --> <div class="card-body"> <div class="tab-content p-0"> <!-- Morris chart - Sales --> <div class="chart tab-pane active" id="revenue-chart" style="position: relative; height: 300px;"> <canvas class=" w-100 " id="revenue-chart-canvas" height="300" style="height: 300px;"></canvas> </div> <div class="chart tab-pane " id="sales-chart" style="position: relative; height: 300px;"> <canvas class=" w-100 " id="sales-chart-canvas" height="300" style="height: 300px;"></canvas> </div> it show me only the first graph. And If I try to select the second graph does not appear it. How could fix my problem? -
Is it possible to Check Audio or video file duration in Python/Django?
I want to check the audio or video file duration in python. Basically I am working on a platform similar to TikTok, where the user has restrictions for uploading the video or audio of a specific duration. I need to develop a web API that will access the file posted and check first of all, whether the uploaded file is a video or audio, I have achieved this using the library https://pypi.org/project/filetype/ Now I want to check whether the uploaded content has the time duration less than or equal to 1 minute and 30 seconds. How can I achieve this? Thanks in advance. -
Rate limit a celery task without blocking other tasks
I am trying to limit the rate of one celery task. Here is how I am doing it: from project.celery import app app.control.rate_limit('task_a', '10/m') It is working well. However, there is a catch. Other tasks that this worker is responsible for are being blocked as well. Let's say, 100 of task_a have been scheduled. As it is rate-limited, it will take 10 minutes to execute all of them. During this time, task_b has been scheduled as well. It will not be executed until task_a is done. Is it possible to not block task_b? By the looks of it, this is just how it works. I just didn't get that impression after reading the documentation. Other options include: Separate worker and queue only for this task Adding an eta to the task task_a so that all of it are scheduled to run during the night What is the best practice in such cases? -
How to access infromation from parent model Django HTML Tags
I have a two formsets in a view called ContactIndex, the parent model for this view is my CustomUser model. How can in my html template present information from my parent model? I've tried these tags without success This is the tags in my HTML template: {{ customuser.first_name }} - does not work {{ object.first_name }} - does not work This is my view: def ContactIndex(request, CustomUser_id): customuser = CustomUser.objects.get(pk=CustomUser_id) if request.method == "POST": ContactFormset = ContactInlineFormSet(request.POST, request.FILES, instance=customuser) AddressFormset = AddressInlineFormSet(request.POST, request.FILES, instance=customuser) if ContactFormset.is_valid() or AddressFormset.is_valid(): AddressFormset.save() ContactFormset.save() # Do something. Should generally end with a redirect. For example: return redirect ('ContactIndex', CustomUser_id=customuser.id) else: ContactFormset = ContactInlineFormSet(instance=customuser) AddressFormset = AddressInlineFormSet(instance=customuser) return render(request, 'members/member_contact_form.html', {'ContactFormset':ContactFormset, 'Address Formset':AddressFormset }) -
Object filtering issue after removing a field
My previous query is queryset_list = Team.objects.filter( models.Q(players=self.request.user) | models.Q(team_manager=self.request.user) | models.Q(coach=self.request.user) ).order_by('id').distinct() Now I have remove the "players" field from the table "Team" This change is only for the new update.... But I need to provide support for both newly updated users and previously updated users..... Now if a person login with old update this will crack -
Django Form to browse/navigate through data from db
I built 2 forms where you can add services and articles (items) to the db. Each service has one or more items. This one-many relation is stored in a table service_article. I want to build a form where i can browse through the data and see one service at a time and which articles this service has. This is what i've done so far: the models.py: from django.db import models class ArtikelTyp(models.Model): id = models.AutoField(unique=True, primary_key=True) description = models.TextField(blank=True, null=True) class Meta: db_table = 'artikel_typ' class Artikel(models.Model): id = models.AutoField(unique=True, primary_key=True) artikel_typ = models.IntegerField(null=True) bezeichnung = models.TextField() menge = models.FloatField(blank=True, null=True) preis = models.FloatField(blank=True, null=True) einheit = models.TextField(blank=True, null=True) class Meta: db_table = 'artikel' class Leistung(models.Model): id = models.AutoField(unique=True,primary_key=True) bezeichnung = models.TextField() dauer = models.TextField(blank=True, null=True) # This field type is a guess. preis = models.TextField() # This field type is a guess. class Meta: db_table = 'leistung' class LeistungArtikel(models.Model): id = models.AutoField(unique=True,primary_key=True) leistung = models.ForeignKey(Leistung,on_delete=models.DO_NOTHING, verbose_name='die Dazugehoerige Leistung') artikel = models.ForeignKey(Artikel,on_delete=models.DO_NOTHING, verbose_name='der Dazugehoerige Artikel') anzahl = models.IntegerField() class Meta: db_table = 'leistung_artikel' the views.py def services(request): data = Leistung.objects.all() artikel_typ = ArtikelTyp.objects.all() lform = Leistungen(data=request.POST or None) if request.method == "POST": if lform.is_valid(): bezeichnung = lform.cleaned_data['bezeichnung'] dauer = lform.cleaned_data['dauer'] … -
How to build a storing password app with proper security measures?
What I need to do : I need to build a small app for users to store intranet passwords and retrive them very easily. What I tried : I am already putting a lot of effort for security, asking user password each time they go the given page, hiding content after X seconds, hiding input by default etc... But so far I have not found a secure way to encrypted password and then showing them decrypted. Is this possible or should I just renforce security somewhere ? -
Django custom validation before the model is saved
This is an extension from my post here preventing crud operations on django model A short into to the problem , im currently using a package called django-river to implement a workflow system in my application. The issue is that they do not have a predefined 'start' , 'dropped' , 'completed' state. Their states are stored as a django model instance. This would mean that my application is unable to programmatically differentiate between the states. Therefore , the labels of these states has to be hardcoded into my program (Or does it? Maybe someone has a solution to this?) Suppose that there is no solution to the issue other than hardcoding the states into my application , this would mean that i would have to prevent users from updating , or deleting these states that i have pre created initially. My idea is to have a form of validation check within the django model's save method . This check would check that the first 3 instances of the State model is always start , deactivated and completed and in the same order. This would prevent the check from passing through whenever a user trys to change items at the ORM … -
ANDROID VOLLEY + DJANGO DATE PARSING
So currently I am working on a android project with a django backend. I am trying to get date of birth from the user input via android and try to sent it to my backend with Volley library. However, one thing about this is that, I need to send the date data in the format of "yyyy-MM-dd". This means that I have to do a parsing from my input from, for example "dd-MM-yyyy" to "yyyy-MM-dd". My question is, how can I make this format to be more lenient, so the user can input the date in any pattern and I can directly send this to my backend without having to parse the pattern from my frontend. Right now in my Django I have set the date_inputs_formats with an array of date pattern. When I input the date data from the admin, it works the way I wanted (any pattern). However, this does not occur if I input from android app (still gives error, and I have to parse my input pattern to the accepted pattern to be sent to backend). My question is, is there any way either from the backend or frontend side that I can do, so that … -
Placing an order in django-oscar says is requires strategy instance
I am manually implementing the order APIs in django-oscar. I made an API using django-rest-framework to place an order and manually create the Line objects in the Order app. But when I create an order, this error is thrown - RuntimeError at /v0/order/orders/ No strategy class has been assigned to this basket. This is normally assigned to the incoming request in oscar.apps.basket.middleware.BasketMiddleware. Since it is missing, you must be doing something different. Ensure that a strategy instance is assigned to the basket! Where do I set the strategy object? and how should it be implemented? I did not override any models or views. I just created a serializer using the default Order app models. Here are my Basket serializer and view method. class BasketSerializer(ModelSerializer): class Meta: model = Basket fields = '__all__' class CartInfo(APIView): permission_classes = (AllowAny, ) def post(self, request): serializer = BasketSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=201) return Response({"msg": serializer.errors}, status=406) I do not have a lot of experience in Django so please bear with my questionable coding practices. Thank you. -
Session key error while updating the page counts?
Here I am updating the page count in the homepage view but this code is not working properly. It gives the IntegrityError saying NOT NULL constraint failed: mysite_pagevisit.session What might be the reason? How can I solve it ? class HomePageView(View): def get(self, request): if not PageVisit.objects.filter(session=request.session.session_key): PageVisit.objects.create(ip=request.META['REMOTE_ADDR'], session=request.session.session_key) settings SESSION_COOKIE_AGE = 5 #for test models class PageVisit(models.Model): ip = models.GenericIPAddressField() session = models.CharField(max_length=255) created = models.DateTimeField(auto_now_add=True) @property def total_visits(self): return PageVisit.objects.count() -
'Medicine' object has no attribute 'add' error
I want to add medicine to my cart from a medicine list. I created a view but when I click add button it gives this error: AttributeError at /cart/3/ 'Medicine' object has no attribute 'add' I want that when a user click + button, medicine will be add users cart. I can add from admin panel but cannot add from web page. Here are my codes. Please help me. carts/views.py def update_cart(request, id): current_user = request.user cart = Cart.objects.filter().first() try: medicine = Medicine.objects.get(id=id) except Medicine.DoesNotExist: pass except: pass cart.product.add(medicine) return HttpResponseRedirect("/cart") carts/models.py class Cart(models.Model): user = models.TextField(User) product = models.OneToOneField(Medicine, on_delete=models.CASCADE, primary_key=True) total = models.DecimalField(max_digits=100, decimal_places=2, default=0.00) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) active = models.BooleanField(default=True) **plus button in html ** <a href="/cart/{{medicine.id}}" class="btn btn-sq-xs btn-success"> <i class="fa fa-plus fa-1x"></i><br/> </a> -
How do I create new models not affecting the nested serializer
I already have a general idea of how it should be done. The only issue that I face now is how to actually send the data. I don't want to create new Projects I just want to add them to the notifications. How do I pass the data, the actual JSON? class NotificationsScheduleSerializer(ModelSerializer): projects = ProjectSerializer(many=True) # Thats the Many2Many Field user = HiddenField(default=CurrentUserDefault()) class Meta: model = NotificationsSchedule fields = [ "pk", "projects", "period", "week_day", "created_at", "time", "report_type", "user", ] def create(self, validated_data): breakpoint() # I don't ever get "projects" in validated_data just Empty OrderedDict projects_data = validated_data.pop("projects", []) notification = NotificationsSchedule.objects.create(**validated_data) return notification class ProjectSerializer(ModelSerializer): class Meta: model = Project fields = ["pk", "name"] I want to be able to pass something like this. { "projects": [290, 289], "period": "daily", "week_day": 2, "time": "16:02:00", "report_type": "word_report" } But it expects dict instead. "non_field_errors": [ "Invalid data. Expected a dictionary, but got int." ] -
Deploy Django to Vuejs to Heroku - Static file not Found
guys. i have one problem when deploy Django and Vue. the problem is https://mysite.herokuapp.com/static/static/dist/app.js not found. its pretty work fine but its in deployment. In Setting STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR, ""), ] In index.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Django</title> <link rel="stylesheet" href="{% static 'static/dist/app.css' %}" /> <link href="https://cdn.jsdelivr.net/npm/@mdi/font@5.x/css/materialdesignicons.min.css" rel="stylesheet" /> </head> <body> <div id="app"> <App></App> </div> <script src="{% static 'static/dist/app.js' %}"></script> </body> </html> I'll appreciate of all ur help. Thanks... -
Python: formula to calculate cumulate and monthly value of a list
I have two request for you: First one: I have the following montly income variable given by the following: total_income={'Revenues': list(100 for m in range(12))} I want to extract (based on the today date) the month income. Ad example with the formula: this_month=datetime.datetime.now() this_month=now.month I want to extract from total_income the value of this month. Ad example if this_month=6 I want to have the income of this month. Second one Also based on the this_month variable I want to get the cumulate sum of all month until it. Ad example if this_month=6 I want to have the sum of all income starting from 1 to 6. -
Django Visual Studio The environment '....' is not available
I had a virtual environment setup for Django 3 with visual studio. However at some point it seems that this previous environment has been damaged - and therefore is no longer working (nothing appears on git to have changed). I therefore attempted to setup a new environment via the visual studio python environment options. I could setup a conda environment but it will not let me setup a python environment as "you will need to install a python interpreter...". However on the same page it states that the latest python 64 is installed. It will not run with the conda environment that I have setup as it states "The environment '....' is not available." I have tried creating a new solution with VS and this appears to work as intended. However it is not really an option to create a new solution as I will loose a lot of existing git commits along with this causing issues with existing servers. -
How can I catch a token and an email in a django url?
I am trying to use re_path to catch the following url http://localhost:5000/auth/zzDbEOGxVBzyKMKjfQtNR51VxTVX2p9YvlD5oCiB73Xndj0kD6f8tB6YXNaY/?email=test%40test.se I have tried re_path(r'^auth/(?P<token>\w+)/(?P<email>[\w.@+-]+)/', views.create_update_user, name='auth'), and other permutations but I can't seem to get it right I was originally trying with email only being separated with the ? (no /) http://localhost:5000/auth/zzDbEOGxVBzyKMKjfQtNR51VxTVX2p9YvlD5oCiB73Xndj0kD6f8tB6YXNaY?email=test%40test.se but I couldn't get that to work either. -
Problem Related Many to many relationship in Django
I am creating a relationship between Username and User_edu, this is bidirectional code of model.py from django.db import models class username(models.Model): name=models.CharField(max_length=100) class user_edu(models.Model): qualification=models.CharField(max_length=100) clgname=models.CharField(max_length=100) marks=models.CharField(max_length=100) year_of_graduation=models.CharField(max_length=100) uname=models.ManyToManyField(username) In views.py viewue = user_edu.objects.all() if request.method == 'POST': obj = username.objects.get(id=id) uq = user_edu.objects.get(id=request.POST['qualification']) uc = user_edu.objects.get(id=request.POST['clgname']) um = user_edu.objects.get(id=request.POST['marks']) uy = user_edu.objects.get(id=request.POST['year_of_graduation']) uq.uname.add(obj) uc.uname.add(obj) um.uname.add(obj) uy.uname.add(obj) uq.save() uc.save() um.save() uy.save() return render(request, 'data.html', {'user_edu_all': viewue}) else: obj = username.objects.get(id=id) return render(request, 'data.html', {'user_edu_all': viewue}) I am trying to do that the user will register the name first in one webpage and that they will give the details of the education in another page how to relate user and educationdetails -
Content not being served from STATIC_ROOT
Its my first project in django,so i dont know a lot of things.firstly, i want to serve static files from django STATIC_ROOT, not STATICFILES_DIRS. this is my project tree: src >> ...db.sqlite3 ...manage.py ...mainapp (main module) ...__init__.py ...settings.py ...urls.py ...wsgi.py ...myapp (django app) ...Migrations(Folder) ...__init__.py ...admin.py ...apps.py ...models.py ...tests.py ...views.py ...accounts (django app) ...Migrations(Folder) ...__init__.py ...admin.py ...apps.py ...models.py ...tests.py ...views.py ...templates ...myapp ...home.html ...accounts ... ... ...static ...myapp ...css ...bootstrap.css ...home.css ...js ...images ...accounts ... ... ... ...static_cdn (STATIC_ROOT) ...admin ... ... ... ...myapp ...css ...js ...images ...accounts ...css ...js ...images in settings.py : INSTALLED_APPS = [ 'myapp', 'accounts', ....., ....., ....., 'django.contrib.staticfiles', ] ....... ....... ....... STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR,'static'), ] STATIC_ROOT = os.path.join(BASE_DIR,'static_cdn') in urls.py : from django.contrib import admin from django.urls import path from django.conf import settings from django.conf.urls.static import static ....... from myapp.views import ( ......., ......., ) from accounts.views import ( ......., ......., ) urlpatterns = [ ......., ......., ......., ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) in home.html in templates : <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"> <title>.......</title> <link rel="stylesheet" type="text/css" href="{% static 'myapp/css/bootstrap.css'%}"/> <link rel="stylesheet" type="text/css" href="{% static 'myapp/css/home.css'%}"/> </head> <body> ....... ....... … -
how to mapping/dispatcher the Django urls?
I'm trying to make some Maps... to use in market. so i try to use Django, Python. but there are some problems related to url mapping. here's the problem. jeobjeom_code = c[5] = pk = SAF11050 i want to make some links like 'RAW_SoMae_MaeJang_Info_detail/SAF11050' but didn't work. if jeobjeom_code is only int, it works! but if jeobjeom_code is string, didn't work at all. i guess c[5] using is wrong... but i don't know how to fix it... NoReverseMatch at /Maps_DaeLi_PanMae Reverse for 'RAW_SoMae_MaeJang_Info_detail' with keyword arguments '{'pk': 'c[5]'}' not found. -models.py class RawSomaeMaejangInfo(models.Model): jeobjeom_code = models.CharField(db_column='JeobJeom_Code', primary_key=True, max_length=50) # Field name made lowercase. latitude = models.CharField(db_column='Latitude', max_length=100, blank=True, null=True) # Field name made lowercase. longitude = models.CharField(db_column='Longitude', max_length=100, blank=True, null=True) # Field name made lowercase. -urls.py urlpatterns =[ path('RAW_SoMae_MaeJang_Info_detail/<int=pk>', views.RAW_SoMae_MaeJang_Info_detail, name='RAW_SoMae_MaeJang_Info_detail'), -Maps_DaeLi_PanMae.html var tmpl = '<div style="font-family: dotum, arial, sans-serif;font-size: 18px; font-weight: bold;margin-bottom: 5px;">#{title}</div>' + '<table style="border-spacing: 2px; border:s 0px"><tbody><tr>' + '<tr><td style="color:#767676;padding-right:12px">check</td>' + '<td><a href="{% url 'RAW_SoMae_MaeJang_Info_detail' pk='c[5]' %}" >link</a></td>' + -views.py def Maps_DaeLi_PanMae(request): Maps_DaeLiJeom_list = RawSomaeMaejangInfo.objects.all() context = {"Maps_DaeLiJeom_list":Maps_DaeLiJeom_list} return render(request, 'app/Maps_DaeLi_PanMae.html', {"Maps_DaeLiJeom_list":Maps_DaeLiJeom_list}) -
Django makegration on production
I have a django project working currently. If i create new model on dev/debug environment I can run makemigrations and migrate and the new model is created but when I sync the changes to production and I try to pull new changes and run python manage-py makemigrations <- this dont detect new models, if i run python manage.py makemigrations appname <- this detect changes but tries to create initial creation of full db structure. Could be possible add only new created model to database? I use Mysql in production and sqlite in dev environment.