Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How to create a view that can be emailed to users?
In my DB, I have a bunch of objects of model 'Foo'. Users can create, update, delete objects in the admin panel. Once a week I would like to send a digest of all objects that were created, updated, or deleted. I am using the django-simple-history plugin so I am able to create a dictionary that has changes for a given date range. This part is OK. I would like to take this data, put it in a HTML page, and then email it to a distribution list. For the 2nd part, do I create a Django view or just create a HTML template and do variable substitution? This view will never been shown on a webpage. Not sure what is the easiest way to do this. -
hosting django app its return path: .github/workflows/main_school-database.yml
am trying to host my django app on Microsoft azure but when i choose my github account, my repository and my branch when its successeful but when I click on Preview File its throws me an error saying: File path: .github/workflows/main_school-database.yml and with something i did not know. its looks like i need to create yml file inside my project directory and paste that code its throws me. I'm a begineer in Microsoft Azure and this is my first time building an applications on Azure with django after i migrate from Heroku to Microsoft Azure. is anybody who can help please? the logs: # Docs for the Azure Web Apps Deploy action: https://github.com/Azure/webapps-deploy More GitHub Actions for Azure: https://github.com/Azure/actions More info on Python, GitHub Actions, and Azure App Service: https://aka.ms/python-webapps-actions name: Build and deploy Python app to Azure Web App - school-database on: push: branches: - main workflow_dispatch: jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Set up Python version uses: actions/setup-python@v1 with: python-version: '3.9' - name: Create and start virtual environment run: | python -m venv venv source venv/bin/activate - name: Install dependencies run: pip install -r requirements.txt # Optional: Add step to run tests here (PyTest, … -
ERROR: Could not build wheels for backports.zoneinfo, which is required to install pyproject.toml-based projects
The Heroku Build is returning this error when I'm trying to deploy a Django application for the past few days. The Django Code and File Structure are the same as Django's Official Documentation and Procfile is added in the root folder. Log - -----> Building on the Heroku-20 stack -----> Determining which buildpack to use for this app -----> Python app detected -----> No Python version was specified. Using the buildpack default: python-3.10.4 To use a different version, see: https://devcenter.heroku.com/articles/python-runtimes Building wheels for collected packages: backports.zoneinfo Building wheel for backports.zoneinfo (pyproject.toml): started Building wheel for backports.zoneinfo (pyproject.toml): finished with status 'error' ERROR: Command errored out with exit status 1: command: /app/.heroku/python/bin/python /app/.heroku/python/lib/python3.10/site-packages/pip/_vendor/pep517/in_process/_in_process.py build_wheel /tmp/tmpqqu_1qow cwd: /tmp/pip-install-txfn1ua9/backports-zoneinfo_a462ef61051d49e7bf54e715f78a34f1 Complete output (41 lines): running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-3.10 creating build/lib.linux-x86_64-3.10/backports copying src/backports/__init__.py -> build/lib.linux-x86_64-3.10/backports creating build/lib.linux-x86_64-3.10/backports/zoneinfo copying src/backports/zoneinfo/_zoneinfo.py -> build/lib.linux-x86_64-3.10/backports/zoneinfo copying src/backports/zoneinfo/_tzpath.py -> build/lib.linux-x86_64-3.10/backports/zoneinfo copying src/backports/zoneinfo/_common.py -> build/lib.linux-x86_64-3.10/backports/zoneinfo copying src/backports/zoneinfo/_version.py -> build/lib.linux-x86_64-3.10/backports/zoneinfo copying src/backports/zoneinfo/__init__.py -> build/lib.linux-x86_64-3.10/backports/zoneinfo running egg_info writing src/backports.zoneinfo.egg-info/PKG-INFO writing dependency_links to src/backports.zoneinfo.egg-info/dependency_links.txt writing requirements to src/backports.zoneinfo.egg-info/requires.txt writing top-level names to src/backports.zoneinfo.egg-info/top_level.txt reading manifest file 'src/backports.zoneinfo.egg-info/SOURCES.txt' reading manifest template 'MANIFEST.in' warning: no files found matching '*.png' under directory 'docs' warning: no files found matching '*.svg' under directory … -
Django file upload testcase: how to send both form data and files in request
I want to write a testcase for file upload page which also have other form fileds. So I come up with the following code: file_b = open(test_file2, 'rb') file_c = open(test_file3, 'rb') form_data = {'form_field_1': 'abc', 'form_field_2': 'def'} form_data = form_data.update({'file_name': self.file_b, 'co-file_name': self.file_c}) self.client.post(reverse('overrun_cause_modal', kwargs={'workflowid': self.wf_id}), data=form_data, format='multipart') the above code caused form to be invalid: form = WorkflowForm(data=form_data) form.is_valid() --> False if I do comment out: form_data = form_data.update({'file_name': self.file_b, 'co-file_name': self.file_c}) then form is valid. How can I send both form data and files in request so that I can have a valid regular form and also request.FILES['file_name'], request.FILES['co-file_name'] as well as request.FILES['file_name'].name and request.FILES['co-file_name'].name? -
Django migration IntegrityError: invalid foreign key (but the data exists)
I am gradually updating a legacy Django application from 1.19 -> 2.2 and beyond. To upgrade to 2.2, I just added on_delete=models.CASCADE to all models.ForeignKey fields that did not have the error. Possibly unrelated, when I run manage.py migrate, Django throws the following error (I shortened the table/field names for brevity): django.db.utils.IntegrityError: The row in table 'X' with primary key '3' has an invalid foreign key: X.fieldname_id contains a value '4' that does not have a corresponding value in Y__old.id. Note in particular the __old.id suffix for the db table that Django expects to contain a row with id 4. When manually inspecting the db, the table Y does really contain a valid row with id 4! I'm assuming, to support the migration, Django is making some temporary tables suffixed with __old and somehow it is unable to migrate said data? The db row Y in question is really simple: a char, boolean, and number column. -
Where does manage.py get the frontend when there isn't a main.js?
I want to know why my changes aren't reflecting in the browser/console I'm working on a React + Django app and encountered this warning react-dom.development.js:86 Warning: The tag <thread> is unrecognized in this browser When I saw this I found the one instance I wrote <thread> and replaced it with <thead> I then saved my changes and re ran python manage.py runserver and webpack --mode development --watch ./leadmanager/frontend/src/index.js --output-path ./leadmanager/frontend/static/frontend/ After reloading my app I'm still confronted with the same warning message and when I inspect the warning I can see in the Chrome console that the file is still using <thread> I thought it could be because I didn't clear my static/frontend/main.js before re running webpack which didn't change anything I then notice when I run python manage.py runserver without running the separate webpack command, and after deleting static/frontend/main.js my app still gets loaded to localhost... It was my understanding that static/frontend/main.js is what python uses to display my app in the browser Where is python getting the frontend to display my app when there isn't a main.js file? -
ValueError: Could not find function validator when calling makemigrations in Django 4.0
Using the solution here to validate URLField, I am getting ValueError when I run python manage.py makemigrations and I'm not sure why. What am I doing wrong? from django.contrib.auth.models import User from django.db import models from django.core.exceptions import ValidationError from urllib.parse import urlparse def validate_hostname(*hostnames): hostnames = set(hostnames) def validator(value): try: result = urlparse(value) if result.hostname not in hostnames: raise ValidationError(f'The hostname {result.hostname} is not allowed.') except ValueError: raise ValidationError('Invalid URL') return validator class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True) twitter = models.URLField( blank=True, null=True, validators=[validate_hostname('twitter.com', 'www.twitter.com')] ) Traceback $ python manage.py makemigrations Migrations for 'userprofiles': userprofiles/migrations/0002_userprofile_twitter.py - Add field twitter to userprofile Traceback (most recent call last): File "/home/master/github/mywebsite/src/manage.py", line 22, in <module> main() File "/home/master/github/mywebsite/src/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/master/.cache/pypoetry/virtualenvs/mywebsite-WMQVlvmt-py3.10/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/home/master/.cache/pypoetry/virtualenvs/mywebsite-WMQVlvmt-py3.10/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/master/.cache/pypoetry/virtualenvs/mywebsite-WMQVlvmt-py3.10/lib/python3.10/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/home/master/.cache/pypoetry/virtualenvs/mywebsite-WMQVlvmt-py3.10/lib/python3.10/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/home/master/.cache/pypoetry/virtualenvs/mywebsite-WMQVlvmt-py3.10/lib/python3.10/site-packages/django/core/management/base.py", line 98, in wrapped res = handle_func(*args, **kwargs) File "/home/master/.cache/pypoetry/virtualenvs/mywebsite-WMQVlvmt-py3.10/lib/python3.10/site-packages/django/core/management/commands/makemigrations.py", line 214, in handle self.write_migration_files(changes) File "/home/master/.cache/pypoetry/virtualenvs/mywebsite-WMQVlvmt-py3.10/lib/python3.10/site-packages/django/core/management/commands/makemigrations.py", line 255, in write_migration_files migration_string = writer.as_string() File "/home/master/.cache/pypoetry/virtualenvs/mywebsite-WMQVlvmt-py3.10/lib/python3.10/site-packages/django/db/migrations/writer.py", line 141, in as_string operation_string, operation_imports = OperationWriter(operation).serialize() File "/home/master/.cache/pypoetry/virtualenvs/mywebsite-WMQVlvmt-py3.10/lib/python3.10/site-packages/django/db/migrations/writer.py", line 99, in serialize _write(arg_name, arg_value) File "/home/master/.cache/pypoetry/virtualenvs/mywebsite-WMQVlvmt-py3.10/lib/python3.10/site-packages/django/db/migrations/writer.py", … -
Model instances autocreation on interval
I want to implement django models autocreation but have no clue how to do it. As example we set 1 year interval, and when it passes the model instance is automatically created. -
Can not see an app with name "advertisements" in admin interface
I tested it many times. When I add an app with the name advertisements (add models, admin + register in INSTALLED_APPS) it is not listed in the admin interface (it is very hard to see but it disappears after microseconds). models.py: from django.db import models # Create your models here. class Advertisement(models.Model): pass admin.py: from django.contrib import admin from .models import Advertisement # Register your models here. @admin.register(Advertisement) class AdvertisementAdmin(admin.ModelAdmin): pass apps.py: from django.apps import AppConfig class AdvertisementsConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'advertisements' settings.py: INSTALLED_APPS = [ # ... "advertisements", ] Changing an app directory to something like advertisements2, app name (in apps.py) to advertisements2 solves the problem. -
How to print value from specific model/queryset Django
This is my code for the view def return_chat(request): context = {'client_name': request.POST['client_name'], 'messages': [], 'datetime': []} def order_messages(): replies = Replies.objects.all().filter(unique_num=request.POST['unique_num']) sent_messages = InstantMessages.objects.all().filter(unique_num=request.POST['unique_num']) + 'S' from itertools import chain all_messages = list(chain(replies, sent_messages)) all_messages.sort(key=lambda x: x.datetime) return all_messages for item in order_messages(): context['messages'].append(item.message) context['datetime'].append(item.datetime) return render(request, 'chat.html', context) My HTML code: <html> <body> <div style="position:relative;background-color:#f5f5f5;width:900px;height:500px;border-radius:15px;border:2px solid black;margin:auto;margin-top:10%;"> <div style="position:absolute;left:20px;padding:10px;top:15px;border-left-style:solid;border-left-color:#48b8fa;margin:auto;width:870px;max-height:350px;overflow-y:scroll;"> {% for all_messages in messages %} <br> {{ all_messages }} <br> {% endfor %} </div> <textarea placeholder="Type your message to {{ client_name }} here.." style="background-color:#f5f5f5;position:absolute;width:900px;height:90px;border-bottom-left-radius:15px;border-bottom-right-radius:15px;bottom:0;border:2px solid black;right:-2px;bottom:-2px;padding:20px;margin:auto;padding-right:80px"></textarea> <button style="position:absolute;width:80px;height:90px;border-bottom-right-radius:15px;bottom:0;border:2px solid black;right:-2px;bottom:-2px;"><b>Send</b></button> </div> </body> </html> Essentially. I want the replies on the left and the InstantMessages model to appear in the right side in the Django template. I need css/html, and Python advice. Either or all would help greatly!! -
Display field from another model in django admin
Let say I have two model. I want to make subject field in Program model appear in UserProgramAdmin. What is the best way to do that? class Program(models.Model): name = models.CharField(max_length=15, blank=False) summary = models.CharField(max_length=200, blank=True) subject = models.ManyToManyField(Subject, related_name='all_subjects') is_active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True, editable=False) updated_at = models.DateTimeField(auto_now=True, editable=False) def __str__(self) -> str: return self.name class UserProgram(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) program = models.ForeignKey( Program, on_delete=models.CASCADE, ) is_active = models.BooleanField(default=True) is_finish = models.BooleanField(default=False, editable=False) /admin.py class UserProgramAdmin(admin.ModelAdmin): list_display = ('user', 'program' , 'is_active', 'is_finish') Thanks in advance -
How to change a field type in a Django model with existing data?
I have the following existing twitter field on the extended UserProfile model and I'd like to change the field type from a URLField to a CharField with max_length of 20. When I try to migrate the change, I get the error django.db.utils.DataError: value too long for type character varying(20). I do not care about existing data in that field and prefer they go blank if there is existing data when migrating. How can I change the field type and clear existing data? class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True) # old field twitter = models.URLField(verbose_name="Twitter", blank=True) # new field # twitter = models.CharField( # max_length=20, verbose_name="Twitter Username", null=True, blank=True # ) -
dal.autocomplete and AutocompleteFilter don't work in model with foreign key to itself don't work in admin site
I wan't to make a filter on categories by parent category, I use a model and for parent category I linked to itself. the model: class Category(models.Model): name = models.CharField(max_length=100) parent = models.ForeignKey( "self", on_delete=models.CASCADE, null=True, blank=True, related_name="childs" ) description = models.TextField(null=True, blank=True) is_adult = models.BooleanField(default=False) is_active = models.BooleanField(default=True) in admin.py : class ParentCategoryFilter(AutocompleteFilter): title = "By parent category" field_name = "parent" autocomplete_url = "parent-category-autocomplete" is_placeholder_title = True class CategoryAdmin(admin.ModelAdmin): search_fields = ["name"] autocomplete_fields = ["parent"] fieldsets = ( ( _("Details"), { "fields": ( "name", "parent", "description", ), }, ), ) list_display = ( "name", "parent", ) list_filter = [ParentCategoryFilter] admin.site.register(Category, CategoryAdmin) and the views.py where ParentCategoryFilter is defined: class ParentCategoryAutocompleteView(autocomplete.Select2QuerySetView): permissions = [ "CategoryView", ] def get_queryset(self): qs = Category.objects.filter(parent__isnull=True) if self.q: qs = qs.filter(Q(name__istartswith=self.q)) return qs the problem I get is that in the filter I get the child's categories name. I don't know what the problem with it. -
ClientError at /saved_json/ An error occurred (403) when calling the HeadObject operation: Forbidden
I was trying to add images, json files to s3 bucket. It was going well about few months ago but i have opened it now and it shows an error on the line where the object of model is created. Error named: Exception Type: ClientError at /saved_json/ Exception Value: An error occurred (403) when calling the HeadObject operation: Forbidden for image in images: photo = Photo.objects.create( //eror is here email=data['email'], image=image, ) -
How to send emails with send_mass_mail in Django for more than one recipients dynamically?
I try to send an email to more than one recipients but I am doing something wrong. I try to use use a for loop to get the email addresses from the user. If I print the emails these are in this format: 'someone@xy.com'. But if I try to send them, only one user gets the email. views.py from django.shortcuts import render from django.core.mail import send_mass_mail from somemodels.models import Project import datetime import calendar def emails(request): today = datetime.date.today() weekday = today.weekday() month = datetime.date.today().month year = datetime.date.today().year cal = calendar.monthrange(year, month)[1] # az utolso nap az aktualis honapban firstday = datetime.date.today().replace(day=1) # az elso nap az aktualis honapban subject='hello' message='what's up?' from_email='myemail@gmail.com' for p in Project.objects.raw('SELECT * FROM somemodels_project INNER JOIN auth_user ON auth_user.id = othermodel_project.permitted_users'): recipient_list = p.email, print(recipient_list) if (today == firstday): messages = [(subject, message, from_email, [recipient]) for recipient in recipient_list] send_mass_mail(messages) print('Successfully sent') else: print('Not sent') return render(request, 'performance/emails.html') urls.py app_name = 'email' urlpatterns = [ path('emails/', login_required(views.emails), name='emails'), ] -
Django - dictionary update sequence element #0 has length 0; 2 is required
When I am logged out I cannot access my site anymore. Why does this happen? I doesn't matter what view I change I cannot access the site anymore. ValueError at /accounts/login/ dictionary update sequence element #0 has length 0; 2 is required Request Method: GET Request URL: http://127.0.0.1:8000/accounts/login/?next=/ Django Version: 3.2.5 Exception Type: ValueError Exception Value: dictionary update sequence element #0 has length 0; 2 is required Exception Location: /Users/lorenz/.conda/envs/netto_clone/lib/python3.10/site-packages/django/template/context.py, line 244, in bind_template Python Executable: /Users/lorenz/.conda/envs/netto_clone/bin/python Python Version: 3.10.4 Python Path: ['/Users/lorenz/PycharmProjects/netto_clone', '/Users/lorenz/PycharmProjects/netto_clone', '/Users/lorenz/Library/Application ' 'Support/JetBrains/Toolbox/apps/PyCharm-P/ch-0/213.6777.50/PyCharm.app/Contents/plugins/python/helpers/pycharm_display', '/Users/lorenz/.conda/envs/netto_clone/lib/python310.zip', '/Users/lorenz/.conda/envs/netto_clone/lib/python3.10', '/Users/lorenz/.conda/envs/netto_clone/lib/python3.10/lib-dynload', '/Users/lorenz/.conda/envs/netto_clone/lib/python3.10/site-packages', '/Users/lorenz/Library/Application ' 'Support/JetBrains/Toolbox/apps/PyCharm-P/ch-0/213.6777.50/PyCharm.app/Contents/plugins/python/helpers/pycharm_matplotlib_backend'] Server time: Fri, 01 Apr 2022 16:21:12 -0100 -
Django + Vue.js GET /ws HTTP/1.1 404 2292 error every second
I am building a project with Vue.js on the front-end and Django on the back-end. I am using port 8000 for Django and port 8080 for Vue.js. Every time I route to something on the 8080 port, I get this error like this that gets printed out every second: [01/Apr/2022 17:18:57] "GET /ws HTTP/1.1" 404 2292 Not Found: /ws I can't figure out why this happens or how to fix it. -
How to record audio from the mic and save it as a .wav file in django web app
I am trying to make and deploy speech emotion detection machine learning model using Django for that I have to take audio recording from the user before setting up the model, I am stuck at how can I take audio recording from the user and send it to my ML model to detect emotion. please help! -
Import csv file using django - form doesn't appear
I try to create a project and I need to import a csv file (Import csv file using django - Exception Type: DatabaseError) I want to display the form on other page, not on home. But, when I create a new path, it didn't display me that specific view. csvs/urls.py from django.urls import path from .views import upload_file_view app_name='csvs' urlpatterns =[ path('import/', upload_file_view, name='upload-view') ] csvs/views.py from django.shortcuts import render from .forms import CsvModelForm from .models import Csv import csv from django.contrib.auth.models import User from sales.models import Sales def upload_file_view(request): form = CsvModelForm(request.POST, request.FILES) if form.is_valid(): form.save() form = CsvModelForm() obj= Csv.objects.get(activated=False) with open(obj.file_name.path, 'r') as f: reader = csv.reader(f) for i, row in enumerate(reader): if i==0: pass else: #row = "".join(row) #row = row.replace(";"," ") #row=row.split() #print(row) #print(type(row)) date = row[1] user = User.objects.get(username=row[0]) Sales.objects.create( date=date, product= row[2], user=user, ) obj.activated=True obj.save() return render(request, 'upload.html', { 'form': form }) main file - urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from sales.views import import_view, home_view urlpatterns = [ path('admin/', admin.site.urls), path('import/', import_view, name="import"), path('', home_view, name="home"), path('import/', include('csvs.urls', namespace='csvs')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) sales/views.py from django.shortcuts import render … -
How can I store data of registration into my django database?
I want to store data of patient from registration page to my django database using serializers but I am not sure how to do that!! Here I am attaching views.py file: from django.http import HttpResponse, HttpResponseForbidden from django.shortcuts import render,redirect from django.contrib import messages from django.contrib.auth import authenticate,login,logout from rest_framework import viewsets from .models import * from .serializers import PatientSerializer class PatientView(viewsets.ModelViewSet): queryset = patient.objects.all() serializer_class = PatientSerializer def login_user(request): if request.method == 'POST': username = request.POST['Username'] password = request.POST['Password'] user_type = request.POST['user_type'] user = authenticate(username=username, password=password) #doctor is superuser and receptionist is normaluser if user is None: login(request, user) if user_type == 'Doctor': return render(request,'') elif user_type == 'Receptionist': return render(request, 'Auth/registration.html') else: return render(request,'') else: messages.error(request, "Bad Credentials") return redirect('login') return render(request, "Auth/login.html") def registration(request): if request.method == "POST": username = request.POST['username'] PID = request.POST['PID'] Name = request.POST['Name'] Age = request.POST['Age'] DOB = request.POST['DOB'] gender = request.POST['gender'] BG = request.POST['BG'] PN = request.POST['PN'] Add = request.POST['Add'] else: if request.user.is_staff: return render(request,'Auth/registration.html') else: return HttpResponseForbidden('<h1> 403 Forbidden <br>You are not allowed to access this page.</h1>') This is my registration.html file : <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> … -
Making a GET request with filter
My model is the following class PokerRoom(models.Model): STATUS = (("Pending", "Pending"), ("Finished", "Finished")) status = models.CharField( max_length=11, choices=STATUS, verbose_name=_("Status da Story"), default="Pending", ) name = models.CharField(max_length=200, verbose_name=_("room name"), validators=[alphanumeric]) slug = models.CharField(max_length=200, verbose_name=_("room slug"), null=True, blank=True) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) styleCards = MultiSelectField(choices=CHOICES, default=FIBONACCI) datetime = models.DateTimeField(null=True, blank=True) date = models.CharField(max_length=10, null=True, blank=True) user = models.ForeignKey(User, on_delete=DO_NOTHING) first_name_user = models.CharField( max_length=200, verbose_name=_("user name"), null=True, blank=True ) deck = models.ForeignKey(Pack, on_delete=models.CASCADE) index = models.IntegerField( null=True, blank=True, verbose_name=_("story being voted") ) I'm my application, I want to make a searchbar for "status" and "name" and do a GET request with those filter that would be provided by the client when he make the search. But I don't know how to do that in my views.py I was thiking in a GET method like this, but I don't know how to get the planningName and planningStatus from the frontend. def get(self, request, pk): """GET of PokerRoom historic""" user = request.user pk = self.kwargs["pk"] planningName = planningStatus = moderatorRoom = PokerRoom.objects.values("id", "first_name_user", "date", "name", "status", "styleCards", "datetime", 'slug' ).filter(Q(user= user) | Q(name=planningName) | Q(status=planningStatus)).order_by("-datetime") Can someone helpe me? -
How do I check if a record saved successfully in Django?
Could you take a look at this code below? It seems like the form is submitted and validated successfully. However, it doesn't seem to be saving to my database. Please check my comment in the post() method below starting with #####. I know in PHP one can print_r($var); exit; but can't seem to find equivalent in Python/Django. class ReportListView(ListView): model = ReportList form_class = ReportListForm initial = {} context_object_name = 'reportlists' template_name = "reports.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) #context['now'] = timezone.now() return context def get_queryset(self): return ReportList.objects.filter(user=self.request.user) def get(self, request, *args, **kwargs): form = self.form_class(initial=self.initial) return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): # process form cleaned data # name = form.cleaned_data.get('name') # .lower() new_report = form.save(commit=False) new_report.user = self.request.user new_report.save() ### what can I write to check if new report has been saved? ### also, how can I print something here to print that in the browser e.g. ### print(datavariable) ### exit() ?? or something to stop execution here so that I read previous print output return redirect('report') return render(request, self.template_name, {'form': form}) -
Queryset to filter exactly N objects from a table
I am trying to work out how to allocate exactly N available objects, in a way which is safe against concurrent activity. Is there a way to write a queryset that will fail if it cannot return at least N objects? This is probably an excess of caution for my particular application because the chances of a race are infinitesimal, but I'm curious What I know won't work is available = Foo.objects.filter( status=Foo.AVAILABLE).count() if available < N: #let the user know there aren't enough left # but now something concurrent may grab them! foo_qs = Foo.objects.select_for_update().filter(status=Foo.AVAILABLE)[:N] with transaction.atomic(): for foo in foo_qs: ... # quite a bit. In RL I will have locked related objects as well. foo.status=Foo.RESERVED foo.save() because slicing a queryset guarantees only no more than N objects. Removing the slice might lock a large number of rows that I don't need to lock. Is this inefficient? The whole Foo table won't be locked for long because I update only N objects and then exit the transaction. Is the only answer to grab the objects one at a time inside the transaction, or to get all of them as a list and re-check its length? with transaction.atomic(): foos … -
Django webhook receiver
I built a web hook receiver that takes JSON and creates a model object. It works fine with JSON. But someone I am receiving data from uses a different type of string data. I am currently just printing it out in the console. How would I convert this into a model object? The data they are sending looks like this: Phone1=4441114444&FirstName=Chris&LastName=Farley&DOB=1982-11-21&Email=test@test.com class Client(models.Model): first_name = models.CharField(blank =True, max_length=100) last_name = models.CharField(blank=True, max_length=100) phone = models.CharField(max_length=100, null=True, default="", blank=True) email = models.EmailField(max_length=100,default="", blank=True) @csrf_exempt def webhook(request): if request.method == 'POST': print(json.loads(request.body)) Client.objects.create( first_name=json.loads(request.body)['FirstName'], last_name=json.loads(request.body)['LastName'], phone=json.loads(request.body)['Phone1'], email=json.loads(request.body)['Email'] ) return HttpResponse(request.body, status=200) -
django problem trying to do mosh python Tutorial course
: [Errno 2] No such file or directory python manage.py runserver I tried the cd thing didn't workout Python Tutorial - Python Full Course for Beginners 5:05 project: building a website with Django