Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 3.0: Running backgound infinite loop in app ready()
I'm trying to find a way to constantly poll a server every x seconds from the ready() function of Django, basically something which looks like this: from django.apps import AppConfig class ApiConfig(AppConfig): name = 'api' def ready(self): from django.conf import settings from api import utils import asyncio async def start(): while True: utils.refresh_servers_list() await asyncio.sleep(settings.WAIT_SECONDS_SERVER_POLL) async def _poll(): task = asyncio.Task(start()) loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) try: loop.run_until_complete(_poll()) except asyncio.CancelledError as e: print(e) I just want my utils.refresh_servers_list() to be executed when Django starts/is ready and re-execute that same method (which populates my DB) every settings.WAIT_SECONDS_SERVER_POLL seconds indefinitely. Thanks! -
Render Django permission in tabular form
Sorry for this questions. I didn't know either this questions make sense or not. I'm new to django and I wan't to build web app using django. Everything's working as I aspect. Default django admin panel is enough good for development purpose but I want to develop custom user admin panel. Here I want to render all the permission in tabular form as below. I tried django-tabular permission but I didn't know how to integrate with custom user admin. Any suggestion would be appreciated. Sorry for my bad English. -
Why FieldError is showing in Django?
I am creating a search form using django which will render result according to search value. All fields are working fine except one field. HTML Code <form action="{% url 'search' %}"> <label">State</label> <select name="state"> <option selected="true" disabled="disabled">State (All)</option> {% for k,v in state_choices.items %} <option value="{{k}}">{{v}}</option> {% endfor %} </select> <label>Bedrooms</label> <select name="bedrooms"> <option selected="true" disabled="disabled">Bedrooms (Any)</option> {% for k,v in bedroom_choices.items %} <option value="{{k}}">{{v}}</option> {% endfor %} </select> <button type="submit">Submit form</button> </form> Django code def search(request): result = Listing.objects.order_by('-list_date') # state if 'state' in request.GET: state = request.GET['state'] if state: result = result.filter(state = state) # bedrooms if 'bedrooms' in request.GET: bedrooms = request.GET['bedrooms'] if bedrooms: result = result.filter(bedrooms_lte = bedrooms) context = { 'state_choices': state_choices, 'bedroom_choices': bedroom_choices, 'listings': result } return render(request, 'listings/search.html', context) The bedrooms is creating the problem. Below is the error am getting : Environment: Request Method: GET Request URL: http://localhost:8000/listings/search?keywords=&city=&bedrooms=2&price=1000000 Django Version: 3.0.1 Python Version: 3.6.9 Installed Applications: ['pages.apps.PagesConfig', 'listings.apps.ListingsConfig', 'realtors.apps.RealtorsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize'] Installed 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'] Traceback (most recent call last): File "/home/barefaced/Desktop/ubuntu/mini projects/django/practice/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/barefaced/Desktop/ubuntu/mini projects/django/practice/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File … -
Getting an error as 'unicode' object has no attribute 'objects'?
I am having form consisting of a field and in that field I am giving the furniture id 1 or 2 0r 3 and I having a users and furniture models as shown below class furniture(models.Model): id=models.IntegerField(primary_key=True) phrase=models.CharField(max_length=60,default='0000000') def __unicode__(self): return self.phrase class users(models.Model): email=models.CharField(max_length=50,default='0000000') password=models.CharField(max_length=50,default='0000000') room = models.ForeignKey(rooms,on_delete=models.CASCADE) goal = models.ManyToManyField(goals) style = models.ManyToManyField(designs) furniture = models.ForeignKey(furniture,on_delete=models.CASCADE) My views.py is: def user_register(request): if request.method == 'POST': username=request.POST["username"] email = request.POST['email'] password = request.POST['password'] room = request.POST['room'] g=goal=request.POST['goal'] g = g.split(',') s=style=request.POST['style'] s=s.split(',') furniture=request.POST['furniture'] user = users(password=password,email=email) user.room=rooms.objects.get(pk=room) goal = goals.objects.filter(pk__in=g) style = designs.objects.filter(pk__in=s) user.furniture = furniture.objects.get(pk=furniture) user.save() user.goal.add(*goal) user.style.add(*style) return render(request,'home.html') home.html is: <form action="{% url 'car:user_register' %}" method="POST" > {% csrf_token %} <div class="form-group"> <label for="username">Username</label> <input type="text" name="username" class="form-control" required> </div> <div class="form-group"> <input type="text" name="room" id="name" value=" "> </div> <div class="form-group" > <input type="text" name="goal" id="goal" value=" "> </div> <div class="form-group" > <input type="text" name="style" id="style" value=" "> </div> <div class="form-group" > <div class="rangeslider"> <input type="number" name="furniture" id="furniture" value="1"> </div> <div class="form-group"> <label for="email">Email</label> <input type="text" name="email" class="form-control" required> </div> <div class="form-group"> <label for="password2">Password</label> <input type="password" name="password" class="form-control" required> </div> <input type="submit" value="Register" style="background-color:#000080;" class="btn btn-secondary btn-block"> </form> My error page is: I had tried like … -
How to update fields of custom user model using Django serializer
I am trying to update the various fields of a user model when the user wants to update it which was created earlier. I am having a custom user model and I am using django rest framework for the update api. views.py class UserUpdate(generics.UpdateAPIView): """ Update user. """ parser_class = (FileUploadParser,) permission_classes = (AllowAny,) queryset = User.objects.all() serializer_class = UserUpdateSerializer def update(self, request, *args, **kwargs): instance = self.get_object() instance.user_id = request.data.get("user_id") instance.save() serializer = self.get_serializer(instance, data=request.data) serializer.is_valid(raise_exception=True) self.perform_update(serializer) return Response(serializer.data) models.py class User(models.Model): USER_CHOICES = ( (1, u'ADMIN'), (2, u'SALES'), (3, u'KITCHEN'), (4, u'EMPLOYEE'), ) image = models.ImageField(upload_to='employees/', null = True, blank = True) name = models.CharField(max_length=50) user_id = models.CharField(max_length=30, primary_key = True, blank = False) email = models.CharField(max_length=50) password = models.CharField(max_length=100) is_active = models.BooleanField(default=True) user_group = models.PositiveSmallIntegerField(default=4, choices=USER_CHOICES) firebase_token = models.CharField(max_length=150, default=None, null = True) shop = models.ForeignKey(Shop, on_delete=models.SET_DEFAULT, default=None) phone = PhoneField(blank=False, default=0) serializers.py class UserUpdateSerializer(serializers.ModelSerializer): shop = serializers.CharField() class Meta: model = User fields = ('image', 'url', 'phone', 'name', 'user_id','email', 'password', 'is_active', 'user_group', 'shop') def update(self, instance, validated_data): shop = validated_data.pop('shop') user_id = validated_data.pop("user_id") print(user_id) shopId = Shop.objects.filter(name=shop).values('shop_id').first() if shopId is not None: shop_id = shopId['shop_id'] try: if user_id is not None: instance.name = validated_data.get('name', instance.name) instance.image … -
Created website using Django, but the images are not showing when deployed to heroku but shows in localhost
The images are coming from the table in where the admin have uploaded the images. enter image description here this is my settings to store static files and media STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'portfolio/static/') ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,'static') MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' The models i've created from django.db import models # Create your models here. class ProfileImage(models.Model): image = models.ImageField(upload_to='images/') class Job(models.Model): image = models.ImageField(upload_to='images/') summary = models.CharField(max_length= 200) class Project(models.Model): image = models.ImageField(upload_to='images/') summary = models.TextField() title = models.CharField(max_length=30) link = models.URLField(max_length=200, null=True, blank=True) def __str__(self): return(self.title) class Social(models.Model): image = models.ImageField(upload_to='images/') title = models.CharField(max_length=30) link = models.URLField(max_length=200, null=True, blank=True) def __str__(self): return(self.title) class Skills(models.Model): title = models.CharField(max_length=20) def __str__(self): return(self.title) In templates i've : <img src="{{profile_pic.image.url}}" height="600px" width="500x" class="img-fluid img-thumbnail" alt="Responsive image"> <br> In views i have: from django.shortcuts import render from .models import Job, Skills, Project, Social, ProfileImage # Create your views here. def home(request): jobs = Job.objects.all() skills = Skills.objects.all() projects = Project.objects.all() socials = Social.objects.all() profile_pic = ProfileImage.objects.all().first() context = {'jobs':jobs, 'skills':skills, 'projects':projects, 'socials':socials, 'profile_pic':profile_pic} return render(request, 'jobs/home.html', context) When i deploy to heroku it shows: -
Django functional view to create file for download and URL mapping
I created a view to handle creation of a png when a download is wanted by the user. The view simply calls an API, saves the png data to a bytesIO buffer, and returns a FileResponse object. def download_plot_png(request): csv_path = os.path.join(os.getcwd(), 'analyze', 'static', 'analyze', 'data', 'player_box_scores.csv') df = Api.get_existing_data_frame(csv_path=csv_path, logger=logging.getLogger(__name__)) plot_path, _, _ = Api.create_scatter_plot_with_trend_line(x_key='x_key', y_key='y_key', df=df, save_path='png_buffer') converted_png = plot_path return FileResponse(converted_png, filename='test.png') I attempt to call the view in my template by doing the following: <a href="{% url 'download_plot_png'}"style="padding: 5px;"> <input type="submit" value="Download Plot" class="downloader"> </a> I think that the following would work if my URL mapping was correct but I keep getting a 404 error relating to the urlpatterns list in urls.py. What do I set the location of 'download_plot_png' since I do not actually want any redirect to happen? I just want the view to run to create and handle the FileResponse, and then return to my old view as normal. This did not work, the error given was Reverse for 'download_plot_png' not found. 'download_plot_png' is not a valid view function or pattern name.: urlpatterns = [ path('', views.index, name='index'), path('plot/', views.plot, name='plot'), path('download_plot_png/', views.download_plot_png, name='download_plot_png') ] This did not work either, urlpatterns = [ … -
How to query across multiple models in single Django view?
I currently have the following models in my Django code. from django.conf import settings import math from django.contrib.auth import get_user_model from django.db import models from django.urls import reverse # Create your models here. import statistics from django.utils import timezone from decimal import Decimal #import for mail from django.core.mail import EmailMessage, send_mail from django.db.models import Q, QuerySet, F, FloatField, ExpressionWrapper, Manager from django.db.models.functions import Cast from django.db.models.aggregates import Avg import datetime from django.utils import timezone class Card(models.Model): card_name = models.CharField(max_length=255) geography_choices = [('Africa', 'Africa'), ('Asia', 'Asia'), ('Australia', 'Australia'), ('Europe', 'Europe'), ('North America', 'North America'), ('South America', 'South America')] geography = models.CharField(max_length=255, choices=geography_choices, default='North America') type_choices = [('Creature', 'Creature'), ('Spell', 'Spell'), ('New Type', 'New Type'),('Undecided', 'Undecided')] card_type = models.CharField(max_length=255, choices=type_choices, default='Creature') class Article(models.Model): title = models.CharField(max_length=255) body = models.TextField() author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) entry_date_time = models.DateTimeField(default=timezone.now, null=True) class Meta: ordering = ['-entry_date_time'] score_choices = [(-5,'-5'), (-4, '-4'), (-3,'-3'), (-2, '-2'), (-1,'-1'), (0,'0'), (1,'1'), (2,'2'), (3,'3'), (4,'4'), (5,'5')] score = models.FloatField(choices=score_choices, default=0) read_through_choices = [(-1, 'Competitive'), (0, 'No Effect'), (1, 'Industry-Wide')] read_through = models.IntegerField(choices=read_through_choices, default=0) cardvar = models.ForeignKey(Card, on_delete=models.CASCADE, null=True) I am trying to run a search function that searches my articles and a) returns articles whose "cardvar__card_name" matches our query … -
Confusion when trying python3 manage.py migrate error to migrate my database to run my server properly
I have been trying to migrate by typing the command python3 manage.py migrate to work on an issue I have been assigned on github and I keep receiving this error: Operations to perform: Apply all migrations: admin, auth, contenttypes, questions, sessions Running migrations: Applying questions.0002_question_user...Traceback (most recent call last): File "/home/twayne/.local/lib/python3.6/site-packages/django/db/models/fields/init.py", line 1768, in get_prep_value return int(value) TypeError: int() argument must be a string, a bytes-like object or a number, not 'User' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in execute_from_command_line(sys.argv) File "/home/twayne/.local/lib/python3.6/site-packages/django/core/management/init.py", line 401, in execute_from_command_line utility.execute() File "/home/twayne/.local/lib/python3.6/site-packages/django/core/management/init.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/twayne/.local/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/home/twayne/.local/lib/python3.6/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/home/twayne/.local/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/home/twayne/.local/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 233, in handle fake_initial=fake_initial, File "/home/twayne/.local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/twayne/.local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/twayne/.local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "/home/twayne/.local/lib/python3.6/site-packages/django/db/migrations/migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/home/twayne/.local/lib/python3.6/site-packages/django/db/migrations/operations/fields.py", line 112, in database_forwards field, File "/home/twayne/.local/lib/python3.6/site-packages/django/db/backends/sqlite3/schema.py", line 328, in … -
Get request.user from context in custom template tag in django >= 2.1
I had working code for a custom template tag in Django 2.0: @register.simple_tag(takes_context=True) def my_tag(context): print(context.request.user) Upgrading to 2.1, I am now getting this error: AttributeError: 'Context' object has no attribute 'request' How do I get the user from the context in Django >= 2.1? -
Django demo site
I want to create a demo instance for my new SaaS using Django. So I want to make the demo available publicly, and set a cron job, to reset the database every 2 hours or so. The concept is this: give out the full access to the application, and then put an demo.sqlite3 db file in the root folder. Then, I will set a cron job to replace the current db with the demo one every 2 or 3 hours. Any idea how to do it? Also, my demo app runs on Postgresql. Is there a way to use the sqlite db file to auto migrate its data to the postgresql? Thank's! -
Django error "Reverse for 'app_list' with keyword arguments '{'app_label': 'Account'}' not found."
I've had this issue for a while now, and I'm still a beginner, so please understand. I am trying to have the admin page in Django send mass emails to registered users, and practically all the source code is very similar to the answer in this link here, but the error I am getting is: Reverse for 'app_list' with keyword arguments '{'app_label': 'Account'}' not found. I don't know where to put app_label or whether its coming from the URL, but I am very confused. I am using a custom User model called Account here: class Account(AbstractBaseUser): email = models.EmailField(verbose_name = 'email', max_length = 250, unique = True) username = models.CharField(max_length = 250, unique = True) first_name = models.CharField(max_length = 30) last_name = models.CharField(max_length = 30) date_joined = models.DateTimeField(verbose_name = 'date joined', auto_now_add = True) last_login = models.DateTimeField(verbose_name = 'last login', auto_now_add = True) is_active = models.BooleanField(default = True) is_admin = models.BooleanField(default = False) is_staff = models.BooleanField(default = False) is_superuser = models.BooleanField(default = False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] #class Meta: #app_label = 'Account' objects = MyAccountManager() #class Meta: #abstract = True #app_label = 'Account' #abstract = True def __str__(self): return self.first_name + " " + self.last_name def has_perm(self, perm, … -
Django - save AxesSubplot via seaborn to django models.ImageField
I'm trying to save graph from seaborn module as ImageField to django model. models.py class HeatmapFiles(models.Model): username = models.ForeignKey( 'CustomUser', verbose_name='Username', on_delete=models.CASCADE, blank=False ) heatmap = models.ImageField( verbose_name='Heatmap', blank=False ) example_file.py import io import seaborn as sns import matplotlib.pyplot as plt from django.core.files.images import ImageFile sns.set() flights_long = sns.load_dataset("flights") flights = flights_long.pivot("month", "year", "passengers") f, ax = plt.subplots(figsize=(9, 6)) new = sns.heatmap(flights, annot=True, fmt="d", linewidths=.5, ax=ax) figure = io.BytesIO() new.get_figure.savefig(figure, format='png') image_file = ImageFile(figure.getvalue()) and image_file objects returns None here: <ImageFile: None> I can save it, but that doesn't make sense. How to save "new" object as django model? -
Sending post request through Postman works but not when using http
I am working on uploading an image to my server (right now it is just localhost). Below is the part of the code in my views.py that is causing the problem. valid_extensions = ['jpg', 'jpeg', 'png', 'gif'] images = request.data.getlist('images[]') directory = os.path.join(os.getcwd(), 'static', 'images', 'products') for image in images: extension = os.path.splitext(image.name)[1][1:].lower() file_name = "".join(choice(ascii_lowercase) for i in range(16)) + "." + extension if extension in valid_extensions: file_path = os.path.join(directory, file_name) with open(file_path, 'wb+') as destination: for chunk in image.chunks(): destination.write(chunk) ProductImage.objects.create(file_name=file_name, original_name=image.name, file_length=image.size, product=product, file_path=file_path.replace(os.getcwd(), '').replace('\\', '/')) else: data = {'full_messages': ['Image file type is not supported.']} return Response(data, status=status.HTTP_422_UNPROCESSABLE_ENTITY) data = {'full_messages': ['Product created successfully.']} return Response(data, status=status.HTTP_201_CREATED) For some reason when I send my post request through Postman it successfully uploads the file, but when I send the same request through HTTP (Angular 8) I get errors in the console. It says AttributeError: 'NoneType' object has no attribute 'decode' and if I change the Below is the request when sending from http Below is the Postman request -
What to put as "sender" for post_save receiver?
My models.py looks like this right now: class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) @receiver(post_save, sender=Employee) def set_perms(sender, instance=None, created=False, **kwargs): if created: restaurant = instance.restaurant assign_perm("change_user", instance, instance) assign_perm("view_restaurant", instance, restaurant) I'm getting an error NameError: name 'Employee' is not defined which I'm not too surprised about. However, what should I put as the sender instead? Note: I know it's best practice for signals to be in another file completely but I just want to get things working for now. -
Reverse lookup on template page not working
I have a contact and an event model where the event model has a foreign key to contact. The first half of my html obviously works, but for some reason when I display the list of other events that the contact has done, I can't get the list to show up. Is it because I'm calling {{event.whatever}} twice on the same page but in two differrent context? views.py class EventDetail(DetailView): template_name = 'crm/eventdetail.html' model = Event models.py class Contact(models.Model): firstname = models.CharField(max_length=20, null=True, blank=True) lastname = models.CharField(max_length=20, null=True, blank=True) email = models.CharField(max_length=40, null=True, blank=True) phone = models.CharField(max_length=15, null=True, blank=True) title = models.CharField(max_length=20, null=True, blank=True) notes = models.CharField(max_length=400, null=True, blank=True) company = models.ForeignKey(Company, on_delete=models.CASCADE, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ["lastname"] def __str__(self): return self.firstname class Event(models.Model): event_type = models.CharField(max_length=20, choices = event_types) contact = models.ForeignKey(Contact, on_delete=models.CASCADE) created_by = models.ForeignKey(User, on_delete=models.CASCADE) should_follow_up = models.BooleanField(default=False) date = models.DateField() notes = models.CharField(max_length=400) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def get_absolute_url(self): return reverse('events_detail', kwargs={'pk': self.pk}) eventdetail.html <div id="container"> <h1> Event: {{event.event_type}} </h1> <ul> <li>Event Contact: {{event.contact}}</li> <li>Created By: {{event.created_by}}</li> <li>Date: {{event.date}}</li> <li>Note: {{event.notes}}</li> </ul> <h1>Events for {{event.contact}}</h1> <table class="table"> <tr> <th scope="col">Event Type</th> <th scope="col">Date</th> <th scope="col">3</th> </tr> … -
Django query categories, exclude those without posts
I have these two models, post and categories. class Category(models.Model): """ Categories """ name = models.CharField(max_length = 80, help_text="Enter a descriptive and unique category name.") slug = models.SlugField(max_length = 250, help_text="The slug is used to link category pages.") class Post(models.Model): """ Blog posts """ author = models.ForeignKey(User, related_name='blog_posts', on_delete = models.CASCADE) category = models.ForeignKey(Category, related_name = 'blog_posts', on_delete = models.CASCADE) title = models.CharField(max_length=250) body = models.TextField(help_text = "Type your blog post using plain text or mark-down format.") I am trying to query all the categories that have posts, excluding categories which don't have yet posts. The SQL equivalent of: SELECT * FROM category WHERE id IN (SELECT DISTINCT(category_id) FROM post) Many thanks! -
Assign values to EMAIL_HOST_USER and EMAIL_HOST_PASSWORD dynamically
I have made a model named ZohoMail which is as follows: class ZohoMail(models.Model): email = models.EmailField(null=True) password = models.CharField(max_length=255,null=True) def __str__(self): return self.email I know that to send email i have to make some configuration in settings.py file #settings.py EMAIL_PORT = 465 EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_SSL = True EMAIL_HOST = 'smtp.zoho.in' EMAIL_HOST_USER = 'myemail@example.com' EMAIL_HOST_PASSWORD = 'mypassword' But what if i want to pass values dynamically like this in settings.py file #settings.py from myapp.models import ZohoMail email_obj = ZohoMail.objects.get(email='myemail@example.com') EMAIL_PORT = 465 EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_SSL = True EMAIL_HOST = 'smtp.zoho.in' EMAIL_HOST_USER = email_obj.email EMAIL_HOST_PASSWORD = email_obj.password My problem is i want to know how can i dynamically set email and password as i want to use default PasswordResetView with email and password of ZohoMail object. When i do this i get the following error File "/home/ubuntu/frameskraftvenv/lib/python3.6/site-packages/django/apps/registry.py", line 125, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") P.S: Password is stored in plain text in ZohoMail model.No encryption is used right now -
Error: too many values to unpack (expected 2) when raise error with serializers.ValidationError
Merry Christmas. I'm trying to validate empty fields in an endpoint by overwriting to_internal_value function and displaying an error message with ValidationError, very similar as the following answer: serializer.py def to_internal_value(self, data): missing = [] for k in ['comments']: try: if data[k] == '': missing.append(k) except Exception as e: missing.append(k) if len(missing): raise serializers.ValidationError("The following fields are required: %s" % ','.join(missing)) return data The problem is that I get: Error: too many values to unpack (expected 2) when raise serializers.ValidationError instruction is executed and data is comming with comments field empty (''). Even with a simple string: raise serializers.ValidationError("The following fields are required: comments") I receive the same error. In the python console, raise throw the error: >>> from rest_framework.serializers import ValidationError >>> from rest_framework import serializers >>> data={'comments': [''], 'user': ['']} >>> missing=[] >>> missing.append('comments') >>> raise serializers.ValidationError("The following fields are required: %s" % ','.join(missing)) Traceback (most recent call last): File "<stdin>", line 1, in <module> rest_framework.exceptions.ValidationError: [ErrorDetail(string='The following fields are required: comments', code='invalid')] Instead of serializers.ValidationError() I had to use ValueError() and It words good, but I guess that it's not the suggested way. I'm using djangorestframework==3.10.3 Thank in advance, any help will be appreciated -
Filtering using model queries in django
I am trying to filter the data in a tabular form using AJAX and JQUERY in django only the issue is I trying to send "ram_list" ie{ram size} to the server using GET method in ajax and jquery. The template just cannot able to render the data once the checkbox are clicked template "products.html" {% extends 'homepage.html' %} <!-- Attach all those files that such Jquery UI after adding the features of filtering; The basic one should be considered first [Similar to flipkart] The user selects all the features regarding they want to filter and then we can click a submit button to make an AJAX call. --> {% block content %} <div class="row"> <!-- Header row under Navbar --> <div class="col-12 bg-primary py-3"> <h1 class="pageTitle text-center">Choose A Video Card</h1> </div> <!-- SideBar --> <div class="col-2 bg-info"> <form action="." method="POST"> {% csrf_token %} <!-- Min and max value of Boost Clock --> <h3>Boost Clock</h3> <input type="number" class="form-control" id="blockContentMin" placeholder="min" name="Boost_Clock_min" value="0"> <input type="number" class="form-control" id="blockContentMax" placeholder="max" name="Boost_Clock_max" value="2000"> <p id="price_show" style="padding:10px;">0 - 2000 MHz</p> <div id="boost_clock_range"></div> <!-- Min and max value of Core Clock --> <h3>Core Clock</h3> <input type="number" value="0" class="form-control" id="viewCountMin" placeholder="min" name="Core_Clock_min"> <input type="number" value="2000" class="form-control" id="viewCountMax" placeholder="max" … -
persian slug caused ERR_CONNECTION_RESET
I faced with below problem about a week ago, and I could not solve it till now. My web app url works fine with english slug, but it displays ERR_CONNECTION_RESET for persian slugs. I changed english slug manually to contain just one persian character and it displays 404 not found, but when I put two persian characters it displays ERR_CONNECTION_RESET error again. I can't see server log as I'm using host shared for my python-django project. slug field: slug = models.SlugField(max_length=255, allow_unicode=True) url: url(r'^doctor-profile/(?P<slug>\S+)/$', FrontDoctorDetailView, name='frontDoctorDetail'), and get slug in views function: doctorObj = get_object_or_404(Doctor, slug=urllib.parse.unquote(slug)) I checked request header from network tab in chrome browser and it displays: Request URL: http://vaghtbede.com/doctors/%D9%88%D8%A7/ status: failed Can you display me some way to find out what is the problem? -
Usiing django's site's framework without subdomains
I am trying to set up a simple multi-tenant django app, but I don't have the resources to dynamically provision subdomains. I'd like to use Django's sites framework, but it appears to require sites to be differentiated by subdomains. Is there a way to change it so this framework can use some other differentiating factor such as a field on the user's profile? As an possible example, how could I get the "Sites" framework to use the current_site profile field; class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) sites = models.ManyToManyField(Site) # Sites the user has access to # use `current_site` for the sites framework instead of subdomain current_site = models.ForeignKey(Site, on_delete=models.SET_NULL) # Site the user is currently accessing -
Favicon.ico renders nothing in web/admin sites when using AWS S3
I am working on Django project and serving static files from AWS S3 as well as media files. Everything, like CSS, JS, and etc are loading perfectly, but /favicon.ico is the only thing that is not loading. I struggled with how to load /favicon.ico, which the log kept said favicon.ico is not found, but the problem was setting whether the Debug option to 1 or 0. Now I have set my Debug option to 0, and the log seems like it is GETTING /favicon.ico, but it renders NOTHING AT ALL. Here is my Log. [31/Dec/2019 21:11:55] "GET /favicon.ico HTTP/1.1" So it is Getting Favicon.ico, but it is not doing anything. All of my fa fa-icons are Squares and admin sites look awkward without favicon. I am even thinking of just serving static files from instance instead of from S3. Can someone please help this? -
Shutting Off CELERY.BACKEND_CLEANUP
I'm using Django with Celery. I need to turn off the celery.backend_cleanup that runs every day at 4 UTC. I've been looking at the documentation and can't find how to disable it. Below is my last try: celery.py from __future__ import absolute_import, unicode_literals from django.conf import settings from celery import Celery import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") app = Celery('app') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() app.conf.beat_schedule = { 'backend_cleanup': { 'task': 'celery.backend_cleanup', 'schedule': None, 'result_expires': None }, } I don't want this to run. How can I stop it? -
Can I pass an F() expression value into my own function and still call update in Django?
I need to convert a bunch of fields on a certain Django (1.9) model from string to decimals. Instead of doing this: for x in Foo.objects.all(): x.biz = str_to_decimal(x.bar) x.bang = str_to_decimal(x.fizz) ... x.save() I want to be able to do something like this: fields = { 'biz': str_to_decimal(models.F('bar')), 'bang': str_to_decimal(models.F('fizz')), } Foo.objects.update(**fields) The bulk update functionality isn't available to me either since it's only in a later version of Django. Any thoughts? Thank you.