Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Run and validate online compiler against test cases
I made a online compiler (python/Django web app) using hackerearth's API. it's just a normal compiler you can write and run the codes. but I want to add questions and validate the output on that particular question. i.e if output is not according to that particular question then it should give an error. the problem is i don't know the logic(how to validate against test cases). here is the code for API connection that send and receive the JSON dictionary from hackerearth. this is provided by hackerearth itself def runCode(request): if request.is_ajax(): source = request.POST['source'] lang = request.POST['lang'] data = { 'client_secret': '*********bbbb9496f094d690*********', 'async': 0, 'source': source, 'lang': lang, 'time_limit': 5, 'memory_limit': 262144, } if 'input' in request.POST: data['input'] = request.POST['input'] r = requests.post(RUN_URL, data=data) return JsonResponse(r.json(), safe=False) else: return HttpResponseForbidden() the above code just give a blank compiler to write and run anything and does not provide validation. i hope you got my point. and please contact me if you have any idea about this thing, even if you have done this with other language and not only python/Django -
Adding online chat to existing Django website
I have developed a website that is currently working. Is there any Django package which I can add to my website so I can have online chat with website users? -
RecursionError : maximum recursion depth exceeded while calling a Python object
I am getting an error in admin console while trying to open a model . How to fix it Model.py class TbSysEmailconfig(models.Model): id = models.ForeignKey('self', models.DO_NOTHING, db_column='Id', primary_key=True) # Field name made lowercase. emailtemplateid = models.ForeignKey(TbMasEmailtemplate, models.DO_NOTHING, db_column='EmailTemplateId') emailfromname = models.CharField(db_column='EmailFromName', max_length=100, blank=True, null=True) emailfrom = models.CharField(db_column='EmailFrom', max_length=100) credential = models.CharField(db_column='Credential', max_length=100) password = models.CharField(db_column='Password', max_length=100) post = models.IntegerField(db_column='Post', blank=True, null=True) host = models.CharField(db_column='Host', max_length=100) priority = models.CharField(db_column='Priority', max_length=100, blank=True, null=True) maximumday = models.IntegerField(db_column='MaximumDay', blank=True, null=True) maximumminute = models.IntegerField(db_column='MaximumMinute', blank=True, null=True) systemid = models.IntegerField(db_column='SystemId') partfiletemplate = models.CharField(db_column='PartFileTemplate', max_length=500, blank=True, null=True) comment = models.CharField(db_column='Comment', max_length=1000, blank=True, null=True) ismaildefault = models.SmallIntegerField(db_column='IsMailDefault') maildefault = models.CharField(db_column='MailDefault', max_length=4000, blank=True, null=True) createddate = models.DateTimeField(db_column='CreatedDate') createdbyuserid = models.IntegerField(db_column='CreatedByUserId') updateddate = models.DateTimeField(db_column='UpdatedDate') updatedbyuserid = models.IntegerField(db_column='UpdatedByUserId') delflag = models.SmallIntegerField(db_column='DelFlag') class Meta: db_table = 'TB_SYS_EmailConfig' admin.py from django.contrib import admin from .model import TbSysEmailconfig #Modifire admin.site.register(TbSysEmailconfig) When I select some item it show this error -
django sphinx compilation error: index.rst not found and WARNING: Unknown directives
Please I'm facing a weird mistake. Here I have a Django project that runs very well locally, I even generated the documentation and everything is going perfectly well. The problem is that when I import the project in https://readthedocs.org/ the compilation fails, I tried almost everything, but always the same problem I use django == 2.2 python == 3.7.8 My project structure: - Myproject -- docs -- build -- source - conf.py - index.rst - file.rst - another_file.rst make.bat Makefile requirements.txt -- MyprojectDir -- MyappDir My conf.py file inside my source directory look like this: # Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # # import os # import sys # sys.path.insert(0, os.path.abspath('.')) # -- Project information ----------------------------------------------------- import os import sys import django cwd = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.abspath(os.path.join(cwd, '../../'))) os.environ['DJANGO_SETTINGS_MODULE'] = 'vtcvlp.settings' … -
how can I avoid getting duplicates in my header title?
I am trying to format a component where it takes a category followed by a course title. my code currently works, but its adding category + course per course when it should be category + (all courses from that category), how can I fix simple error or retrieve all categories followed by its courses? class Course(models.Model): cuid = models.UUIDField(primary_key=True, default=generate_uuid, editable=False, unique=True) slug = models.SlugField() title = models.CharField(max_length=120) description = models.TextField() price = models.IntegerField() category = models.ForeignKey(Category,on_delete=models.CASCADE) class CourseListView(ListView): template_name = 'site/courses.html' model = Course {% block page-content-1 %} {% for object in object_list %} {{object.category}} <ul> <li>{{object}}</li> </ul> {% endfor %} {% endblock %} TAG 1 Windows security TAG 2 child_1 TAG 1 112 -
How to display Jsignature field as image using Django templates
Jsignature feild in stored in database in this way user_signature = [{"y": [25, 26, 33, 43, 51, 60, 66, 70, 75], "x": [99, 103, 104, 105, 105, 105, 105, 106, 106]}, {"y": [46, 44, 44, 44, 46, 49, 51, 52, 53, 55, 59, 60, 61, 63, 65, 66], "x": [106, 111, 116, 121, 124, 122, 119, 114, 108, 105, 107, 112, 118, 122, 125, 129]}, {"y": [61, 65, 66, 65, 63, 61, 58, 54, 52, 54, 55, 58, 58, 63], "x": [121, 125, 129, 133, 136, 139, 143, 141, 137, 141, 145, 148, 153, 154]}] Now how can i display this user_signature as image in django template. I tried in this way <img src="data:image/png;base64,{{request.user.user_signature}}" -
Can we deploy keras model on web using Php?
Well currently i am learning machine learning and i found out that we deploy keras model using python framework django or flask? Why we can't Deploy using Php? -
How can I update first_name, last_name & email of Django model User and update other field in separate models
I have been learning the Django tutorial for a few weeks using YT, StackOverflow, Django documentation, and other sources. So, maybe my question goes out of the sense. I hope you will understand my question. If anything is a mistake on my code or you want to give me some suggestions, then reply to me. I make the site locally on my computer. First of all, I have created a signup page and login page using Django Model. After User login the site, In profile settings, I have created form field like first_name, last_name, email, mobile_number, date_of_birth, zip_code, address, website, bio, etc. I have models.py for Account setting from django.db import models from django.contrib.auth.models import User # Create your models here. class Account(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) profile_photo = models.ImageField(upload_to='profile', null=True) mobile_number = models.PositiveBigIntegerField(null=True) date_of_birth = models.DateField(auto_now_add=False, auto_now=False, null= True) zip_code = models.IntegerField(null=True) address = models.CharField(max_length=225, null=True) website = models.URLField(max_length=100, null=True) bio = models.CharField(max_length=225, null=True) In forms.py from django import forms from .models import Account class AccountForm(forms.ModelForm): class Meta: model = Account fields = '__all__' In templates <form class="form mx-auto my-5" method="POST" action="" enctype="multipart/form-data"> <input name="user" type="hidden" value="{{request.user.id}}" required> <div class="form-row"> <div class="col form-group"> <label for="first_name" class="font-weight-bold">First name (required):</label> … -
How to stop function and run other after x seconds in Django?
So basically I have a view which runs a function that is written in another file. Since I don't want the function running any longer than 25 seconds, is there any way for me to skip the function after it has ran for 25 seconds and just simply return the redirect reverse? Here is what my view looks like def radio(request): song_search = request.POST.get('search').capitalize() request.session['song'] = song_search if models.Genre.objects.filter(Song=song_search): song_query_createobject(request) else: song_query_createobject(request) song_finder(request) return redirect(reverse('songresult')) -
Django ValueError: The view cookbook.views.profile didn't return an HttpResponse object. It returned None instead
I've read through plenty of questions with this same error message but I could not find the same case as mine. Usually you would see if statement with no returns but this doesnt have if statements. error Traceback (most recent call last): File "C:\Users\locti\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\locti\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response raise ValueError( ValueError: The view cookbook.views.profile didn't return an HttpResponse object. It returned None instead. There are other views as well but I dont think they are related view.py def profile(request, name): try: user = User.objects.get(username=name) except User.DoesNotExist: return render(request, "cookbook/error.html") return render(request, "cookbook/profile.html", { "pageuser": user }) profile.html {% extends "cookbook/layout.html" %} {% block body %} <h2>{{ user.username }}</h2> {% endblock %} -
Randomly pick X objects with distinct names
The following attempt: Article.objects.filter(category__id="b5e20323-8cec-413a-b405-342b3809f9a4").distinct('title').order_by("?") Gives me: ProgrammingError: SELECT DISTINCT ON expressions must match initial ORDER BY expressions I tried to drop to raw SQL. So I tried: SELECT * FROM (SELECT DISTINCT title from article WHERE category_id = '...') AS inner_distinct ORDER BY RANDOM() LIMIT 3 This works but I need to add an additional field to to the title. If I change my raw query to: SELECT * FROM (SELECT DISTINCT title, id from article WHERE category_id = '...') AS inner_distinct ORDER BY RANDOM() LIMIT 3 All of a sudden the DISTINCT keyword has no effect. How can I overcome this? -
Django table with query results and computed data
I am trying to list the last entry a user makes in a table along with the number of entries the user has made. The query I have so far gets me the last entry (there can only be one active at a time) data = Student.objects.filter(session=session, active=True) The objects are then sent over and displayed in a table {% for item in data %} <tr> <td>{{ item.name }}</td> <td>{{ item.category }}</td> <td align="center">{{ [count here]}}</td> </tr> {% endfor %} I would like the count for the number of times the user's name appears in the database in the same row as the object data itself. I would like the count displayed where "count here" is as above. -
why do I get "ModuleNotFoundError: No module named 'model-name'" error when I run my Django project after moving to python3.8.5?
I have a Django project which worked fine, but then I installed Python3.8.5, uninstalled the python27 I was using before, and installed Django 3.1.1 on my computer. Now when I run my project I get the error "ModuleNotFoundError: No module named 'model-name'". Seems like it can't find my models. How do I get my project to run properly? -
How to send POST request in order to add an object that has ForeignKey in Axios and Django Rest Framework
Code models.py class CustomUserManager(UserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): if not email: raise ValueError('メールアドレスは必須項目です。') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) # Django提供のカスタムユーザーのFieldを決定 class User(AbstractUser): # AbstractUserでpasswordは定義済みのため、ここではpasswordを再定義しない(DBにはちゃんと保存される。) username = models.CharField(max_length=150, unique=True) email = models.EmailField(max_length=100, unique=True) profile = models.TextField(max_length=800, blank=True, null=True) icon = models.ImageField(blank=True, null=True) background = models.ImageField(blank=True, null=True) # AbstractUserはfirst_name,last_nameを保持しているため無効化 first_name = None last_name = None is_staff = models.BooleanField( ('staff status'), default=True, help_text=( '管理サイトへのアクセス権を持っているかどうか'), ) is_active = models.BooleanField( ('active'), default=True, help_text=( 'ユーザーがアクティブかどうか' ), ) is_superuser = models.BooleanField( ('superuser status'), default=True, help_text=( 'Designates that this user has all permissions without ' 'explicitly assigning them.' ), ) # createdAt, updatedAt は時系列順等に並べたいモデルに付与 created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = CustomUserManager() EMAIL_FIELD = 'email' USERNAME_FIELD = 'username' REQUIRED_FIELD = ["username", "email"] class Meta: db_table = "users" # ====== ======= ====== ====== ====== ====== ======= ======= class Bland(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Meta: db_table = "blands" # … -
compare fields in two different django models
I am trying fill a field (hours) in Employee model based on the aggregate of a field (time_worked) in Timesheet model. MODELS.PY class Employee(models.Model): ... user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name='employees') hours = models.DurationField(null=True, blank=True) class Timesheet(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) employee = models.ForeignKey(Employee, on_delete=models.CASCADE, null=True,) time_worked = models.DurationField(null=True, blank=True) How do add up the time_worked in Timesheet model of only employee A and insert the results into hours column of Employee model for employee A? -
Django Static - Google Cloud Storage - CDN
I am still new with serving my Django static/media files to Google cloud storage. It's working now but I am not sure if this is right or is this enough already, do I still need to use CDN like Cloudfront or other similar services? I am really confused and any recommendation would be much appreciated. Below is my configuration. import os from google.oauth2 import service_account BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) GS_CREDENTIALS = service_account.Credentials.from_service_account_file( os.path.join(BASE_DIR, 'extras/google-storage.json') ) STATICFILES_STORAGE = 'extras.storage_backends.GoogleCloudStaticFileStorage' DEFAULT_FILE_STORAGE = 'extras.storage_backends.GoogleCloudMediaFileStorage' GS_PROJECT_ID = 'project_id' GS_STATIC_BUCKET_NAME = 'static_bucket' GS_MEDIA_BUCKET_NAME = 'media_bucket' STATIC_URL = 'https://storage.googleapis.com/{}/'.format(GS_STATIC_BUCKET_NAME) MEDIA_URL = 'https://storage.googleapis.com/{}/'.format(GS_MEDIA_BUCKET_NAME) GS_DEFAULT_ACL = 'publicRead' I am using the following: Django 2.2 Python 3.7 Thanks you so much! -
select serial number from the list given for user in django
i wrote a Django app but it's not complete. it's a kinda CRM app for Controlling my customers. how does it work? in the client section, I enter the customer's name, phone number, email, name of the app that he/she bought, and the SERIAL NUMBER image_one when I create a new user I have to manually type the serial number image_two but I don't want that. WHAT I Want?? in the product section, after I enter the product's name, I want a place to enter 1000 serial numbers ( serial numbers are generated in other app and that app gave me a text file with thousands of serial numbers). I want something like this in Django App: image_tree now the final part : in the client section, when I chose the product name (One product or more), I want a serial number picked up from the list and never use for another user. image_foure I know my English is bad. sorry for that :( please help any idea how I can do this? -
Python script to django html output
I want to put python script output to HTML using Django with a button. When the user clicks the button again and it changes the random number again. import random num = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'] print(random.choice(num)) -
when should you employ the POST method over the GET method for submitting data from a form?
when should you employ the POST method over the GET method for submitting data from a form? 1-when you want the data to be cached 2- when efficiency is important 3- when the data in the form may be sensitive 4- when you want to use your browser to help with dubugging and explain the answer please -
Django Python POST Method not writing to database
I now have an issue with my POST Method not writing to the database and not showing in Admin site. the views.py file works until it gets to the 'if form.is_valid()' but doesn't go any further than that. What am I doing wrong? Please help, I've spent time trying to search for the answer but to no avail. code as below urls.py path('weekly/', user_views.weekly, name='weekly'), views.py def weekly(request): if request.method == 'POST': form = SubscriptionForm(request.POST) print('I got this far 3!') if form.is_valid(): form.save() messages.success(request, 'Thank you for your payment!') return redirect('classes') else: return render(request, 'clubex/weekly.html', {'title': '1 Week Free'}) else: return render(request, 'clubex/weekly.html', {'title': '1 Week Free'}) models.py (do these names have to match the 'id' in the HTML doc?) class Subscription(models.Model): firstName = models.CharField(max_length=100) lastName = models.CharField(max_length=100) username = models.CharField(max_length=100) sub_type = models.CharField(max_length=50) email = models.EmailField(max_length=100) address = models.CharField(max_length=100) address2 = models.CharField(max_length=100) state = models.CharField(max_length=100) country = models.CharField(max_length=100) zip = models.CharField(max_length=10) same_address = models.BooleanField() save_info = models.BooleanField() credit = models.BooleanField() debit = models.BooleanField() paypal = models.BooleanField() cc_name = models.CharField(max_length=100) cc_number = models.CharField(max_length=20) cc_expiration = models.CharField(max_length=10) cc_cvv = models.IntegerField() def __str__(self): return f'{self.firstName} {self.lastName} {self.sub_type}' forms.py (do these names have to match the 'id' in the HTML doc?) class SubscriptionForm(forms.ModelForm): … -
How to save variables into mysql database in django
so l have pulled the data from a movie website and l saved it into variables for example title but now I'm struggling to send this data to MySQL DB def index(request): response = requests.get( 'https://fmovies.to/api/list_movies.json', params={'limit':'20'}, ) json_response = response.json() movies = json_response['data']['movies'] #title = movies[0]['title'] #movie_url = movies[0]['url'] #description = movies[0]['description_full'] #movie_torrent_link = movies[0]['torrents'][0]['url'] #cover_image = movies[0]['medium_cover_image'] for value in movies: title = value['title'] movie_url = value['url'] description = value['description_full'] movie_torrent_link = value['torrents'][0]['url'] image = value['medium_cover_image'] rating = value['rating'] genre = value['genres'] runtime = value['runtime'] year_of_production = value['year'] slug = value['slug'] print(image) print(rating) print(runtime) print(year_of_production) print(slug) return render(request, 'index.html',{'title':title}) -
How to Login/Logout a User Django Rest
I am using DjangoRestFramework-SimpleJWT, The user is able to obtain a JSONWebToken. My Question is: How to create a Login and Logout API, were the user is able to Login/Logout? Thanks. -
compress and minifiying files failed at {% compress css %} in base.html file i'm using django, python. OS : Windows 8.1
I am developing a django-based application under windows 8.1 I install the following packages after activating my virtual environment: Django == 3.0.8 libsass == 0.20.0 django-libsass == 0.8 ... I strictly followed the modification of my setting.py to no avail. I may have a problem with the path of the sass package: ... my base.html template : <!DOCTYPE html> {% load static %} {% load compress %} {% load thumbnail %} <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>{{APPLICATION_NAME}}</title> <link href="https://fonts.googleapis.com/css?family=Quicksand:300,400,500,700" rel="stylesheet"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap- datetimepicker/4.17.47/css/bootstrap-datetimepicker.min.css" />` {% compress css %} <link href="{% static 'css/main.scss' %}" type="text/x-scss" rel="stylesheet"> <link href="{% static 'css/mention.scss' %}" type="text/x-scss" rel="stylesheet"> {% endcompress %} when I run python manage.py runserver and access http://127.0.0.1:8000 I get the blocking error: During handling of the above exception (No module named 'sass {infile} {outfile}'), another exception occurred: and above : Error during template rendering In template E:\Developpement\Langages\python\django\crm\templates\base.html, error at line 16 ({% compress css %}) thank you for unblocking me -
Live Console data to webpage using django
I'm creating a website using Django where I need to show the live console data of the pycharm to the webpage. How can I do that? -
Prepopulate form with it's instance if invalid using CreateView Django
I use generic CreateView to create a User instance. class SignUp(CreateView): template_name = 'reg.html' form_class = SignUpForm success_url = reverse_lazy('login') def form_valid(self, form): raw_password = form.instance.password form.instance.set_password(raw_password) return super().form_valid(form) How would I efficiently prepopulate form with it's own instance if any form error occurs? Without rewriting post methods or smth if possible. Thanks.