Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'int' object has no attribute 'days'. DurationField Django
I am trying to set default value of duration field. I want to send request without this value and then program get default value. If I send value 0 by postman it's okey but if I set defualt value as 0 then program treat it like int and i have this problem: "'int' object has no attribute 'days'". Is there any idea how to cast default value to duration field type ? -
Deploy both django and react on cloud using nginx
I have a digitalocean server and I have already deployed my Django backend server using gunicorn and nginx. How do I deploy the React app on the same server? -
How to unrar files in a django web application
I am trying to unrar files uploaded by users in django web application. I have gone through different approaches but none of them are working for me. The below methods work fine in my local OS (Ubuntu 18.04), but n't working in the server. I am using Python 3.6. import rarfile - here 'rarfile' is imported from python3.6/site-packages/rarfile. It is giving this error - bsdtar: Error opening archive: Failed to open '--' Following the steps suggested here, I installed 'unrar'. from unrar import rarfile - here it's being imported from python3.6/site-packages/unrar/ But this gave the error - LookupError: Couldn't find path to unrar library. So to solve the issue, I followed the steps mentioned here, and created UnRaR executable, and also set the path in my environment. This works fine in local, but unable to understand how to do the same in 'production environment'. import patoolib - importing from patool I also tried implementing patool, which worked fine in local but not in production and I am getting this error - patoolib.util.PatoolError: could not find an executable program to extract format rar; candidates are (rar,unrar,7z), This has become a big blocker in my application, can anyone please explain how to … -
how to rename fieldname in django_filters
I have created a Django-based webpage and using the Primary key and displaying id field. Here I am using django_filter and want to rename id field as DSID. Can anyone know the way to do it? any help in this issue would be appreciated from .models import * import django_filters class ShiftChangeFilter(django_filters.FilterSet): class Meta: model = ShiftChange fields = ['ldap_id', 'EmailID','id',] -
how to display a dropdown field predefined in my model?
class ItemDetails(models.Model): STATUS = ( ('In-Stock', 'In-Stock'), ('Out-of-Stock', 'Out-of-Stock'), ('issued-to', 'issued-to') ) serial_no = models.CharField(max_length=50,null=True) rem_qty = models.IntegerField(default=0) status = models.CharField(max_length=30, default='in-stock', choices=STATUS) model_no=models.ForeignKey(Items,on_delete= models.CASCADE) issued_to =models.ForeignKey(Prosecutions,on_delete=models.CASCADE) employee_name=models.CharField(max_length=50,null=True) created = models.DateTimeField(default=datetime.now()) -
Loading media files from a network drive in Django with Apache
I have a django page where I am trying to add a banner images which is stored in a network drive. In Dev environment: setting.py : MEDIA_URL = '/media/' MEDIA_ROOT = PureWindowsPath('//shared drive/folder/').drive urls.py: urlpatterns = [ path('admin/', admin.site.urls), ...... ...... ] urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) models.py: class WelcomePage(models.Model): departmentname = models.CharField(max_length=100,blank=True,null=True) bannerimage = models.ImageField(upload_to='DjangoPortal/welcome/images/',blank=True) home.html: <div class="card border-secondary mb-3"> <div class="card-body" style="padding: 0px !important;"> <img src="{{ pagedata.bannerimage.url }}" width="100%" /> </div> </div> with the above settings the page works perfectly In Production: All the above settings remains the same. In settings.py DEBUG =False and ALLOWED_HOSTS=[prod server ip, localhost] In httpd.conf I added below Define MEDIAROOT "//shared drive/folder/" Alias /media "${MEDIAROOT}" <Directory "${MEDIAROOT}"> Require all granted </Directory> but the image is not loading. Am I doing anything wrong? The technology specification is Windows Server 2012 R2 + Python 3.9 + Django 3.0.1 + SQL Server+ Apachelounge 2.4 Please guide if you have worked on or aware of this kind of scenario. -
I want to create a uniqueID for cutomers when they signup my webapp
I'm creating a signup page for my web app using Django and I would like to create a unique ID for customers when they signup in sequential order. ex:- first customer ID= 5000001 second customer ID:- 5000002 and so on I don't want the customer ID visible to the users. The customer Id is just for my purpose to create one to many relations to connect with their details in the database It would be really helpful if I can get some good suggestions -
Switch from default python interpreter to ipython in elpy (Django command)
Elpy uses the default python interpreter (elpy-django-command shell), I wondered if it is possible to use Ipython instead. -
Django alternative project structure
I have a django app which has alot of parts of the app seperated into files and folders like the following. app/ models/ __init__.py //imports everything from all model files my_app.py next_app.py ... views/ __init__.py //imports everything from all view files my_app.py next_app.py ... admin/ __init__.py //imports everything from all admin files my_app.py next_app.py ... It's not only 2 files in each folder, I'm getting close to 20 and it's starting to feel a bit messy. So, I came up with an alternative (which I've tested a bit so I think it works atleast), but I'm not sure if it's a bad idea to structure my project like this. (best practices etc.) This is my alternative: app/ modules/ my_app/ models.py views.py admin.py next_app/ models.py views.py admin.py models/ __init__.py //imports everything from models.py in every module in modules/ views/ __init__.py //imports everything from views.py in every module in modules/ admin/ __init__.py //imports everything from admin.py in every module in modules/ -
Textarea field return a string dictionary to convert dictionary in django
I am working on textarea which I pass a string dictionary format and get this value in views.py file it give string value like this output but when I want to convert in into diction is cause an error error here is my views.py file views.py here is html file: check.html -
Text after space character cut off in password text field using django
I tried to get the password field using the POST method in Django views. It showing the first halfword after space word it can't be shown. I will search for why it's happening. So the number of persons told the problem is in HTML page quotes are not properly used. but I will check my code all quotes are properly used. but I could not get the full text. how to solve this issue. Html Page <div class="form-control"> <input type="password" name="passwd1" value="{{ selected.passwd1 }}" class="input-lg" placeholder="Password" /> </div> <div class="form-control"> <input type="password" name="passwd2" value="{{ selected.passwd2 }}" class="input-lg" placeholder="Confirm Password" /> </div> How to solve this Issue. -
How to use Python FFmpeg Video Stream with Django?
I try to use Python FFmpeg Video Streamin like this web. I create function like this in views.py . def movie(request): video = ffmpeg_streaming.input('/static/media/images/Introduction.mp4') _360p = Representation(Size(640, 360), Bitrate(276 * 1024, 128 * 1024)) _480p = Representation(Size(854, 480), Bitrate(750 * 1024, 192 * 1024)) _720p = Representation(Size(1280, 720), Bitrate(2048 * 1024, 320 * 1024)) hls = video.hls(Formats.h264()) hls.representations(_360p, _480p, _720p) video_out = hls.output('/static/media/images/Introduction.m3u8') return render(request, 'index.html', {'movie':video_out}) When I run server it's show error like this. FileNotFoundError at / [WinError 2] The system cannot find the file specified Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.1.3 Exception Type: FileNotFoundError Exception Value: [WinError 2] The system cannot find the file specified Exception Location: C:\ProgramData\Anaconda3\lib\subprocess.py, line 1307, in _execute_child Python Executable: C:\ProgramData\Anaconda3\python.exe Python Version: 3.8.3 Python Path: ['c:\\DjangoMax\\maxmodify', 'C:\\ProgramData\\Anaconda3\\python38.zip', 'C:\\ProgramData\\Anaconda3\\DLLs', 'C:\\ProgramData\\Anaconda3\\lib', 'C:\\ProgramData\\Anaconda3', 'C:\\ProgramData\\Anaconda3\\lib\\site-packages', 'C:\\ProgramData\\Anaconda3\\lib\\site-packages\\win32', 'C:\\ProgramData\\Anaconda3\\lib\\site-packages\\win32\\lib', 'C:\\ProgramData\\Anaconda3\\lib\\site-packages\\Pythonwin'] I have the problem at line video_out = hls.output('/static/media/images/Introduction.m3u8') It's not show error when I comment this line. How to use Python FFmpeg Video Stream with Django? -
Remove a queued task if the related object does not exist
I am trying to delete a queued task (using Celery) which is triggered when an object is created. If, the task is to be triggered 2 min before an event and the object is deleted already, the queued messages remain. task.py @app.task def send_notification(): # do some stuff # return something models.py class ABC(models.Model): description = models.TextField() views.py def abc(request): # create the ABC object send_after=timezone.now() + timedelta(minutes=5) send_notification.apply_async(eta=send_after) # return something So, when the object ABC is deleted right after creating one, the related queued message should also be deleted. Any idea on how to handle this ? -
Possible to delete an object's specific row in django?
I have model that creates several different rows. Like this... class Myteam(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) QB = models.CharField(max_length=80, null=True) RB1 = models.CharField(max_length=80, null=True) WR = models.CharField(max_length=80, null=True) TE = models.CharField(max_length=80, null=True) D = models.CharField(max_length=80, null=True) K = models.CharField(max_length=80, null=True) In my template, I'm looping through the rows and displaying them as html table rows. I've added a delete function to each row because I'd like the app's user to be able delete a player from their "Myteam" object. Problem is, I can only delete the entire object because there's only one id which is for the entire object. The template looks like this right now. Here's two rows as an example. <tbody> {% for t in team %} <tr> <td id="" > {{ t.QB }} <a href="{% url 'delete_player' t.id %}">Delete</a> </td> <tr> <td> {{ t.RB1 }} <a href="{% url 'delete_player' t.id %}">Delete</a> </td> </tr> <tr> I did come across one possible solution here which suggested using {{ forloop.counter }} to assign individual id's to the row, but I can't get this to work how I would like. Just in case, here's the views.py def delete_player(request, id): player = Myteam.objects.get(id=id) player.delete() return redirect('show') I feel like there's probably … -
Retrieving UUIDs in Django
I wrote a model that has a UUID generated as the primary key. When a POST request is made to add an entry to the table, the fields that are sent in the request are all the fields except for the uuid. Once I have added the new entry to the table, how can I retrieve its generated UUID? -
Django - Crispy Forms Layout Not Working as Expected
I'm aiming to add a '$' onto an input box of a form. Below is the form: class StgAccrualForm(ModelForm): class Meta: model = Stg_Monthly_Accrual exclude = ['stg_location_param', 'date_of_service'] localized_fields = '__all__' def __init__(self, *args, **kwargs): super(StgAccrualForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_show_labels = False self.helper.layout = Layout( PrependedText('rev_amount', '$')) I'm rending the rev_amount field of Stg_Monthly_Accrual as {{ rev_amount | as_crispy_field }}; however, the input box for rev_amount does not have a '$'. I'm bringing in the appropriate tags {% load crispy_forms_tags %} as well. What am I missing? Is it that layout does not work with as_crispy_field and only {% crispy form %}? -
How to use IN query in Django ORM?
How do I run the Where IN query in Django ORM and iterate it? The following returns nothing: user_ids = Wallet.objects.filter(customer_id=[sender_id,reciever_id]) print(user_ids) -
How to periodically change the order of two elements in each row of a div
In one of the HTML files of my Django project, I have a div that contains a col-6 for an image and a col-6 for a text. {% if automotives %} {% for automotive in automotives %} <div class="row"> <div class="col-6 mb-4 mb-md-0 my-5 pl-5"> <h3 class="font-weight-bold">{{ automotive.title }}</h3> <p class="text-muted">{{ automotive.description|safe }}</p> </div> <div class="col-6 mb-4 mb-md-0 my-5 pr-5"> <div class=" overlay z-depth-1-half"> <img src="{{ automotive.cover.url }}" class="img-fluid" alt="cover"> </div> </div> </div> {% endfor %} {% endif %} I read title and description and cover from the database. I want to periodically change the order of image and text in each row. I have no idea how to do it. and I don't know much about js or jquery. any help is appreciated. -
How can i use order_by for persian list in django?
There is list of name ['هاشمی','آذری','واحدی'] ,i want to sort this list that is out put of drf in django .but order_by in django works for arabic language do not work for persian language. for example in persian language after sort it must be ['آذری','واحدی','هاشمی'] ... but it has problem and after sort it is ['آذری','هاشمی','واحدی']. -
I want the data of table row, the table whose checkbox is checked. My table row is in for loop
I want the data of table row, the table row whose checkbox is checked. My table row is in for loop.I want anyone to come and check the checkbox and submit the form and store the complete data of that table row in the database.i tried with ajax but i think may be it can be done by django-template. here is my index.html : <form name="form" method="POST" id="form"> {% csrf_token %} <table class="table table-bordered table-responsive" id="flip-scroll"> <thead> <tr> <th scope="col">Visa Option</th> <th scope="col">Processing Type</th> <th scope="col">No. Of Visa</th> <th height="60" scope="col">Travel Date</th> <th scope="col">Price</th> </tr> </thead> <tbody> {% for j in package %} <tr class="valid-container" data-id="{{ j.id }}"> <td style="cursor:pointer;" width="200"><input type="checkbox" name="c1">&nbsp; <output class="visa_type" style="font-size:14.5px !important;">{{ j.visa_type }}</output></td> <td height="52" width="158"> <select class="custom-select processing_type" name="processing_type" required> <option value="{{ j.price }}" selected>Normal</option> <option value="{{ j.express_price }}">Express</option> </select> </td> <td height="52"> <select class="custom-select no_of_person" name="no_of_person" required> <option value="1" selected>1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> </select> </td> <td width="190" height="60"> <div class="input-group date" data-date-format="dd.mm.yyyy"> <div class="input-group mb-2"> <input type="text" class="form-control travel_date" name="travel_date" value="dd.mm.yyyy" placeholder="dd.mm.yyyy"> <div class="input-group-text"><i class="ti-calendar"></i></div> <div class="input-group-addon"> </div> <div class="input-group-prepend"> </div> </div> </div> </td> <td width="166">{{ j.currency_type … -
Can Django do a flexible `JOIN TABLE` like SQL Alchemy?
According to my current understanding, Django can not do a left join table as flexible and easy as SQLalchemy. For example we have these two table: Table: Transport_Rules Type Origin_id Destination_id Cross country 4 1 Cross state 4 5 Table: Mapping_Country Name ID New York 4 California 5 Paris 1 Target: Finding the type in the table Transport_Rules with inputs are destination_name and origin_name. Provided: ori_name = New York dest_name = California How I did it in SQL Alchemy: map1 = aliased(Mapping_Country, name='map1') map2 = aliased(Mapping_Country, name='map2') rule = Session.query( Transport_Rules.type, Transport_Rules.origin_id, Transport_Rules.destination_id ).join( map1, Transport_Rules.origin_id == map1.ID ).join( map2, Transport_Rules.destination_id == map2.ID ).filter( and_( map1.Name==ori_name, map2.Name==dest_name ) ).all() How I did it in Django: provided no assign foreign key in setting up model since I have not understood the logic of it yet. origin_id = Mapping_Country.objects.filter(name = ori_name).values('ID')[0]['ID'] destination_id = Mapping_Country.objects.filter(name = dest_name).values('ID')[0]['ID'] rule = Transport_Rules.objects.filter(Origin_id = origin_id, Destination_id = destination_id ).values() Even through, visually, Django may looks shorter but if we have multiple joins. Doing it would be very annoying. Main Question: Can Django do left join making connection like SQL query. Is the only solution to define foregin key in models setting ? -
Add verify field with each field in dhango model
I am creating a table for user detail. After user registration, Admin verify every detail with documents uploaded by user. Like Name, Surname with Passport. class User(AbstractUser): name = models.CharField(max_length=30) surname = models.CharField(max_length=30) I am trying this. add a json field verified_fields ({'fields': ['verified', 'fields', 'name']}) in model. I will add fields in value of "fields" which has been verified. But I think I may have problems using this data in templates. Is there any better method to do this. User also have multiple status. I have to save time when user's status changes. like user activated on 12, became employee on 20, became something else on 30. I am thinking another table to save these changes. table with fields user, new_status(that has been changed to) and date. If anyone have better idea, please suggest. -
How to raise or return 405 method not allowed in Django
I want to raise or return a 405 Method not allowed but I cannot find how. Like in Flask you could do abort(405). Is there anyway to raise or return a Django 405 exception. -
django_admin - command not found
Followed the installation steps but I'm getting an error zsh: command not found: django-admin I can see django and django-admin.py present under /Users/simd/Library/Python/2.7/lib/python/site-packages/bin but for some reason not able to access it. I've even tried chmod command suggested in the Django documenation, but no luck. I'd be really grateful if someone can help me out, Thanks! I'm using MacOS Catalina -
drf authtoken Unable to log in with provided credentials
i'm using token authentication with customuser and also have customemail backend. i also tried to use custome token serializer because its using email for auth. it seems to be working with user created by admin but user created by rest api not able to login showing this error. loginview: @csrf_exempt @api_view(["POST"]) @permission_classes((AllowAny,)) def login(request): serializer = AuthCustomTokenSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token, created = Token.objects.get_or_create(user=user) return Response({'token': token.key}, status=status.HTTP_200_OK) serializer.py: class AuthCustomTokenSerializer(serializers.Serializer): ''' Changing Token auth to use email instead username ''' email = serializers.EmailField(label=_("Email")) password = serializers.CharField( label=_("Password",), style={'input_type': 'password'}, trim_whitespace=False ) def validate(self, attrs): email = attrs.get('email') password = attrs.get('password') print(email, password) if email and password: user = authenticate(username=email, password=password) print("this is user", user) # The authenticate call simply returns None for is_active=False # users. (Assuming the default ModelBackend authentication # backend.) if not user: msg = _('Unable to log in with provided credentials.') raise serializers.ValidationError(msg, code='authorization') else: msg = _('Must include "username" and "password".') raise serializers.ValidationError(msg, code='authorization') attrs['user'] = user return attrs class CustomUserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True, required=False) class Meta: model = CustomUser fields = ('id', 'first_name', 'last_name', 'email', 'mobile_number', 'password', 'is_active', 'user_type', 'otp') def create(self, validated_data): user = CustomUser( email=validated_data['email'], mobile_number=validated_data['mobile_number'], first_name=validated_data['first_name'], last_name=validated_data['last_name'], user_type=validated_data['user_type'], ) user.set_password(validated_data['password']) …