Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django "ImageField" form value is None
I'm trying to implement profile picture field for users. The following is the code for each file for the implementation I tried, forms.py, models.py, views.py, and urls.py. I use a IDE (vscode) to debug django, and I placed a breakpoint on the user.avatar = form.cleaned_data['avatar'] line in views.py below, to quickly check if cleaned_data['avatar'] is filled as user input, as I expect. However, even after I upload a file on the url, submit, the line shows None while expected a image object, and of course it doesn't save anything so no change to the database either. # # forms.py # accounts/forms.py # from accounts.models import UserProfile # .. class UserProfileForm(forms.ModelForm): avatar = forms.ImageField(label=_('Avatar')) class Meta: model = UserProfile fields = [ 'avatar', ] def __init__(self, *args, **kwargs): super(UserProfileForm, self).__init__(*args, **kwargs) self.fields['avatar'].required = False # # models.py # accounts/models.py # from django.contrib.auth.models import User from PIL import Image class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(upload_to="images", blank=True, null=True) # note: I also did "python manage.py makemigrations accounts; python manage.py migrate accounts;" # # views.py # accounts/views.py # class UserProfileView(FormView): template_name = 'accounts/profile/change_picture.html' form_class = UserProfileForm def form_valid(self, form): user = self.request.user user.avatar = form.cleaned_data['avatar'] user.save() messages.success(self.request, _('Profile picture has been … -
Celery upgrade from 4.4.6 to 5.1.2 fails with error DatabaseError: ORA-00904: "DJANGO_CELERY_BEAT_PERIODI5B67"."EXPIRE_SECONDS": invalid identifier
I have a working DJango application with python 3.7.12 django==2.2.24 celery==4.4.6 django-celery-beat==1.5.0 I need to upgrade celery to celery==5.1.2 django-celery-beat==2.2.0 I get below error after upgrading the libraries. Exception in thread django-main-thread: Traceback (most recent call last): File "/home/ssin/workspace/djapp/venv3712/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/ssin/workspace/djapp/venv3712/lib/python3.7/site-packages/django/db/backends/oracle/base.py", line 510, in execute return self.cursor.execute(query, self._param_generator(params)) cx_Oracle.DatabaseError: ORA-00904: "DJANGO_CELERY_BEAT_PERIODI5B67"."EXPIRE_SECONDS": invalid identifier I tried to recreate the migration and run the migrations but that also failed with same error. python manage.py makemigrations python manage.py migrate django_celery_beat -
Host both PHP/JS and Django applications with Apache on Windows
I have a WAMP Server 3.2 (Apache 2.4.46) installed on Windows 10 (64-bits), it is exposed to the local company network. I use it to host ordinary php/js applications. My httpd-vhosts.conf is used to look like this: <VirtualHost *:80> ServerName RealNameOfTheServer DocumentRoot "d:/projects" <Directory "d:/projects/"> Options +Indexes +Includes +FollowSymLinks +MultiViews AllowOverride All Require all granted </Directory> </VirtualHost> Now I got a Django app which preferably needs to be hosted with the same server (since I don't have any other) along with other php applications. I tried to follow the example to configure my virtual hosts, but it uses daemon process which is not available on Windows. My httpd-vhosts.conf after applied changes makes Django app work correctly but dumps php/js apps. <VirtualHost *:80> ServerName RealNameOfTheServer DocumentRoot "d:/projects" <Directory "d:/projects/"> Options +Indexes +Includes +FollowSymLinks +MultiViews AllowOverride All Require all granted </Directory> WSGIPassAuthorization On ErrorLog "logs/dashboard.error.log" CustomLog "logs/dashboard.access.log" combined WSGIScriptAlias / "d:\projects\dashboard\dashboard\wsgi_windows.py" WSGIApplicationGroup %{GLOBAL} <Directory "d:\projects\dashboard\dashboard"> <Files wsgi_windows.py> Options +Indexes +Includes +FollowSymLinks +MultiViews AllowOverride All Require all granted </Files> </Directory> Alias /static "d:/projects/dashboard/static" <Directory "d:/projects/dashboard/static"> Require all granted </Directory> </VirtualHost> Is there any way to run both php and Django apps on Windows? -
how to fix error code H10 in heroku with python
i've seen other posts saying to do things with the Procfile but nothing has worked for me when i try to run my server with heroku, I receive this error: at=error code=H10 desc="App crashed" method=GET path="/" host=d1sbot.herokuapp.com request_id=33508569-4287-462f-86b4-12e9a8c6dca8 fwd="150.101.163.59" dyno= connect= service= status=503 bytes= protocol=https my requirements.txt looks like this: asgiref==3.5.0 Django==4.0.3 gunicorn==20.1.0 sqlparse==0.4.2 whitenoise==6.0.0 my settings.py file looks like this: from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-#2%rkkxk6&nmlzk-0lc2aw-n@&)dt1o_g)f5e=i6a611*6u3@1' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [ '127.0.0.1', 'd1sbot.herokuapp.com', ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'web', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] ROOT_URLCONF = 'botfiles.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(MAIN_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'botfiles.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password … -
How can I display the price of each item Django
I'm trying to return the price of each item but depending on these conditions. i. If no user has placed a bid on the item, return starting bid ii. If a user has placed a bid on the item, update the starting bid to the new bid amount I have tried the below but it is not reflecting the new amount when a user places a bid on the item. DETAILS.HTML <div> <h5>{{ listing.title }}</h5> <hr> <p>{{ listing.description }}</p> <hr> <p>Current price: ${{ listing.bid }}</p> VIEWS.PY def make_bid(request, listing_id): listing = Auction.objects.get(pk=listing_id) bid_item = Bids.objects.filter(auction=listing).order_by('-new_bid').first() #if theres no bid available, use starting bid, if available, update to the latest bid if bid_item == None: bid = listing.starting_bid else: bid = bid_item.new_bid if request.method == 'POST': bid_form = BidForm(request.POST, listing=listing) if bid_form.is_valid(): accepted_bid = bid_form.save(commit=False) accepted_bid.user = request.user accepted_bid.save() messages.success(request, 'Successfully added your bid') return redirect('listing_detail', listing_id=listing_id) else: context = { "bid_form": bid_form, "bid": bid, "bid_item": bid_item, "listing": listing } return render(request, 'auctions/details.html', context) return render(request, 'auctions/details.html', bid_form = BidForm()) FORMS.PY class BidForm(forms.ModelForm): class Meta: model = Bids fields = ['new_bid'] labels = { 'new_bid': ('Bid'), } def __init__(self, *args, **kwargs): self.listing = kwargs.pop('listing', None) super().__init__(*args, **kwargs) def clean_new_bid(self): new_bid = … -
<header> <body> and <footer> tags don't work properly xhtml2pdf | django
I'm using xhtml2pdf to render an html page to pdf and I would like to have a page header and a page footer which repeats for every new page. I've tried to use the tag <header> and <footer> of html but actually these don't work: they just show up in the page right in the position I wrote the code. Any idea of which could be the problem? I've also problems in the pagination: I've already looked in stackoverflow for similar questions but I couldn't handle the problem. -
django + apache + moviepy - MoviePy error: FFMPEG encountered the following error while writing file
I am trying to extract audio from a video uploaded using moviepy. The code works well during development but i keep getting error after deploying the django app. def extract_audio(object_id): """This function extracts audio from video""" # Get the object translator_object = Translator.objects.get(pk=object_id) old_audio_file_path = '' if translator_object.source_audio: old_audio_file_path = translator_object.source_audio.path # raise exceptions if not translator_object: raise Exception("Object not found") if not translator_object.source_video: raise Exception( "Video file not available, try again!") if not os.path.isfile(translator_object.source_video.path): raise Exception( "Video file not available, try again!") video_clip = VideoFileClip(translator_object.source_video.path) new_audio_file_path = str(uuid4())+'.wav' video_clip.audio.write_audiofile(new_audio_file_path) translator_object.source_audio = File(open(new_audio_file_path, "rb")) translator_object.save() try: os.unlink(new_audio_file_path) if os.path.isfile(old_audio_file_path): os.unlink(old_audio_file_path) except: print('Deleting error..') error: OSError at /admin/translator/translator/ [Errno 32] Broken pipe MoviePy error: FFMPEG encountered the following error while writing file 162f5850-943b-483b-b97d-2440cc84a2ef.wav: b'162f5850-943b-483b-b97d-2440cc84a2ef.wav: Permission denied\n' In case it helps, make sure you are using a recent version of FFMPEG (the versions in the Ubuntu/Debian repos are deprecated). Request Method: POST Request URL: https://felix-projects.eastus.cloudapp.azure.com/admin/translator/translator/ Django Version: 3.2.10 Exception Type: OSError Exception Value: [Errno 32] Broken pipe MoviePy error: FFMPEG encountered the following error while writing file 162f5850-943b-483b-b97d-2440cc84a2ef.wav: b'162f5850-943b-483b-b97d-2440cc84a2ef.wav: Permission denied\n' In case it helps, make sure you are using a recent version of FFMPEG (the versions in the Ubuntu/Debian repos are … -
Authorize.net SDK support for Python 3.10
Authorize.net official Github SDK doesn't work as the collections module is deprecated in python. Authorize.net official SDK is not active for months. Will they support the new version of python or do we have to look for a new payment gateway that supports Python 3.10. -
Detection fake profil by using keystroke dynamics
Hello i need to create a Web site for détections of importer bye usine keystroke dynamics biometric i have to do it with python and django for the authentification and also to have idea of the way of writting of my user speech, slowly -
I want i hash my password but some fields should not be required
Please help as soon as posible Please Please Please In django validation when I signup, i don't want to validate some fields becouse the are not required, but if i am creating user from another page there i want those fields, so how to do unrequired some fields class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ["id", "username", "password" ,"first_name", "last_name","email", "User_Type","url","sign_up_count", "facebook", "twitter", "linkedin", "instagram", "telegram", "discord", "snapchat"] def create(self, validated_data): user = User( email=validated_data['email'], first_name=validated_data['first_name'], last_name=validated_data['last_name'], username=validated_data['email'], User_Type=validated_data['User_Type'], facebook=validated_data['facebook'], twitter=validated_data['twitter'], linkedin=validated_data['linkedin'], instagram=validated_data['instagram'], telegram=validated_data['telegram'], discord=validated_data['discord'], snapchat=validated_data['snapchat'], ) user.set_password(validated_data['password']) user.save() return user when i signup a account i dont want facebook, telegram and more..., but if i am creating user from another page that time i neet it. so how to set unrequired thes fields for validate Please help as soon as posible please please please -
Django: Filter by less verbose (database name) on TextChoices class
I have a model: class RegulationModel(models.Model): class Markets(models.TextChoices): EUROPE = 'E', 'Europe' US = 'US', 'US' JAPAN = 'J', 'Japan' KOREA = 'K', 'Korea' BRAZIL = 'B', 'Brazil' INDIA = 'I', 'India' CHINA = 'C', 'China' market = models.CharField(verbose_name='Market:', max_length=2, choices=Markets.choices) [... more fields ..] How do I filter on the more verbose choice in the Markets class? For example say I want to filter with "China", i'd like to do something like: regulation = RegulationModel.objects.get(market__verbose='China') (I know this isn't possible but it's just to get an idea) The reason why I am doing this is because I am getting the choice from AJAX therefore the format is not ["C","US"] .etc. I wouldn't mind a suggestion which would allow me to convert my choice "China" --> "C" and then load this variable into the filter. -
Reset password view without using FormViews in django
I am trying to set a reset password view without using the reset FormViews that Django uses by default. This means that I don't really use the auth application, more than for the tokens and some other small stuff. What I did now is a normal view that displays an email/username form, and send an email to the user with a token: password_reset_token = PasswordResetTokenGenerator() def sendPasswordResetEmail(user, current_site): mail_subject = 'Password reset' message = render_to_string('myapp/password_reset_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': password_reset_token.make_token(user), }) to_email = user.email email = EmailMessage(mail_subject, message, from_email='testing@testing.com', to=[to_email]) email.send() After this, the user should be displayed with a view that asks for the user to fill a SetPasswordForm if the token is correct and it's a GET request. Or it should check for the token and check if the form is valid. If the form and token are valid then the password should be changed. I am trying to replicate a bit Django's PasswordResetConfirmView, but I'm not really sure if I'm doing it right. This is how I would do it, but I can't tell if there's any way to exploit the view somehow: def passwordResetConfirm(request, uidb64, token): if request.user.is_authenticated: return redirect("decks:index") try: uid … -
How to render results from groupby query in html - Django
I'm trying to render results of a group by query from a view to an HTML table but it is returning nothing. I originally had success in listing all results, but after applying the sum aggregation I can't get it to appear. Django View - with Group By def get_asset_price(request): # CryptoAssets is the model obj = CryptoAssets.objects.filter(user_id=request.user.id).values('symbol') obj = obj.aggregate(total_units=Sum('units'), total_cost=Sum('cost'))\ .annotate(total_units=Sum('units'), total_cost=Sum('cost'))\ .order_by('symbol') # Returns list of dictionaries context = { 'object': obj } return render(request, 'coinprices/my-dashboard.html', context) HTML <style> table, th, td { border: 1px solid black; } </style> <div class="container"> <h1>My Dashboard</h1> <table> <tr> <th>Symbol</th> <th>Total Units</th> <th>Total Cost</th> </tr> {% for row in object.obj %} <tr> <td>{{ row.symbol }}</td> <td>{{ row.units }}</td> <td>{{ row.cost }}</td> </tr> {% endfor %} </table> </div> {% endblock %} I'll provide the view below that worked without the group by. Django View - No group by def get_asset_price(request): # CryptoAssets is the model obj = CryptoAssets.objects.all().filter(user_id=request.user.id) # Returns list of objects context = { 'object': obj } return render(request, 'coinprices/my-dashboard.html', context) -
django-filter fieldset dependent on related field polymorphic ctype
class RelatedPoly(PolymorphicModel): common_field = ... class QweRelatedPoly(RelatedPoly): qwe = ... class RtyRelatedPoly(RelatedPoly): rty = ... class A(Model): related_poly = OneToOneField(RelatedPoly, ...) I also have a ViewSet for A model, and I need to implement a filterset_class which should be able to filter by both qwe and rty fields of RelatedPoly subclasses. In which ways could I achieve this? -
Django Nested Group By Data in template
here I explain my model, data, table structure, and expected result. My models are given below: class Buyer(models.Model): name = models.CharField(max_length=100) code = models.CharField(max_length=20 class Merchand(models.Model): name = models.CharField(max_length=100) code = models.CharField(max_length=20 class Order(models.Model): code = models.CharField(max_length=20) buyer = models.ForeignKey(CustomUser, on_delete=SET_NULL, related_name='br_order') merchand = models.ForeignKey(CustomUser, on_delete=SET_NULL, related_name='mr_order') value = models.FloatField(null=True, blank=True) qty = models.FloatField(null=True, blank=True) this is my model structure and my order model data is like this: {'code': 'C-001', 'buyer': 1, 'merchand': '1', 'qty': 100, 'value': '100'} {'code': 'C-002', 'buyer': 1, 'merchand': '1', 'qty': 100, 'value': '300'} {'code': 'C-003', 'buyer': 2, 'merchand': '2', 'qty': 100, 'value': '400'} {'code': 'C-004', 'buyer': 3, 'merchand': '2', 'qty': 700, 'value': '400'} {'code': 'C-005', 'buyer': 2, 'merchand': '2', 'qty': 900, 'value': '4500'} {'code': 'C-006', 'buyer': 2, 'merchand': '3', 'qty': 200, 'value': '2000'} {'code': 'C-007', 'buyer': 3, 'merchand': '2', 'qty': 700, 'value': '400'} {'code': 'C-008', 'buyer': 2, 'merchand': '2', 'qty': 900, 'value': '4500'} {'code': 'C-009', 'buyer': 2, 'merchand': '3', 'qty': 200, 'value': '2000'} I want to generate a table like this: = Buyer: 1, qty: 200, value: 400 - code: C-001, qty: 100, value: 100 - code: C-002, qty: 100, value: 300 = Buyer: 2, qty: 200, value: 13400 - code: C-003, qty: 100, value: … -
Python: sys.modules key points to diffenent module then the one it should originally point to
Running django-4.0.3, python-3.8.10; Python 3.8.10 (default, Nov 26 2021, 20:14:08) Type 'copyright', 'credits' or 'license' for more information IPython 7.27.0 -- An enhanced Interactive Python. Type '?' for help. In [1]: import sys In [2]: keys = sorted([key for key in sys.modules if 'lino_medico.lib.courses' in key]) ...: modules = tuple( ...: m ...: for m in map(sys.modules.__getitem__, keys) ...: ) In [3]: keys Out[3]: ['lino_medico.lib.courses', 'lino_medico.lib.courses.desktop', 'lino_medico.lib.courses.models'] In [4]: sys.modules[keys[-1]] Out[4]: <module 'lino_medico.lib.courses.desktop' from '/home/blurry/lino/env/repositories/medico/lino_medico/lib/courses/desktop.py'> In [5]: sys.modules['lino_medico.lib.courses.models'] Out[5]: <module 'lino_medico.lib.courses.desktop' from '/home/blurry/lino/env/repositories/medico/lino_medico/lib/courses/desktop.py'> In [6]: from importlib import import_module In [7]: import_module(keys[-1]) Out[7]: <module 'lino_medico.lib.courses.desktop' from '/home/blurry/lino/env/repositories/medico/lino_medico/lib/courses/desktop.py'> In [8]: keys[-1] Out[8]: 'lino_medico.lib.courses.models' In [9]: import weakref In [10]: isinstance(import_module(keys[-1]), weakref.ProxyTypes) Out[10]: False If you look at the keys in Out[3]: the last module name is 'lino_medico.lib.courses.models' but in Out[4]: as well as in Out[5]: and Out[7]: the key points to the file .../lino_medico/lib/courses/desktop.py instead of .../lino_medico/lib/courses/models.py. I am feeling out of my league here. Any help would be appreciated on explaining how this can happen. -
Django formset error: multiple values added are not saved, only the last value is saved
I'm using Django's formset to add the function to add multiple forms on one page. I want to receive all the Model fields from the form and save several objects through the '+' button only for the hour field. Currently, the code below accepts only the hour field in the form. In order to receive input of all fields from the form, is it necessary to input all fields in forms.py? With the code below, 'save' function works, but assuming that 5 'hours' field are entered, only the last value is added to DB. [models.py] class Supporting(models.Model): date = models.DateTimeField(blank=True, null=True) student = models.ForeignKey(Student, on_delete=models.CASCADE, blank=False, null=True) hour = models.CharField(max_length=2, blank=True, null=True) teacher = models.CharField(max_length=50, blank=True, null=True) comment = models.TextField(blank=True, null=True) technician = models.CharField(max_length=50, blank=True, null=True) [forms.py] from django import forms from django.forms import modelformset_factory from .models import Supporting SupportingModelFormset = modelformset_factory( Supporting, fields=('hour', ), extra=1, widgets={'name': forms.TextInput(attrs={ 'class': 'form-control', }) } ) [views.py] def add_supporting(request): if request.method == 'GET': formset = SupportingModelFormset(queryset=Supporting.objects.none()) elif request.method == 'POST': formset = SupportingModelFormset(request.POST) if formset.is_valid(): for form in formset: if form.cleaned_data.get('hour'): form.save() return HttpResponseRedirect('/supporting/') return render(request, 'supporting/add.html', {'formset': formset}) [supporting/add.html] {% block content %} <form class="form-horizontal" method="POST" action=""> {% csrf_token %} {{ formset.management_form … -
Handle many models using graphene in django
In my django project i have many different models which i want to query using GraphQL. For instance: class Country(): name = CharField(max_length) class Competition(): name = CharField(max_length) class Season(): name = CharField(max_length) class Team(): name = CharField(max_length) ... etc In my schema.py I need to create the GraphQL Types: class CountryType(): class Meta: model = models.Country fields = '__all__' class CompetitionType(): class Meta: model = models.Competition fields = '__all__' class SeasonType(): class Meta: model = models.Season fields = '__all__' class TeamType(): class Meta: model = models.Team fields = '__all__') ... etc And last but not least I have to create the Query class in the schema.py: class Query(graphene.ObjectType): country = graphene.relay.Node.Field(CountryType) competition = graphene.relay.Node.Field(CompetitionType) season = graphene.relay.Node.Field(SeasonType) team = graphene.relay.Node.Field(TeamType) all_country = graphene.List(CountryType) all_competition = graphene.List(CompetitionType) all_season = graphene.List(SeasonType) all_team = graphene.List(TeamType) def resolve_all_countries(root, info): return models.Country.objects.all() def resolve_all_competitions(root, info): return models.Competition.objects.all() def resolve_all_seasons(root, info): return models.Season.objects.all() def resolve_all_teams(root, info): return models.Team.objects.all() def resolve_country_by_name(root, info, name): try: return Country.objects.get(name = name) except Country.DoesNotExist: return None ... etc This all seems like much boilerplate code which adds unnecessary complexity and overhead. Of course for sophisticated queries you would need to write your own functions, but is this really "the way … -
Using Apache XAMPP on Windows 10 to create 1 Django website and one normal website
I have created a Django protect that works perfectly fine on windows Apache with Xampp. However, if I try to create a virtual host for a non-Django website, it doesn't work. If I then put my Django website into a virtual host it doesn't work, but then my non-Django website does work. By doesn't work I mean it takes me to this https://i.stack.imgur.com/DS0a5.png Here is all my code for my Django website inside a virtual host and my other non-project in a virtual host. #Django Wensote <VirtualHost *:443 _default_:443 neostorm.us.to:443> ServerName neostorm.us.to ServerAlias neostorm.us.to Alias /static "C:/xampp/htdocs/neostorm/static" <Directory "C:/xampp/htdocs/neostorm/static"> Require all granted </Directory> WSGIScriptAlias / "C:/xampp/htdocs/neostorm/neostorm/wsgi_windows.py" application-group=neostorm <Directory "C:/xampp/htdocs/neostorm/neostorm"> <Files wsgi_windows.py> Require all granted </Files> </Directory> ErrorLog "C:\xampp\apache\logs\neostorm_error.log" CustomLog "C:\xampp\apache\logs\neostorm_custom.log" common </VirtualHost> #Non Django Website <VirtualHost *:443 mail.neostorm.us.to:443> ServerName mail.neostorm.us.to DocumentRoot "C:/xampp/htdocs/webmail" <Directory "C:/xampp/htdocs/webmail"> Require all granted </Directory> </VirtualHost> Any help would be appreciated. -
Is it possible to get the selected date of DateRangeFilter in django admin.py?
I am trying to export the admin data into CSV file. For that i have to use start range and end range. So, i need to give the start date and end date manually the date is not fixed here. If i allow the user to select the date from DateRangefilter my job will be easy. After selecting the date i will allow them to export as CSV within two date ranges. Is it possible? example: Mymodel.objects.filter(created_at__range=(start_date, end_date)) Note: I have to do this functionality within the admin.py file. Not in frontend using javascript things. Please help me. Image link below https://i.stack.imgur.com/nWYNj.png -
Make a new model but no migrations are found
I currently have 1 model in my admin database called "Users" I was able to do a migration for this. But when I created another model, and when I try to migrate, there are no changes. class RegisterForm(models.Model): name = models.CharField(max_length=10) email = models.EmailField() password1 = models.CharField(max_length=20) password2 = models.CharField(max_length=20) admin.py: admin.site.register(RegisterForm) In my settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users', ] Ive tried doing python manage.py makemigrations users and python manage.py makemigrations Ive tried removing past migrations and editing the init file, but no luck. Could anyone provide me some guidance? Thanks! -
Is there a way to concatenate non related django models?
I have like 20 django apps in one project with their similar own models each represent a branch of a chain, the will simultaneously be doing CRUD operations? first of all, is this a good design? will it be too much on any online database? the second part is how to combine all the models for data representation? the models go something like this class App1(models.Model): serial = models.IntegerField() date_entry = models.DateField(default=datetime.date.today) company = models.ForeignKey(to=Company, on_delete=models.DO_NOTHING) product = models.ForeignKey(to=Product, on_delete=models.DO_NOTHING) weight = models.DecimalField(max_digits=10, decimal_places=2) country = models.ForeignKey(to=Country, on_delete=models.DO_NOTHING) cert_no = models.CharField(max_length=40) custom_cert_date = models.DateField() model 2 class App2(models.Model): serial = models.IntegerField() date_entry = models.DateField(default=datetime.date.today) company = models.ForeignKey(to=Company, on_delete=models.DO_NOTHING) product = models.ForeignKey(to=Product, on_delete=models.DO_NOTHING) weight = models.DecimalField(max_digits=10, decimal_places=2) country = models.ForeignKey(to=Country, on_delete=models.DO_NOTHING) custom_cert_no = models.CharField(max_length=40) custom_cert_date = models.DateField() and so on for each app I want to combine the weights of all models grouped by country, date_entry, and product one group by at a time?? I've tried this but it just concat them, doesn't add the weights, however the columns are the same? app1_data = App1.objects.filter(date_entry__gte=year1, date_entry__lte=year2).values('product__type').annotate( Sum('weight')).order_by('product__type') app2_data = App2.objects.filter(date_entry__gte=year1, date_entry__lte=year2).values('product__type').annotate( Sum('weight')).order_by('product__type') combined_data = list(chain(app1_data, app2_data)) will pandas help ? any help will be appreciated -
Type warning on pandas to_csv method path_or_buf variable given an HTTP response
I'm passing a pandas dataframe as csv file to the HTTP response and the code is working well. BUT I have here a warning on type hint on pandas' method to_csv on path_or_buf variable, Pycharm warns with : Expected type 'Union[str, PathLike[str], WriteBuffer[bytes], WriteBuffer[str], None]', got 'HttpResponse' instead This is the code used : def get_dataframe_response(request: Request) -> HttpResponse: my_dataframe: DataFrame = pd.DataFrame(<my_data_here>) get_dataframe_response: HttpResponse = HttpResponse(content_type="text/csv") get_dataframe_response["Content-Disposition" = "attachment; my_filename.csv" my_dataframe.to_csv(path_or_buf=get_dataframe_response, index=False, header=True) return get_dataframe_response -> Do you know what's causing this error or what should I use instead ? I tried get_dataframe_response.content but had issues and code stopped working. I saw pandas had issues even 6 months ago with type hints on path_or_buf variable already. But I want to make sure I use the right types. -
How does the Now() class works?
So I found a way to get the database timestamp and I tried to implement it for the first time def __str__(self): is_exp = 'EXPIRED' if self.date_created > Now() - datetime.timedelta(minutes=10) else 'AVAIL' return '{} {}'.format(self.code, is_exp) the code is used to see if a token is expired. I ran this code an it gave me this errpr '>' not supported between instances of 'datetime.datetime' and 'CombinedExpression' Now I've found some solution I've not tried yet but my main goal here is to understand what's going on. -
How to restrict access for personal profile page in django?
For example, I have a user: testuser. His personal page is users/account/testuser. How can I restrict access for his personal profile page, so only he can visit this page and for others it will be 403? I suggest I should use UserPassesTestMixin for it, but I don't know what to write in test_func. Actually I want to compare username from url, and user's username, and if it be equal, django will allow access to page. Or maybe there is another way to do it? View: class AccountInformationView(UserPassesTestMixin, DetailView): model = Profile template_name = 'users/account.html' def get_object(self, queryset=None): return get_object_or_404(User, username=self.kwargs.get('username')) def test_func(self): pass url: path('account/<str:username>', AccountInformationView.as_view(), name='account')