Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django save override never stops saving gtts generated mp3 file to directory
When I run the save override method, the mp3 file is saved to the specified folder, only it keeps saving itself to that dir over and over again until I eventually restart the server. The file is saved to the right place and it can be played with VLC, so at least there's that... It would appear that the problem persists with both of the save models I've included. I'm guessing that the super().save() is never run, but I can't really tell what's going on, simply put. What am I doing wrong, why is the multi-saving happening and how should I fix it? from django.db import models from PIL import Image from gtts import gTTS from io import BytesIO import tempfile from django.core.files import File class VoiceModel(models.Model): name = models.CharField(max_length=50) ... audiofile = models.FileField(upload_to='sounds/loads', max_length=100, blank=True, null=True) # editable=False) def __str__(self): return self.name def save(self, *args, **kwargs): new_string = 'repeat after me: ' + str(self.name) file_name = '{}.mp3'.format(str(self.name).lower().replace(' ', '_')) make_sound = gTTS(text=new_string, lang='en') mp3_fp = BytesIO() make_sound.write_to_fp(mp3_fp) self.audiofile.save(file_name, mp3_fp) super(VoiceModel, self).save(*args, **kwargs) # def save(self, *args, **kwargs): # new_string = 'repeat after me: ' + str(self.name) # audiofile = gTTS(text=new_string, lang='en') # with tempfile.TemporaryFile(mode='wb+') as f: # # with … -
How do I integrate authorize.net on django app?
I can see that there’s packages to use but I’ve also heard that there’s a lot more to do that packages will be useless. Any guidance would be appreciated. -
Django Forms redirect on processing of a step in Wizard
I'm trying to check a step once the form has been processed. It has 4 radio buttons on it with various values, and when any option but the 4th is pressed, I want it to redirect straight to a static page outside the wizard. Currently, I'm struggling to see a method that allows me to do this outside of done() (Too late in the flow) and render() (is called before the form on the page is processed). Has anyone else got an implementation or the correct method in the Django forms wizard to allow for a redirect? Docs i'm looking at https://docs.djangoproject.com/en/1.7/ref/contrib/formtools/form-wizard/ -
validation form fields in updateview django
i have my updateView which i post update data with update_key and object_type and update_value class PackageTranslationsUpdateView(PackageAccessMixin, UpdateView): # TODO : enhance logic + add validation model = Package fields = ('translations',) template_name = "base_form.html" # form_class = PackageTranslationForm # second_form_class = PackageSeasonsEpisodesTranslationForm def post(self, request, *args, **kwargs): super().post(request, *args, **kwargs) update_key = request.POST.get('update_key') object_type = request.POST.get('object_type') update_value = request.POST.get('update_value') language_code = request.POST.get('language_code') child_package = None # get instance to update instance = self.object season_number = request.POST.get('season_number') season = self.object.seasons.filter(number=season_number).first() if season_number != 'false' else None if object_type == 'season': instance = season child_package = instance.package elif object_type == 'episode': instance = season.episodes.filter(number=request.POST.get('episode_number')).first() child_package = instance.season.package # apply changes instance.translations.setdefault(language_code, {})[update_key] = update_value if child_package: child_package.diff_fields.setdefault('%s_tr_%s' % (object_type, instance.pk), {}).setdefault(language_code, {}).update({update_key: "has_changed"}) child_package.save() else: instance.diff_fields.setdefault(language_code, {}).update({update_key: "has_changed"}) instance.save() return JsonResponseOK() and my form has two fields like this : class PackageTranslationForm(forms.Form): """ Custom form to manage translations in json fields, with initial data from Title metadatas. Only works with instance=<Package object> """ localized_title = forms.CharField(label=_("Title"), max_length=255) localized_overview = forms.CharField(label=_("Overview"), widget=forms.Textarea, max_length=1000) class Meta: model = main_models.Package fields = ('localized_title', 'localized_overview') def __init__(self, language, **kwargs): self.language = language super().__init__(**kwargs) i want to do validation to my update_value in my view after … -
Models.py for recommendation system
My webapp displays a list of movies taken from JSON file in bootstrap card format.Each individual card exists for each movie. I need to take user ratings(1-5) for n movies from the user, default value being 0 if the user doesn't rate it. I want to save it in a row-column format in my database where each row represents a user and columns depicts the movies and the table represents ratings by each user for each movie. my views.py looks like this : from django.shortcuts import render import requests import json from .models import * from . import forms def list(request): movies_data=open('movies.json').read() movies = json.loads(movies_data) return render(request, 'home.html', {'movies' : movies}) my home.html looks like this: {% extends 'base.html' %} {% block content %} <div class="jumbotron jumbotron-fluid"> <div class="container"> <center> <h1 class="display-3">Welcome to Movie Finder!</h1> <p class="lead"> Your one-stop and best recommender of movies.</p></center> <div class ="container"> <div class="row"> {% for movie in movies %} <div class="col-sm-3 col-lg-3"> <div class="card h-8"> <div class="card-group"> <div class="card text-center" style="width:20rem;"> <img class="card-img-top" src="{{movie.img_url}}" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">{{movie.title}}</h5> <h5 class="card-title">Rating : {{movie.users_rating}}</h5> <h5 class="card-title">Year : {{movie.year}}</h5> <p class="card-text"><h5>Description:</h5> {{movie.description|truncatewords:10}} </p> <br></br <a href="{{movie.imdb_url}}" class="btn btn-dark">Explore</a> </div> </div> </div> </div> </div> {% … -
Django: How to get an object from many to many field?
I am creating digital products for my eCommerce application. I have created a model Product_activation to activate particular product whenever the user is subscribed to the product I have done the following: class Profile(models.Model): date = models.DateTimeField(auto_now_add=True) full_Name = models.CharField(max_length=32,blank=True) name = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) e_mail = models.EmailField(max_length=70,blank=True) subscribed_products = models.ManyToManyField(Product,related_name='products_subscribed',blank=True) class Product(models.Model): title = models.CharField(max_length=32) price = models.DecimalField(default=10000.00,max_digits=10,decimal_places=2) class Product_activation(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True) product = models.ForeignKey(Product,on_delete=models.CASCADE,related_name='product_activate') activate = models.BooleanField(default=False) deactivate = models.BooleanField(default=False) I have created this below signal: @receiver(pre_save, sender=Profile) def product_activation(sender,instance,*args,**kwargs): if instance.subscribed_products: Product_activation.objects.update_or_create(User=instance.Name,product=instance.subscribed_products,activate=False,deactivate=True) But having problem in product=instance.subscribed_products line of code. This is giving me the following error message: TypeError: int() argument must be a string, a bytes-like object or a number, not 'ManyRelatedManager' Can anyone tell me what I am doing wrong in my code? Thank you -
PUT method not allowed
Im trying to make editable datatables to work with django rest, im trying to use PUT method for table field changes but im getting Method Not Allowed (PUT): /api/zaposleni/2/ Method Not Allowed: /api/zaposleni/2/ I have checked simmilar questions on stack overflow. Im returning key in url and in request body, also put method is decorated which should not trigger the error im getting. Adding breakpoints seems to show that code execution does not even reach my view. View: class ZaposleniDetail(viewsets.ViewSet): @action(detail=True, methods=['put']) def put(self, request, pk): try: zaposleni = Zaposleni.objects.get(pk=pk) except Zaposleni.DoesNotExist: return HttpResponse(status=404) if request.method == 'PUT': # this is when you make changes with datatables editor. I think there was a reason I used PUT instead of POST # but I cant remember why that was right now. # change pk to an int pk = int(pk) # parse request querydict into dict # I could not find a better way to do this. data = parser.parse(request.body) # extract out the nested dict needed for drf post # datatables always send it nested in 'data' but you can change that if you want to parsed_data = data['data'][pk] for key, val in parsed_data.items(): # this is the ugliest part … -
ValidationError or TypeError, ValueError - Exceptions
I am quite a newbie understanding of how to catch exceptions in python. I have a question regarding those two types of ways of catching exceptions. I only found useful information about ValidationError regarding here But I did not quite understand if it can be used besides django or what are the error messages that I can expect about it. I saw this code sample regarding the validation of types. except (TypeError, ValueError) as error: LOGGER.error('Error e.g.', exc_info=True) except ValidationError: LOGGER.error('Error e.g', exc_info=True) So for TypeError and ValueError for me, it is clear: exception ValueError Raised when an operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError. exception TypeError Raised when an operation or function is applied to an object of inappropriate type. The associated value is a string giving details about the type mismatch. In conclusion, I am trying to understanding what would be the advantage of the second code with ValidationError, but it could be tricky as I did not find good documentation about. If someone could share knowledge about ValidationError, I would highly appreciate, Thank you community! -
Runtime error during django recursive template rendering
I want to implement django recursive template rendering for getting users and their subordinates. However, I've got a ErrorRuntimeError at /admin/users/3 maximum recursion depth exceeded in instancecheck. I'm using django 1.9. The code is given below The input is like that: [{name: 'user1@mail.com', id: 1, next: True}, {name: 'user2@mail.com', id: 2, next: True}, {name: 'user3@mail.com', id: 3, next: False}] users_hierarchy.html <ul> {% for user in users %} <li>{{ user.name }}</li> {% if user.next %} <ul> {% include 'users/user_hierarchy.html' with data=user %} </ul> {% endif %} {% endfor %} I except a html such as: <ul> <li>user1@mail.com <ul> <li>user2@mail.com <ul> <li>user3@mail.com</li> </ul> </li> </ul> </li> What I am doing wrong? -
choice field value dependent char field in django
I have 2 fields in my model named 'rrb' char field with choices and 'sr' a char field . when i select choice in rrb as 3 i want sr value to be 6 similarly when i chose 5 in rrb i want value of sr to be 4 how can i do that RRB = ( ("1.4", "1.4"), ("3", "3"), ("5", "5"),("10","10"),("15","15"),("20","20")) rrb = models.CharField( max_length=10, choices=RRB, default="10", ) sr = models.CharField(default='15.36', max_length=10) play.html <td>RX RF Bandwidth(MHz): </td> <td> {{form.rrb}}</td> <td>sample Rating:</td> <td>{{form.sr}}</td> <script type="text/javascript"> var e=document.getElementById('id_rrb'); var s = e.options[e.selectedIndex].value; if(s==3) { document.getElementById('id_sr').value=6; } </script> expected result: whe choice 3 in the (rrb)choices list selected (sr)text field should display 6 -
404 Error on /admin page (Django server running remotely on VPS)
I have problem with django app running on remote vps. App is working locally without any problems, but when I try to deploy it on VPS, run command python manage.py runserver 0.0.0.0:8000 and go to url http://xx.xxx.xxx.xxx:8000/admin I got Page not found error: "/home/xxx/yyy/zzz/admin" does not exist and in django logs: Not Found: /admin "GET /admin HTTP/1.1" 404 1771. 404 Not found page just looks like Django debug page, so server is working. Also in my settings.py I have: ALLOWED_HOSTS = ['*'] Thanks for help! -
Overwrite Django Rest Framework header for OPTION requests
When I send a http OPTION request to an endpoint, Django rest Framework responds with the following paylod: { "name": "Get Categorias", "description": "", "renders": [ "application/json", "text/html" ], "parses": [ "application/json", "application/x-www-form-urlencoded", "multipart/form-data" ] } And The Following headers: Date →Fri, 08 Feb 2019 12:25:50 GMT Server →Apache/2.4.29 (Ubuntu) Content-Length →173 Vary →Accept Allow →GET, HEAD, OPTIONS X-Frame-Options →SAMEORIGIN Keep-Alive →timeout=5, max=100 Connection →Keep-Alive Content-Type →application/json I need to overwrite this headers. I don't Know from where this is coming since I don't have an explicit endpoint for OPTIONS request. Anyone can help me to discover where I can configure the correct headers I need? -
Sentry sdk timeout setting
I have a django app and I was using raven to send events to sentry: settings.py RAVEN_CONFIG = { 'dsn': '***', 'timeout': 10, 'transport': 'raven.transport.requests.RequestsHTTPTransport' } Now, as I'm switching to newly released sentry-sdk, how do I set timeout? Can't find it neither in docs nor in sentry-sdk code. import sentry_sdk from sentry_sdk.integrations.django import DjangoIntegration sentry_sdk.init( dsn="***", integrations=[DjangoIntegration()], timeout=10 ) -
django rest auth facebook authentication 400 error
I am using django-rest-auth for authentication via REST. I've configured facebook as in tutorial. On my local machine it works nice but on DO server I always get 400 error for facebook auth(Google auth works nice on server). { "non_field_errors": [ "Incorrect value" ] } I double checked that creadentials for facebook are valid. So the problem is in Facebook app config. Also I added server ip to white list for facebook app. Actually I don't need redirect uri as I get access_token from https://developers.facebook.com/tools/explorer/ -
How to get child model one row data in drf serilaizer
I have 2 models class Ad(ActivatorModel, TimeStampedModel): ........ class AdImage(models.Model): image = models.ImageField(upload_to=get_file_path) is_primary = models.BooleanField(default=False) my serializer is class MyAdsSerializer(serializers.ModelSerializer): class Meta: model = ads.models.Ad how can I get ad primary image in the above serializer -
How to create a custom mixin in django?
I have a decorater which prevents the user to access the urls if the product with id=1 is not activated... I want to create a mixin similar to this.. This is my decorater: from django.core.exceptions import PermissionDenied from ecommerce_integration.models import Product def product_1_activation(function): def wrap(request, *args, **kwargs): products = Product.objects.filter(pk=1, activate=True) if products: return function(request, *args, **kwargs) else: raise PermissionDenied wrap.__doc__ = function.__doc__ wrap.__name__ = function.__name__ return wrap Any idea how to create a custom mixin similar to the above decorater. Actually I want to create mixins for my Class Based View. Can anyone help me out in this? Thank you -
XMLHttpRequest cannot load due to access control checks for AJAX with Django
I'm working on a project using Python(2.7) and Django(1.10) in which I'm using Ajax to make requests from Django templates and Django views.It was working perfectly well but then I have setup SSL on my server for this Django site and after I'm getting this error when making such requests: Here's what I have done so far: Here's my template add_category.html: {% extends 'dashboard_base.html' %} {% load staticfiles %} {% block title %} <title>Category</title> {% endblock %} <!-- main content --> {% block content %} <div class="main-content"> <div class="content-header clearfix"> <h2 class="pull-left">Add New Category</h2> <ol class="breadcrumb pull-right"> <li><a href="/dashboard"><i class="fa fa-dashboard"></i> Home</a></li> <li class="active">Add New Category</li> </ol> </div> <div class="content"> <div class="clearfix"> <div class="content-box"> <div class="content-box-header"> <h4>Add New Category</h4> </div> <div class="content-box-inner"> <form class="custom-form" action="{% url 'category_add' %}" method="post" id="addcategory"> {% csrf_token %} <div class="row"> <div class="form-group col-md-12"> <label>Category Name</label> <input type="text" name="title" id="title" class="form-control" placeholder="Category name"> </div> <div class="form-group col-md-12"> <label>Category Position</label> <input type="number" name="position" id="position" class="form-control" min="1" value="1"> </div> <div class="form-group col-sm-12"> <label>Description</label> <textarea class="form-control" placeholder="Description" name="description" id="description" ></textarea> </div> <div class="form-group col-sm-12"> <label class="checkbox"> <input type="checkbox" name="enable_category" id="enable_category" class="form-control" value="1" checked="checked"> <span>Enable Category</span> </label> </div> </div> <div class="form-group"> <button type="button" id="add_category" class="btn btn-default bg-green"><i class="fa fa-floppy-o"></i>Save</button> </div> … -
pass query param as dictionary with many values in postman
I am using postman to hit my APIs. I have a question regarding sending query params through postman params. In my API i am getting params using services = request.GET.get('services') and then returning response for the services. My Question is if have more than one service like 'A', 'B', 'C', then how can we send these services in params using postman? -
Password Reset - Validation Django
I am using In-built reset password of django. Now the problem is that when i enter a email which does not exists in database, It does not give error that email does not exist # Reset Password path('password-reset/', auth_views.PasswordResetView.as_view( template_name='commons/password_reset/password_reset.html' ), name='password_reset'), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view( template_name='commons/password_reset/password_reset_done.html' ), name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view( template_name='commons/password_reset/password_reset_confirm.html' ), name='password_reset_confirm'), path('password-reset-complete/', auth_views.PasswordResetCompleteView.as_view( template_name='commons/password_reset/password_reset_complete.html' ), name='password_reset_complete'), -
I wanna create a dynamic editable tables on DJANGO
I set up a Wizard and I wanna add tables in every step, finally I will have a lot of dynamic tables. The goal is to facilitate the tasks and accelerate the development. Does django have a module that allows: Dynamically add tables user can edit the tables and modifying the database automatically. Thanks for your help :) -
How to read Django template text area value in view
How to Read Django Template Text area value in views HTML CODE view code message = request.POST['message'] i am expecting to read text area value -
Add, Delete, Update to multiple database by subclassing django.db.models.Model in django
I want to write to add, update delete to multiple database by using django.db.models.Model I am able to add to multiple database by setting up multi-db in settings.py So setting file look like DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': config['DB_NAME'], 'USER': config['DB_USER'], 'PASSWORD': config['DB_PASSWORD'], 'HOST': config['DB_HOST'], 'PORT': config['DB_PORT'], }, 'tableau': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'tableau', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'localhost', 'PORT': 5432, }, } Then I create subclass of django.db.models.Model and model in my app's model.py from django.db.models import Model class MultiDbModel(Model): class Meta: abstract = True def save(self, *args, **kwargs): for dbname in settings.DATABASES: super(MultiDbModel, self).save(using=dbname) class People(MultiDbModel): name = CharField(max_length=255) country = CharField(max_length=255) def save(self, *args, **kwargs): super(App, self).save(args, kwargs) So when I am creating new object its getting saved to both database. People.objects.create(name='alok', location='India') To this approach I want to add capability of update and delete query also like create is working properly. What methods get called when update and delete query runs or how can I add capability of delete and update to multiple database? -
Can't override Django Admin-template
I can't change my Django admin template. I have followed the instructions from Django Documentations. Have already checked stackoverflow(questions) Have already made /templates/admin/my_app/ and changed base_site.html in /templates/admin/my_app/base_site.html settings.py # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_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', ], }, }, ] base_site.html {% extends "admin/base.html" %} {% block title %}{{ title }} | YOUR CUSTOM NAME{% endblock %} {% block branding %} <h1 id="site-name"><a href="{% url 'admin:index' %}">YOUR CUSTOM NAME</a> </h1> {% endblock %} {% block nav-global %}{% endblock %} -
Django i18n translating checkbox in form model
I am trying to make a multilingual site however I have a set of checkboxes that are going to be used for search terms. They are saved in the database but I only want one representation of them and I want to use translation from the .po file at the last moment. Is it possible to do this with the inbuilt forms or do I need to break the checkbox form element out and do it manually with {% trans 'xxx' %} in the template. The current setup I have is forms.py class VenueForm(forms.ModelForm): facilities=forms.ModelMultipleChoiceField(widget=CheckboxSelectMultiple(),queryset=SearchOption.objects.all()) class Meta: model = Venue #ToDo add tags and maybe photos to creation screen? 'tags','photos' fields = ('name','address1'....) It is lazily displayed with the following tag in the template. {{ form.as_p }} Cheers -
How to put logs in functions that have @background decorator?
Actually i am working on a django project that takes input as an doc(with paragraphs) file parse it into an html file while making each paragraph in a card format. the function that beautifies the whole process has a @background(schedule = 0) decorator on it so i cant print anything inside the function. i want to print the parsed html file in log file to check whether the parsing and beautification hapend right or not. is there a way to do so?? @background(schedule=0) def background_html_from_zip_with_beautification(file_type, model_id, mail_ids, path_unzipped_dir_root, folder_name, html_file, model_name): from exam.views import update_feed_for_material paper = get_model_object(model_name, model_id) if paper.subject.name in ENGLISH_LANGUAGE_SUBJECTS: language = 'ENGLISH' elif paper.subject.name in HINDI_LANGUAGE_SUBJECTS: language = 'HINDI' else: language = str(paper.language) try: html_file_path = path_unzipped_dir_root + '/' + folder_name + '/' + html_file current_directory = path_unzipped_dir_root + '/' + folder_name + '/' with open(html_file_path, "r", encoding="ISO-8859-1") as wordfile: modified_html_file_path, message, flag = get_modified_html_file(wordfile, current_directory, model_id, language, model_name) if flag and modified_html_file_path: with open(modified_html_file_path, 'r') as html_file: for line in html_file: #log statement comes here, i wanted to print line variable in a log file. with open(modified_html_file_path, "r") as modified_html_file: s3path, encrypted_s3path, html_s3_url = get_uploaded_files(paper, model_name, folder_name,modified_html_file, False) store_s3_urls_of_paper_in_db(s3path, encrypted_s3path, paper, file_type, html_s3_url) update_feed_for_material(paper, model_name, …