Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get the float result with certain precision in the F() expressions of Django queryset
addon_income = round(pendingAmount*0.1, 2) print(addon_income) # if pendingAmount = 6, addon_income = 0.6 which is ok here Wallet.objects.filter(id=###).update( active=F('active')+addon_income, total=F('total')+addon_income, uddate_time=timezone.now() ) In the queryset above, if the F('active') = 41.2, F('total') = 41.2, and addon_income = 0.6, the active and total becomes 41.800000000000004 and 41.800000000000004 after the updating. I tried to use round() in the queryset as shown below: Wallet.objects.filter(id=###).update( active=round(F('active')+addon_income, 2), total=routn(F('total')+addon_income, 2), uddate_time=timezone.now() ) but it returns error: type CombinedExpression doesn't define round method Anyone has any suggestion? Thx! -
Django - Change model field in script and migrate
I am creating a Django project where I have a field that automatically generates random ids. I want to start with max_length = 1 and increase it everytime there are no more unique ids left. For example: I use string.ascii_letters + string.digits + ["$-_+"] for random ids. With max_length = 1 there are 66 unique ids left. When I have created the 66. object, max_length should be updated to 2 and my database should be migrated. Now I have 66^2 - 66 ids left. Here's what I tried: class RandomIDMixin(models.Model): id = models.CharField(max_length=settings.DATABASE_ID_MAX_LENGTH, editable=False, primary_key=True, verbose_name="ID", unique=True, default=None) class Meta: abstract = True @receiver(pre_save) def pre_saver(sender, instance, **kwargs): if issubclass(sender, RandomIDMixin): choices = random.choices(string.ascii_letters + string.digits + ["$-_+"] max_length = sender._meta.get_field('id').max_length if instance.objects.all().count() == len(choices)**max_length: # change somehow the database call_command("makemigrations", interactive=False) call_command("migrate", interactive=False) if instance.id is None or instance.id is "": while sender.objects.filter(id=instance.id).exists() or instance.id is None or instance.id is "": instance.id = "".join(, k=sender._meta.get_field('id').max_length)) -
django-select2: how to disable City selection if no Country is selected? (django 2.2)
I try to use dependent fields like this: class AddressForm(forms.Form): country = forms.ModelChoiceField( queryset=Country.objects.all(), widget=ModelSelect2Widget( model=Country, search_fields=['name__icontains'], ) ) city = forms.ModelChoiceField( queryset=City.objects.all(), widget=ModelSelect2Widget( model=City, search_fields=['name__icontains'], dependent_fields={'country': 'country'}, ) ) But the City choises are available if no Country is selected. I want to restrict user to select City without selecting Country. -
how to filter with month and year in django
i have form to filter students by joined year and month.this code working fine for year but it is not working with month.how can i solve this. I only can filter the results by year but not from month.It displays no data available for the month. models.py class Student(models.Model): name = models.CharField(max_length=100) email = models.EmailField() phone = models.CharField(max_length=15) joined_date = models.DateField() views.py def serachstudent(request): q = request.GET["q"] if q: students = Student.objects.filter(Q(joined_date__year__icontains=q)|Q(joined_date__month__icontains=q)) return render(request, "students/view_students.html", {'students': students}) else: return redirect('students:view_student') template <form action="{% url 'students:search_student' %}" class='form-inline'> <!--<label for="month"></label>--> <select name="q"> <option disabled selected>Select Year</option> <option value="2018">2018</option> <option value="2017">2017</option> <option value="2019">2019</option> </select> <!--<label for="month"></label>--> <select name="q"> <option disabled selected>Select month</option> <option value="01">January</option> <option value="02">February</option> <option value="03">March</option> <option value="04">April</option> <option value="05">May</option> <option value="06">June</option> <option value="07">July</option> <option value="08">August</option> <option value="09">September</option> <option value="10">Octbor</option> <option value="11">November</option> <option value="12">Decembery</option> </select> &nbsp; &nbsp; <div> <button type="submit" >Find Students</button> </div> </form> -
Error in Django to show the sender's email
I am trying to view the sender's email that is being sent to the email host. I am able to send emails to the email_host_user using environment variables and have allowed access for less secure apps in Yahoo account. However, when I do the "from_email" I received an error: SMTPSenderRefused--(550, b'Request failed; Mailbox unavailable', 'bill@yahoo.com')--'bill@yahoo.com is just a random sender's email though I am not able to send to the email_host. I think there must be some issues with my views.py? I appreciate your feedback! settings.py EMAIL_HOST='smtp.mail.yahoo.com' EMAIL_HOST_USER=os.environ.get('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD=os.environ.get('EMAIL_HOST_PASSWORD') EMAIL_PORT=587 EMAIL_USE_TLS=True EMAIL_BACKEND='django.core.mail.backends.smtp.EmailBackend' print(os.environ.get('EMAIL_HOST_USER')) print(os.environ.get('EMAIL_HOST_PASSWORD')) print(os.environ.get('SECRET_KEY')) views.py def contact(request): if request.method=='POST': message=request.POST.get('message', '') from_email=request.POST.get('from_email', '') send_mail('Contact Form', message, from_email, [settings.EMAIL_HOST_USER], fail_silently=False ) return render(request, 'first_app/contact.html') contact.html <form action="/contact" method="POST"> {% csrf_token %} <input type="email" name="from_email" placeholder="Your email"> <textarea name="message" placeholder="Message..."> </textarea> <input type="submit"> </form> -
Extend Django Admin Tools template
Is there a way I can override the brand block of django-admin-tools, which extends from Django's admin app? If there is, how? I tried placing base_site.html in one of the templates folders of my project, but Django is not picking it up, assumably because django-admin-tools has priority over the other templates because of the order of the apps in my settings. But if I change the order, django-admin-tools stops working as it's required to be at the top in my settings. -
Django unable to create related model
I have 2 models: CustomerDevice and DeviceStatus like this: # models.py class CustomerDevice(models.Model): customer_uuid = models.ForeignKey(Customer, on_delete=models.CASCADE) customer_device_uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) group_uuid = models.ForeignKey(DeviceGroup, null=True, blank=True, on_delete=models.SET(get_default_group)) device_id_android = models.CharField(max_length=100, blank=True, null=True) class DeviceStatus(models.Model): device_status_uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_index=True) disk_space = models.PositiveIntegerField(blank=True, null=True) battery_level = models.PositiveIntegerField(blank=True, null=True) battery_health = models.CharField(max_length=30) battery_cycles = models.PositiveIntegerField(blank=True, null=True) customer_device = models.ForeignKey(CustomerDevice, on_delete=models.CASCADE, related_name="customer_device") Currently I have an API endpoint that takes 7 parameters: customer_uuid device_id_android disk_space battery_level battery_health battery_cycles customer_device_uuid My serializers: # serializers.py class DeviceGroupSerializer(serializers.ModelSerializer): class Meta: model = DeviceGroup fields = ('group_uuid', 'device_group_name', 'color', 'is_default') class DeviceStatusSerializer(serializers.ModelSerializer): class Meta: model = DeviceStatus fields = ('disk_space', 'battery_level', 'battery_health', 'battery_cycles') class CheckinSerializer(serializers.ModelSerializer): device_group = DeviceGroupSerializer(many=False, read_only=True, source='group_uuid') status = DeviceStatusSerializer(source='customer_device', many=True, read_only=True) class Meta: model = CustomerDevice fields = ('customer_device_uuid', 'customer_uuid', 'device_id_android', 'device_group', 'status') extra_kwargs = { 'customer_uuid': {'write_only': True}, 'device_id_android': {'write_only': True}, } When all parameters are passed, I want to create a new instance of DeviceStatus where the customer_device field is the related CustomerDevice model. When I send a POST request with the corresponding data it gives me an error: Cannot assign "'fa52a064-5543-4dee-a604-d434faf84330'": "DeviceStatus.customer_device" must be a "CustomerDevice" instance. I am able to create the DeviceStatus in Django Admin. The … -
Python: call to self function not working correctly
This seems like a very simple issue, and though I have a workaround I would like to fix it nicely. EDIT: I am using a Django system, so the groups variable is actually inherited/retrieved from a DB) I just tried to make a minimal example, but I realised that that was not conducive to solving my issue I have a class: class Invite(models.Model, IndexedModelMixin): def get_associated_groups(self): return self.groups But when I call get_associated_groups elsewhere def get_groups(resource_object): resource_group_objects = resource_object.get_associated_groups() where Invite is the resource_object, this error is thrown: get_associated_groups() missing 1 required positional argument: 'self' My workaround currently is resource_group_objects = resource_object.get_associated_groups(resource_object) Why isn't the self call implicit? -
Django one-to-many (association same table)
I am new to Djnago's ORM. I have a resource Thing that has tags Tag Normally I would have three tables: things tags thing_tag_associations When I read one-to-many posts on Django, they usually have to do with an object that's has many fields foreign-keyed to many tables. How should I set up a Django model that uses one resource that has many associations to another table? This would actually be a zero-to-many. I can't set up an array row and have each row FK because indexes woudln't work that way. Using an association table seem to be only way I can think of. Are zero-to-many association tables using models supported in Django? -
Why are my dropdown options updating after my Ajax call in the source code but not in the UI?
I have a few django dropdown buttons that I want are originally empty, but I have a script that is called to go fetch the drop down options. I see the options populate in the source code, but they don't actually appear in the UI when I click on the drop down. Am I writing my Ajax call incorrectly? html: <div> <table> <tr> <td> <!-- adding dropdown selector for cryptocurrency symbol (type) --> <div id="symbol_selection" class="input-field col s12"> <select id="selected_symbol"> <option value="" disabled selected>Choose your CryptoCurrency</option> </select> </div> </td> <td> <!-- adding dropdown selector for cryptocurrency market (physical currency type) --> <div id="market_selection" class="input-field col s12"> <select id="selected_market"> <option value="" disabled selected>Choose your Market</option> </select> </div> </td> <td> <!-- adding function test button --> <a class="waves-effect waves-light btn" id="test_btn" onclick="test_fxn()">Run Test</a> </td> </tr> </table> </div> My Ajax Call: $( document ).ready(function() { $.ajax({ method: 'GET', url: "dropdowns", data:{"gettem":"gettem"}, success:function(data){ var op_items = data.symbols; var markets = data.markets; for(var i = 0 ; i < op_items.length; i++){ console.log(op_items[i]) option = "<option value="+ op_items[i]+">"+ op_items[i].toString() +"</option>"; $("#symbol_selection select").append(option); } for(var i = 0 ; i < markets.length; i++){ console.log(markets[i]) option = "<option value="+ markets[i] + ">"+ markets[i] +"</option>"; $("#market_selection select").append(option); } }, … -
How to keep the data consistent between redis cache and mysql?
When I updated the data of mysql dabatase, the redis cache was not updated in time. What should I do to make mysql data change, redis can also clear the old cache in time? -
Django FileField() disable upload
I have a FileField() in a Django model. On save(), I intercept this and upload the actual file data to a remote-backend/Bucket, then save the URL returned from the service in another field. The file actually uploads to my file-system (I believe). How can I disable the FileField() to not actually upload the file to wherever media is stored with Django? -
how to override default Django form validation error
I try this but it doesn't work. default error message is shown only.please help from django import forms from SharedApps_Application.models import certificateDb from django.contrib.admin.widgets import AdminDateWidget from django.forms.fields import DateField my_default_errors = { 'required': 'Application field is required', } class CertificateForm(forms.ModelForm): startdate = forms.DateField(widget = forms.SelectDateWidget(years=range(1995, 2100))) expiredate = forms.DateField(widget = forms.SelectDateWidget(years=range(1995, 2100))) application = forms.CharField(error_messages = my_default_errors) class Meta: model = certificateDb fields = ('application', 'startdate', 'expiredate', 'environment_type','File' ) -
how dynamically generate excel from dataframe and send as a Email in Python?
I have data in the form of nested list. i am converting this data into dataframe. Now i want to convert this dataframe into excel (without storing on local system) and attach/dynamically send mail with this excel file as a attachment i can download the excel file on local system and then attach to mail and send this mail but i dont want to store locally it is directly generate and attach to mail and send data = [['1', 'Ram', 'PL', 'NA', '04/24/19'];['2', 'Dhana', 'PL', 'NA', '04/24/19'],['3', 'Nares', 'A', 'NA', '04/24/19']] df = pd.DataFrame(data, columns=['ad_id','ename','shift','status','date']) output ad_id ename shift status date 0 458435 Ram PL NA 04/24/19 1 471611 Dhana PL NA 04/24/19 2 476934 Naresh A NA 04/24/19 I expect it directly generate the excel file and attach to mail and send -
How to query the implicit through table in django (ManyToMany field)?
In the django documentation it reads the following: If you don’t specify an explicit through model, there is still an implicit through model class you can use to directly access the table created to hold the association. However, I can not find out how I can access this table. Say I have this structure: class Person(models.Model): name = models.CharField(max_length=50) class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person) And I would like to query the table that holds the person_groups (the implicit through table)... how do I do this? PersonGroup.objects.all() That does not work, and I can't find what syntax I should be using. -
Django: database filter output displays <QuerySet [<model: model object (value)>]>
I am new to django, i am trying to import the data from a database by using multiple filters. views.py from django.shortcuts import render from django.http import HttpResponse from .models import NodesdataArchive # Create your views here. def home_view(request, *args, **kwargs): data = NodesdataArchive.objects.filter(status=1, vendor='F5', location='NA') host = { "dns" : data } return render (request, "home.html", {'posts': host}) After using multiple query i am selecting only the object "dns" to show. when i checked the value of the "host" variable its showing the right output. when i load it in the html template, its showing complete output which is shown in the "host" variable not the exact value alone. current output : "QuerySet [NodesdataArchive: NodesdataArchive object (austin)>]>" Expect output to show in the html template: austin Please help, thanks !!! -
In Django ,css file is not loaded
Please tell me why static file can not be read. I can read an image file but I can not read css and js file. I see related questions elsewhere, but I can't solve them so I ask. #settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap4', 'myapp.apps.MyappConfig', ] STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'assets'), ) My directory structure. Projects -assets —css —style.css —image —js —style.js -media -projects —__init__.py —settings.py —urls.py —wigs.py -myapp —migrations —__init__.py —admin.py —apps.py —models.py —tests.py —views.py base.html #html <!DOCTYPE html> {% load static %} {% load bootstrap4 %} {% bootstrap_css %} {% bootstrap_javascript jquery='slim' %} <html lang="ja"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link href="https://fonts.googleapis.com/earlyaccess/sawarabigothic.css" rel="stylesheet" > <link href="{% static 'css/style.css' %}" rel="stylesheet"> <title>Myapp</title> {% include "navi.html" %} </head> <body> {% block content %}{% endblock %} </div> <script src="{% static 'js/style.js' %}"></script> </body> </html> Although it is not here, the image file can be load. <div class="text-center" style="background-image: url({% static 'image/back-image.jpg' %});"> -
Unsupported media type "application/json;charset=utf-8" in request. Django/React file upload
File uploading issue from react to djano I am trying to upload image file from react to django but getting error: Unsupported media type "application/json;charset=utf-8" in request. * DJANGO * class CreateFileProject(viewsets.ModelViewSet): queryset = Project.objects.all() serializer_class = ProjectCreateSerializer parser_classes = (FormParser, MultiPartParser) def perform_create(self, serializer): file_obj = self.request.FILES['file'] print(file_obj) class Project(models.Model): category = models.ForeignKey(Category,on_delete=models.CASCADE) title = models.CharField(max_length=100,blank=True,null=True) description=models.CharField(max_length=600,blank=True,null=True) file=models.ImageField(upload_to='project_mainimage') videourl=models.CharField(max_length=450,blank=True,null=True) project_rank=models.IntegerField() objects=models.Manager() * REACT * this.setState({mainimage:evt.target.files[0]} const fd=new FormData(); fd.append('file',this.state.imgarray[0]); console.log("Submitted file ",this.state.imgarray); let payload={ main_image:fd }; axios.post('http://127.0.0.1:8000/portfolio/route/createproj/',payload); -
How to unit test djano-rest-framework api with data along with imagefield
I have a model that includes a ImageField along with other datas (int,text,etc). And I have api with method POST to create data with image file. Problem is, how to test this POST api that includes imagefield. Want to create fake image in test file instead of real file and how to test this along with other data. serializer.py class CategorySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Category fields = ( 'id','name','description','parent_id','start','end') read_only_fields = ('id','name','description','parent_id','start','end',) class ServiceProviderSerializer(serializers. HyperlinkedModelSerializer): category = CategorySerializer(many=True, read_only=True) class Meta: model = ServiceProvider fields = ( 'id', 'country_code', 'city', 'zip_code', 'service_type', 'preffered', 'display_bann', 'detail_name', 'detail_address', 'detail_description1', 'detail_description2', 'photo', 'category', ) read_only_fields = ('id',) def create(self, validated_data): """ Overriding the default create method of the Model serializer. """ # category_data = validated_data.pop('category') category_data = self.context['request'].data.get('category') service_provider = ServiceProvider.objects.create(**validated_data) category_data = json.loads(category_data) for category in category_data: categoryObj = Category.objects.get(pk=category['id']) service_provider.category.add(categoryObj) return service_provider test.py def setUp(self): self.new_service_provider = { 'country_code': "DE", 'city': "FRANKFURT AM MAIN", 'zip_code': 60435, 'service_type': "Fitness Studio", 'preffered': True, 'display_bann': "?", 'detail_name': "City Fitness Frankfurt", 'detail_address': "Trakehner Str. 5, 60487 Frankfurt am Main", 'detail_description1': "Based on review, we suggest you to go to this studio", 'detail_description2': "", 'category':[{'id':self.category1.pk}] } def test_post_service_provider(self): self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.adminUser.auth_token.key) # get API … -
How can you send information from the local python tkinter app to the django server?
I am trying to send information from my tkinter app (which is basically a desktop app for filling out a form and submitting it) to my website that uses Django and PostgreSQL and store that form information in my database -
Some reason I get an error with using Datatables on the live server - Django
Datatables seem to be a little very sensitive it seems. I need to use it so I have no other options. This is the error I am getting on live... but this works fine on my local machine which is very weird and odd as both environments are the same: DataTables warning: table id=datatables - Ajax error. For more information about this error, please see http://datatables.net/tn/7 No error at all on the inspect element just a nice 502 error. Template File <div class="card data-tables"> <div class="card-body table-striped table-no-bordered table-hover dataTable dtr-inline table-full-width"> <div class="toolbar"> </div> <div class="fresh-datatables"> <table id="datatables" class="table table-striped table-no-bordered table-hover" cellspacing="0" width="100%" style="width:100%"> <thead> <tr> <th data-data="reference_number" data-name="reference_number">Reference Number</th> <th data-data="tracking_number" data-name="tracking_number">Tracking Number</th> <th data-data="order_number" data-name="order_number">Order Number</th> <th data-data="expected_arrival" data-name="expected_arrival">Expected Arrival</th> <th data-data="tracking_status_name" data-name="tracking_status_name">Tracking Status</th> <th data-data="modified_date" data-name="modified_date">Modified Date</th> <th class="disabled-sorting text-right">Actions</th> </tr> </thead> </table> </div> </div> </div> <script type="text/javascript"> $(document).ready(function() { var t = $('#datatables').DataTable({ pagingType: "full_numbers", lengthMenu: [ [10, 25, 50, -1], [10, 25, 50, "All"] ], serverSide: true, ajax: '/api/tracking/view/?format=datatables', columns: [ {"data": "reference_number", "name": "reference_number", "searchable": true, "orderable": true, fnCreatedCell: function (nTd, sData, oData, iRow, iCol) { $(nTd).html("<a href='/tracking/edit/"+oData.id +"'>"+oData.reference_number +"</a>"); } }, {"data": "tracking_number", "name": "tracking_number", "searchable": true, "orderable": true}, {"data": "orders.order_number", … -
Problem adding image url in for loop in django
I'm making a webpage to crawl rss feed contents in django. I'm new in python n django...i'm facing a problem with for loop.. only first image url of rss feed shows on the webpage...and it keep looping after all content. i want to show respective image url of every post Input rss feed is : http://feeds.bbci.co.uk/news/rss.xml Views.py from django.shortcuts import render from django.http import HttpResponse import feedparser def index(request): if request.GET.get("url"): url = request.GET["url"] feed = feedparser.parse(url) feed1 = feed['entries'][0] feed2 = feed1['media_thumbnail'][0]["url"] else: feed = None return render(request, 'rss/reader.html', { 'feed' : feed, 'feed2' : feed2, }) reader.html {% if feed %} <h2>{{ feed.feed.title }}</h2> {% if feed.entries %} {% for entry in feed.entries %} <div> <p>{{ entry.published }}</p> <p>Headline: {{ entry.title }}</p> <p>Link: <a href="{{ entry.link }}">Go >>></a></p> <p>Description: {{ entry.description }}</p> </div? {% for entry1 in feed2 %} ###here is the probelm <div> {{ entry1 }} </div> {% endfor %} {% endfor %} {% endif %} {% else %} <p>Enter your favorite RSS feed above.</p> {% endif %} {% endblock %} -
How to filter data with year and month in Django DateField
I want to filter students with joined_date and month separately from datefield. How can I do that? I tried this but I think it is not the right way. models.py class Student(models.Model): name = models.CharField(max_length=100) address = models.CharField(max_length=200) email = models.EmailField() phone = models.CharField(max_length=15) image = models.ImageField(upload_to='Students',blank=True) joined_date = models.DateField() def __str__(self): return self.name views.py def serachstudent(request): year_list = Student.objects.all().dates('joined_date', 'year') month_list = Student.objects.all().dates('joined_date','month') year = request.GET['q'] month = request.GET['q'] if year or month: for years in year_list: for months in month_list: Student.objects.filter(Q(joined_date__contains=years.year)|Q(joined_date__icontains=months.month)) return redirect('students:view_student') else: return redirect('/students/') template <form action="{% url 'students:search_student' %}" class='form-inline'> <!--<label for="month"></label>--> <select name="q" id="1"> {% for years in joined_date %} <option value="">Select Year</option> <option value="{{year}}">{{year}}</option> {% endfor %} </select> <!--<label for="month"></label>--> <select name="q" id=""> {% for months in joined_date %} <option value="">Select month</option> <option value="{{month}}">{{month}}</option> {% endfor %} </select> &nbsp; &nbsp; <div> <button type="submit" >Find Students</button> </div> </form> -
Django core serializers converting datetime as string("2019-04-24T00:00:00") not keeping Unix time (1556087567237)
from django_unixdatetimefield import UnixDateTimeField class Sample(models.Model): sample_start = UnixDateTimeField() in my database value is storing as unix time (1556087727) but when serializing using Django.core serializers, the format becomes "2019-04-24T00:00:00" -
Make one access-token per username and password in django oauth toolkit
Is there any way to restrict the return access token in via Django Oauth with grant_type=password for per username. I can see every time I request an access token it will create a new token no matter it already has an access token with this username. Especially every time I try to login into the system with username and password. It will make our database has a lot of useless Token. Is there any way or I should manually check if this username is already had a token and return to the consumer. curl -X POST -d "grant_type=password&username=myusername&password=mypass&scope=read" -u "fjsdfj39jdfjskdljf:da932iajf90jsafjsdfj39jdfjskdljffsalfj#9" http://localhost:8000/o/token/ // make a new token no matter it already has an access token with this username.