Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
fetching on frontend is faster than backend database update, how to sync them up?
I am first sending a POST request to add a new position to table ORDER, and after that promise is completed it then sends a post request to a table ORDER_PRODUCT to associate the previous order with some products. The thing is, it happens too fast, and second POST returns an error If i split those two post requests and fire them up manually then its all good. Whats a good way of sorting this out? -
Python MySQL quit working on MacOS – please explain why not
Here's the problem (MacOS environment): ImportError: dlopen(/Users/mike/.virtualenvs/djangoprod/lib/python3.11/site-packages/MySQLdb/_mysql.cpython-311-darwin.so, 0x0002): Library not loaded: '@rpath/libmysqlclient.21.dylib' Reason: tried: '/usr/lib/libmysqlclient.21.dylib' (no such file) The problem, obviously, is @rpath. Previously, I had no problems with this. "It Just Worked.™" Therefore I do not understand the mechanism that has now gone wrong in this (MacOS ...) environment. The libmysqlclient.21.dylib file does exist, just not "here." So, howcum @rpath now finds the apparent value /usr/lib? In the MacOS environment, the "correct location" of MySQL "ought to be something like" /usr/local/mysql-X.Y.Z-osx10.11-x86_64/lib... and somehow the software at some layer is supposed to "know" that. Obviously, it doesn't. However, I guess my real question is that I guess I don't know how it is all supposed to work. -
How can I intergrate my django app to an alredy made database, probably from a PHP app
this is part of the database. The extention is .sql -- phpMyAdmin SQL Dump -- version 3.2.0.1 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: May 20, 2011 at 05:08 PM -- Server version: 5.1.36 -- PHP Version: 5.2.9-2 SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; -- -- Database: `bincomphptest` -- -- -------------------------------------------------------- -- -- Table structure for table `agentname` -- DROP TABLE IF EXISTS `agentname`; CREATE TABLE IF NOT EXISTS `agentname` ( `name_id` int(11) NOT NULL AUTO_INCREMENT, `firstname` varchar(255) NOT NULL, `lastname` varchar(255) NOT NULL, `email` varchar(255) DEFAULT NULL, `phone` char(13) NOT NULL, `pollingunit_uniqueid` int(11) NOT NULL, PRIMARY KEY (`name_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ; I was creating a new database on django with mysqlite but I think I'm inexperience and this maybe possible -
Django list_display does not work at reverse model
Django list_display does not work at reverse model, i want to list_display the title and the production company of two seperated but related tables. here ist my model.py class ProjectBaseModel(models.Model): title = models.CharField("Titel", max_length=100, blank=False, unique=True) former_title = models.CharField("ehemaliger Titel", max_length=100, blank=True) title_international = models.CharField( "Titel, international", max_length=100, blank=True, null=True, unique=True ) program_length = models.PositiveSmallIntegerField( verbose_name="Länge in Min.", blank=True, validators=[MaxValueValidator(300)] ) def __str__(self): return self.title class Meta: abstract = True ordering = ["title"] class FeatureFilm(ProjectBaseModel): class Meta: verbose_name = "Kinofilm" verbose_name_plural = "Kinofilme" class ProjectCompanySet(models.Model): featurefilm = models.ForeignKey( FeatureFilm, on_delete=models.CASCADE, null=True, blank=True ) tv_movie = models.ForeignKey( TvMovie, on_delete=models.CASCADE, null=True, blank=True ) production_company = models.ForeignKey( CompanyOrBranch, related_name="production_company", verbose_name="Produktionsfirma", on_delete=models.SET_NULL, blank=True, null=True, ) My FeatureFilm table inherits from the ProjectBaseModel table. I want to display the FeatureFilm list in the django backend admin. In the list I want to show the appropriate name, but I also want to show the field production_company which is one row of the ProductionCompanySet table, which is a child table related to the FeatureFilm table. the production_company field ist a foreign key to the CompanyOrBranch Table. Here you can see this table: class CompanyOrBranch(CompanyBaseModel): name = models.CharField( "Firma oder Niederlassung", max_length=60, blank=False, ) and here is my … -
Heroku Django: Looking for wrong GDAL version on new Heroku-22 Stack
I am trying to upgrade from the Heroku-18 to Heroku-22 stack, for my Django web app. In order to use the new stack, I had to upgrade from Python 3.7.2 to Python 3.10.8. From what I've seen on Stack Overflow so far and other sources on the internet, I have already been installing GDAL/GIS the correct way for a Django app on Heroku. Which is to use a buildpack and have it ordered first in the list of buildpacks: remote: Building source: remote: remote: -----> Building on the Heroku-22 stack remote: -----> Using buildpacks: remote: 1. https://github.com/heroku/heroku-geo-buildpack.git remote: 2. heroku/python I expected no issues on the upgrade, but now for some reason it's having trouble finding GDAL. These are the versions that are being installed: remote: -----> Geo Packages (GDAL/GEOS/PROJ) app detected remote: -----> Installing GDAL-2.4.0 remote: -----> Installing GEOS-3.7.2 remote: -----> Installing PROJ-5.2.0 And here is the error I'm getting. Notice that it is not looking for gdal2.4.0, which is what's installed. However, it is looking for gdal which I'd hope would be covered by this install. django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal", "GDAL", "gdal2.2.0", "gdal2.1.0", "gdal2.0.0", "gdal1.11.0", "gdal1.10.0", "gdal1.9.0"). Is GDAL installed? If it is, … -
How to display images from a database row by row
I am trying to create a webpage where i am displaying images of animals as a gallery. I would like the gallery where images are displayed side by side in a row (3 images per row). I tried displaying the images from the database (model) side by side in rows but as a beginner i find this quite difficult and would like help with this. I am coding using the Django framework where the model (animal) contains the following fields: Image_Title, Image_Description, Image_Price. I understand the concept where i would have to loop the Animal objects but i am struggling to put 3 in a row. I am able to put one in a row but that is now what i am looking for. Code for views.py def gallery(request): images = Animal.objects.all() context = { 'images': images, } return render(request, 'AnimalGallery/gallery.html', context) Code for Animal model: class Animal(models.Model): Image = models.ImageField() Image_Title = models.CharField(max_length=50) Image_Description = models.CharField(max_length=500, blank=True) Image_Price = models.FloatField(null=True) def __str__(self): return self.Image_Title Code for the HTML(Displays one image per row): <table> {% for each in images %} <tr> <td>{{each.Image}} </td> <td>{{each.Image_Title}} </td> </tr> {% endfor %} </table> This is a website that has implemented the same concept … -
Django and Africa's Talking API
I am quite new to this and am trying to develop a software system in django which uses the Africa's Talking API for airtime and data topups. I would be very happy to find one who knows how to do this and could help me walk through how to do it. thanks in advance. -
.bg-img not loading on home.html
i've uploaded my live project to heroku, and ever since - the background image in the style.css folder doesn't seem to be working. (trying to showcase directory below) /nooz /nooz2 /static //css ///style.css //images /// background_image.jpg /// generic_pic.png /templates -- home.html settings.py INSTALLED_APPS = [ 'cloudinary_storage', 'django.contrib.staticfiles', 'cloudinary', ] STATIC_URL = 'static/' STATICFILES_STORAGE = 'cloudinary_storage.storage.StaticHashedCloudinaryStorage' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_URL = 'media/' DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') style.css .bg-img { background: url('static/images/background_image.jpg'); height: 550px; width: 100%; background-size: 100% 550px; } home.html <div class="container-fluid bg-img" title="Center Stage Background"></div> I tried the following: Changed pathing Change image collecstatic -
Admin Sorting after applying SimpleListFilter
I want a different ordering to be applied after a SimpleListFilter is being applied. class Store(models.Model): name = models.CharField("name", max_length = 128) state = models.IntegerField("state of store", default = 0) revenue = models.IntegerField("accumulated ...", default = 0) class StoreStateFilter(admin.SimpleListFilter): title = "filter by state" parameter_name = "state" def lookups(self, request, model_admin): return [("on", "on"), ("off", "off")] def queryset(self, request, queryset): ... return queryset The admin looks simple: @admin.register(Store) class StoreAdmin(admin.ModelAdmin): ordering = ["revenue", ...] list_filter = [StoreStateFilter, ...] ... So the normal ordering is after revenue, but after applying StoreStateFilter I want the ordering to be after name. Is there a way to achieve that? -
which are the options to pass multiple variables to a next template in django?
Im developing a django app and I need to pass the values that a client choose to the next step of the process(the next template) The question is, which are the different possibilities to do this?, I was thinking about passing the values through the url or maybe I need to use javascript, It is my first web page that I build so I dont really know which is the best way or method. I tried with passing multiple values through the url but with my knowledge I can only pass one -
Django RAW SQL query how to pass date comparison
I am working with Django Raw SQL as I want to build a relatively complex query, As part of it, I have a case statement that says 'if the date on the record is < today then 1 else 0 - this works. overdue_phases = task.objects.filter(orgid=orgid, taskid=taskidx).raw(''' SELECT '1' as id, case when research_due < "2022-12-01" AND research_status != "done" then 1 else 0 end as count from app_task where taskid = "''' + taskidx + '''"''') overdue_phases = task.objects.filter(orgid=orgid, taskid=taskidx).raw(''' SELECT '1' as id, case when research_due < "2022-12-01" AND research_status != "done" then 1 else 0 end as count from app_task where taskid = "''' + taskidx + '''"''') However, when I want to swap the hard coded date for TODAY() I can't make it work. I have tried passing a python date variable into the script (td = datetime.date.today()), but it doesn't return the right results! Can anyone advise me please? -
APScheduler running multiple times for the amount of gunicorn workers
I have a django project with APScheduler built in it. I have proceeded to the production environment now so binded it with gunicorn and nginx in the proceess. Gunicorn has 3 workers. Problem is that gunicorn initiates the APScheduler for each worker and runs the scheduled job 3 times instead of running it for only once. I have seen similar questions here it seems it is a common problem. Even the APScheduler original documentation acknowledges the problem and tells no way of fixing it. https://apscheduler.readthedocs.io/en/stable/faq.html#how-do-i-share-a-single-job-store-among-one-or-more-worker-processes I saw in other threads people recommended putting --preconfig in the settings. But I read that --preconfig initiates the workers with the current code and does not reload when there has been a change in the code.(See "when not to preload" in below link) https://www.joelsleppy.com/blog/gunicorn-application-preloading/ I also saw someone recommended binding a TCP socket for the APScheduler. I did not understand it fully but basically it was trying to bind a socket each time APScheduler is initiated then the second and third worker hits that binded socket and throws a socketerror. Sort of try: "bind socket somehow" except socketerror: print("socket already exists")" else: "run apscheduler module" configuration. Does anyone know how to do it or … -
How to delete everything but the latest object in each group in Django
I want to group my model objects by three fields, and delete all objects but the youngest for each group. My model: class DataFile(models.Model): filename = models.CharField(unique=True, max_length=256) timestamp = models.DateTimeField() tile_label = models.CharField(max_length=256, blank=True) region = models.CharField(max_length=256, blank=True) resolution = models.CharField(max_length=256, blank=True) This query gives me the list of the values I want to keep: DataFile.objects.values('resolution', 'region', 'tile_label').annotate(maxfield=Max('timestamp')) The result of this is {'resolution': '30', 'region': 'SRC', 'tile_label': '10r_20d', 'maxfield': datetime.datetime(2021, 9, 11, 7, 13, tzinfo=<UTC>)} {'resolution': '30', 'region': 'NRC', 'tile_label': '10r_20d', 'maxfield': datetime.datetime(2021, 8, 16, 2, 8, tzinfo=<UTC>)} {'resolution': '30', 'region': 'NRC', 'tile_label': '100r_200d', 'maxfield': datetime.datetime(2021, 11, 15, 23, 5, tzinfo=<UTC>)} {'resolution': '300', 'region': 'SRC', 'tile_label': '10r_20d', 'maxfield': datetime.datetime(2021, 11, 1, 13, 46, tzinfo=<UTC>)} {'resolution': '300', 'region': 'NRC', 'tile_label': '10r_20d', 'maxfield': datetime.datetime(2021, 11, 5, 12, 20, tzinfo=<UTC>)} {'resolution': '300', 'region': 'NRC', 'tile_label': '100r_200d', 'maxfield': datetime.datetime(2021, 11, 18, 5, 54, tzinfo=<UTC>)} {'resolution': '30', 'region': 'SRC', 'tile_label': '100r_200d', 'maxfield': datetime.datetime(2021, 11, 5, 21, 8, tzinfo=<UTC>)} {'resolution': '300', 'region': 'SRC', 'tile_label': '100r_200d', 'maxfield': datetime.datetime(2021, 11, 18, 8, 29, tzinfo=<UTC>)} I now need to filter all DataFile objects except the one with the highest date in each group of resolution, region, tile_label, and then delete them (i.e. keep the one with the … -
Django Model with custom string id field not being deleted
I have a model with a custom string for an id. class BaseModel(Model): id = CharField( max_length=23, auto_created=True, primary_key=True, serialize=False, verbose_name="ID", default=generate, editable=False, ) When deleting, I am getting this error. Internal Server Error: /admin/sampleapp/user/ Traceback (most recent call last): File "path\to\sampleapp\venv\lib\site-packages\django\db\models\fields\__init__.py", line 1988, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: 'AC7EEKrEhYZ9p1r-Q' The above exception was the direct cause of the following exception: response = func(self, request, queryset) File "path\to\sampleapp\venv\lib\site-packages\django\contrib\admin\actions.py", line 39, in delete_selected ) = modeladmin.get_deleted_objects(queryset, request) File "path\to\sampleapp\venv\lib\site-packages\django\contrib\admin\options.py", line 2099, in get_deleted_objects return get_deleted_objects(objs, request, self.admin_site) File "path\to\sampleapp\venv\lib\site-packages\django\contrib\admin\utils.py", line 120, in get_deleted_objects collector.collect(objs) File "path\to\sampleapp\venv\lib\site-packages\django\contrib\admin\utils.py", line 186, in collect return super().collect(objs, source_attr=source_attr, **kwargs) File "path\to\sampleapp\venv\lib\site-packages\django\db\models\deletion.py", line 343, in collect field.remote_field.on_delete(self, field, sub_objs, self.using) File "path\to\sampleapp\venv\lib\site-packages\django\db\models\deletion.py", line 23, in CASCADE collector.collect( File "path\to\sampleapp\venv\lib\site-packages\django\contrib\admin\utils.py", line 186, in collect return super().collect(objs, source_attr=source_attr, **kwargs) File "path\to\sampleapp\venv\lib\site-packages\django\db\models\deletion.py", line 365, in collect sub_objs = field.bulk_related_objects(new_objs, self.using) File "path\to\sampleapp\venv\lib\site-packages\django\contrib\contenttypes\fields.py", line 524, in bulk_related_objects return self.remote_field.model._base_manager.db_manager(using).filter( File "path\to\sampleapp\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "path\to\sampleapp\venv\lib\site-packages\django\db\models\query.py", line 1071, in filter return self._filter_or_exclude(False, args, kwargs) File "path\to\sampleapp\venv\lib\site-packages\django\db\models\query.py", line 1089, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, args, kwargs) File "path\to\sampleapp\venv\lib\site-packages\django\db\models\query.py", line 1096, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) File "path\to\sampleapp\venv\lib\site-packages\django\db\models\sql\query.py", line 1502, in add_q clause, _ … -
How can I create a shortcut to go to a section on another page?
I have a book as an object and I am paginating its chapters, but, its chapters are OBJECTS, with chapter.number and chapter.story. I have a book summary with all the chapters’ numbers, but, thus summary should be a shortcut to the page, for example, book/chapter?page=5&#chapter_five. class ChapterView(DetailView): template_name = "tailwind/book_detail.html" model = Books slug_url_kwarg = "book_name" slug_field = "name" def get_object(self, queryset=None): try: return Books.objects.get(name=self.kwargs["book_name"]) except Books.DoesNotExist as e: raise Http404 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) tuple_book = self.get_object().ordered_chapter().items() book = [{"chapter_number": chapter_number, "chapter_resume": chapter_resume} for chapter_number, chapter_resume in tuple_book] page = self.request.GET.get("page", 1) paginator = Paginator(book, 2) try: paginated_book = paginator.page(page) except PageNotAnInteger: paginated_book = paginator.page(1) except EmptyPage: paginated_book = paginator.page(paginator.num_pages) # just get the current page # the book is not paginated because I need to return all indexes in the template for chapter in book.object_list: if self.request.GET.get("chapter_number", None) == "a": context["chapter_page"] = chapter["chapter_number"].get_page_number() context["book"] = book context["paginated_book"] = paginated_book return context Now, this is my template, this is the part where I am returning the paginated chapters. <div> <div> {% for chapter in paginated_changelogs %} <div> <div> <h2>{{ chapter.chapter_number }} </h2> <div> {{ chapter.chapter_resume }} </div> </div> </div> {% endfor %} </div> And this is my … -
Django ASGI deployment - question about Procfile and Daphne
I've made a simple chat room application in Django, using Daphne as a web server, Channel Layers with Redis, and SQLite as a database. Now I'm trying to deploy it to Heroku. The whole project's directory looks like this: ├───Chat Room Application └───chat_project | ├───chat | ├───chat_project | ├───room |---Dockerfile |---Procfile |---requirements.txt Sorry for the design, the tree command didn't print it the way I wanted. The Chat Room Application directory is where the git repo has been initialized and where the Procfile is supposed to be in. The outer chat_project directory was generated automatically, by Django. And the inner chat_project directory is where the settings.py and asgi.py files are. chat and room are the different Django apps. Since it is an ASGI application, I use the following command to run the web server: daphne chat_project.asgi:application So the Procfile looks like this: web: daphne chat_project.asgi:application My problem is that in my current configuration, the Procfile doesn't see the inner chat_project directory. So when I deploy it, using git push heroku main , I get: === web (Free): daphne chat_project.asgi:application (1) web.1: crashed 2022/11/15 22:12:24 +0200 (~ 6s ago) And when I look at the log, I see: ModuleNotFoundError: No module … -
How to allow requests with API KEY for client application in DJANGO without user login?
I am trying to have a global API KEY where it would be mandatory for the client application to send the API key in headers to get a successful response. I intend to keep my APIs secure and not expose so much information to all public URLs by using IsAuthenticatedOrReadOnly. Even after passing the API keys from the headers if someone tries to go and get it from the network it would be harmful so can anyone help me with the better approach on how we cab secure our API's Find Below more information about what I am trying to achieve. GET /products/ HEADERS - EMPTY RESPONSE - PLEASE PASS THE API KEY TO ACCESS THE APIS GET /products/ HEADERS - [API_KEY - SAMPLE] RESPONSE - [PRO1, PRO2, PRO3, PRO4] POST /products/ HEADERS - [API_KEY - SAMPLE] RESPONSE - PLEASE PROVIDE AUTHENTICATION CREDENTIALS -
Django 4.0.1 - Deleting Instance results in `TypeError: Model instances without primary key value are unhashable`
When deleting a model instance from the admin portal, it raises TypeError: Model instances without primary key value are unhashable. Models.py from django.db import models from djongo import models as MDB_models from django.core.validators import RegexValidator from simple_history.models import HistoricalRecords import datetime,json,uuid from django.contrib.auth.models import User from ..API import Model_Notifications from ..PublicPages import colours from django.apps import apps import sys,requests def leading_zero(value:int): return "{:02d}".format(value) def GetImage(ID): IMG_APP = apps.get_model("VehicleImages","Image") QS = IMG_APP.objects.filter(id=ID) if len(QS) == 0: return None else: return QS.first() class Status(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=150,default="",unique=True) icon = models.ImageField(blank=True,upload_to="StatusIcons") alternateText = models.TextField(max_length=500,default="") history = HistoricalRecords( history_id_field=models.UUIDField(default=uuid.uuid4), excluded_fields=["id"] ) last_modified_by = models.ForeignKey(User,null=True,blank=True,on_delete=models.SET_NULL,help_text="Set Automatically! DO NOT EDIT") def __str__(self): return self.name class VehicleChassis(models.Model): _id = MDB_models.ObjectIdField(auto_created=True, unique=True, primary_key=True) name = models.CharField(max_length=100,default="",unique=True) manufacturer = models.CharField(max_length=100,default="",blank=True) vehicle_class = models.CharField( max_length=30, default="", blank=True, choices=[ ("MINI BUS","Mini Bus"), ("MIDI BUS","Midi Bus"), ("SINGLE DECKER BUS","Single Decker Bus"), ("ARTICULATED SINGLE DECKER BUS","Articulated Single Decker Bus"), ("DOUBLE DECKER BUS","Double Decker Bus"), ("COACH","Coach"), ("INTERDECKER COACH","Interdecker Coach"), ]) history = HistoricalRecords( history_id_field=models.UUIDField(default=uuid.uuid4), excluded_fields=["_id"] ) last_modified_by = models.ForeignKey(User,null=True,blank=True,on_delete=models.SET_NULL,help_text="Set Automatically! DO NOT EDIT") def __str__(self): return self.name class VehicleModel(models.Model): _id = MDB_models.ObjectIdField(auto_created=True, unique=True, primary_key=True) name = models.CharField(max_length=100,default="",unique=True) manufacturer = models.CharField(max_length=100,default="") history = HistoricalRecords( history_id_field=models.UUIDField(default=uuid.uuid4), excluded_fields=["_id"] ) last_modified_by = models.ForeignKey(User,null=True,blank=True,on_delete=models.SET_NULL,help_text="Set Automatically! DO … -
Создание django-проекта
Не создается Django проект. Установил виртуальное окружение, Django (4.1.3), но при создании проекта выдает ошибку. Работаю на Macbook M1enter image description here Создавал несколько разных виртуальных окружений на разные версии Python, устанавливал разные версии Django -
Why Is Sub the Only Thing Returned in My Payload (Django pyjwt)?
So I recently just started django. I added some authentication for my backend. The issue is: when I decode my token, only the sub is returned. I'd like to know why. Here is my authentication.py file: from rest_framework.authentication import BasicAuthentication from rest_framework.exceptions import PermissionDenied from django.contrib.auth import get_user_model from django.conf import settings import jwt User = get_user_model() class JWTAuthentication(BasicAuthentication): def authenticate(self, request): header = request.headers.get('Authorization') if not header: return None if not header.startswith('Bearer'): raise PermissionDenied({'message': 'Invalid authorization header!'}) token = header.replace('Bearer', '') try: payload = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256']) user = User.objects.get(pk=payload.get('sub')) except jwt.exceptions.InvalidTokenError: raise PermissionDenied({'message':'Invalid token'}) except User.DoesNotExist: raise PermissionDenied({'message':'User not found'}) return (user, token) Here is my model: class CustomUser(AbstractUser): username = models.CharField(max_length=200, null=True, blank=True) first_name = models.CharField(max_length=240) last_name = models.CharField(max_length=240) email = models.EmailField(_('email address'), unique=True) bio = models.TextField(null=True, blank=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] -
Why my url appears as a post request when its get django
I have some templates in a django project. I'm trying to save them in the the url with a post request even though I specify it in the html document. Here's my views.py ` from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from .forms import WcaForm, IdForm from . import wcaScraper # Create your views here. def id(response): form = IdForm(response.GET) return render(response, "main/id.html", {"form": form}) def idresults(response): print(response.method) if response.method == "GET": print(wcaScraper.getDataByName(response.GET.get('name'))) return render(response, "main/nameresults.html", {"ids": wcaScraper.getDataByName(response.GET.get('name'))}) def search(response): form = WcaForm(response.GET) return render(response, "main/search.html", {"form": form}) def results(response): wcaData = wcaScraper.getDataById(response.GET.get('id')) variablePassed = { "id": response.GET.get('id'), "single3": wcaData[0].single, "avg3": wcaData[0].avg, "single2": wcaData[1].single, "avg2": wcaData[1].avg, "single4": wcaData[2].single, "avg4": wcaData[2].avg, "single5": wcaData[3].single, "avg5": wcaData[3].avg, "single6": wcaData[4].single, "avg6": wcaData[4].avg, "single7": wcaData[5].single, "avg7": wcaData[5].avg, "blind3single": wcaData[6].single, "blind3avg": wcaData[6].avg, "fmsingle": wcaData[7].single, "fmavg": wcaData[7].avg, "ohsingle": wcaData[8].single, "ohavg": wcaData[8].avg, "clocksingle": wcaData[9].single, "clockavg": wcaData[9].avg, "megasingle": wcaData[10].single, "megaavg": wcaData[10].avg, "pyrasingle": wcaData[11].single, "pyraavg": wcaData[11].avg, "skewbsingle": wcaData[12].single, "skewbavg": wcaData[12].avg, "squaresingle": wcaData[13].single, "squareavg": wcaData[13].avg, "blind4single": wcaData[14].single, "blind4avg": wcaData[14].avg, "blind5single": wcaData[15].single, "blind5avg": wcaData[15].avg, "multisingle": wcaData[16].single, "multiavg": wcaData[16].avg, } return render(response, "main/results.html", variablePassed) ` And my html template <html> <h1>Search by name</h1> <form method="get" action="/idresults"> {% csrf_token %} {{form}} <button type="submit">Search</button> </form> <p>or</p> <a href="id/"> Search by WCA Id</a> </html> … -
improperly configured at /18/delete, Django views issue
I have searched through the other questions similar to my own problem and have come to no solution so im hoping someone can help me figure out where i went wrong. I'm trying to implement a delete post option in my blog program but it is throwing the following error once you click the 'delete' button: ImproperlyConfigured at /18/delete/ Deletepost is missing a QuerySet. Define Deletepost.model, Deletepost.queryset, or override Deletepost.get_queryset(). I am nearly sure its a problem with my URLS.py though what exactly i cannot figure out. the following is the code in question: Views.py # delete post class Deletepost(LoginRequiredMixin, DeleteView): form_class = Post success_url = reverse_lazy('blog:home') template_name = 'templates/post.html' def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False urls.py urlpatterns = [ # home path('', views.postslist.as_view(), name='home'), # add post path('blog_post/', views.PostCreateView.as_view(), name='blog_post'), # posts/comments path('<slug:slug>/', views.postdetail.as_view(), name='post_detail'), # edit post path('<slug:slug>/edit/', views.Editpost.as_view(), name='edit_post'), # delete post path('<int:pk>/delete/', views.Deletepost.as_view(), name='delete_post'), # likes path('like/<slug:slug>', views.PostLike.as_view(), name='post_like'), ] post.html <a class="btn btn-outline-danger" href="{% url 'delete_post' post.id %}">Delete</a> Thanks for your time and i'm sorry for the trivial question but you guys are much smarter than me! -
When using django-allauth how do I get the Sites section in the admin page to show?
I'm new to Django and I'm trying to learn it from Django for Professionals by William Vincent. After installing django-allauth and following the steps in the book, I managed to get the logging in and out the sign up functionality to work. However, when I go to 127.0.0.1:8000/admin, I don't see a Sites section. This section is later used in the book to change the site being referred to (example.com) in the registration confirmation email. I've searched for django-allauth Site admin in here and in the docs but I couldn't find anything about making the Sites section show. -
How can I use Transaction rollback with Multiple forms in Django
I have four forms and I need them to be saved one by one however when any one form yields validation error then I need the data saved in the database to be removed. I understand the transaction rollback with Django query but not able to figure out that how would I will do the same with forms. with transaction.atomic(): # to store errors from the forms if any errors = [] # FormSubmitter are the function to submit the forms or provide the errors. cartoon_image_form_submitter = CartoonImageFormSubmitter( data=cartoon, request=request, form_model_keys=CartoonImage_form_model_keys, ) if ('errors' in cartoon_image_form_submitter and cartoon_image_form_submitter['errors'] is not None): errors.append(cartoon_image_form_submitter["errors"]) swimming_level_master_form_submitter = SwimmingLevelMasterFormSubmitter( data=swimming_level_master, form_model_keys=SwimmingLevelMaster_form_model_keys, ) if ('errors' in swimming_level_master_form_submitter and swimming_level_master_form_submitter['errors'] is not None): errors.append(swimming_level_master_form_submitter["errors"]) stages_summary_form_submitter = StagesSummaryFormSubmitter( data=stages_summary, form_model_keys=StagesSummary_form_model_keys, ) if ('errors' in stages_summary_form_submitter and stages_summary_form_submitter['errors'] is not None): errors.append(stages_summary_form_submitter["errors"]) lesson_level_detail_form_submitter = LessonLevelDetailFormSubmitter( data=lesson_level_details, form_model_keys=LessonLevelDetail_form_model_keys, ) if ('errors' in lesson_level_detail_form_submitter and lesson_level_detail_form_submitter['errors'] is not None): errors.append(lesson_level_detail_form_submitter["errors"]) if errors: errors = '<br>'.join([str(elem) for elem in errors]) from django.utils.safestring import mark_safe errors = mark_safe(errors) messages.error(request, errors) return HttpResponseRedirect('../levels/new') return HttpResponseRedirect('../levels/new') I tried with transaction.atomic(): and thought it will work because forms also saves data in db -
Implemented google login using server side flow how can i do for LinkedIn for Django REST Framework and React?
Hi i have Successfully implemented server side google login But i can't find proper implementation for server side login for LikendIn I am using Django Rest framework for bckend and React as front-end i have followed this blog: https://www.hacksoft.io/blog/google-oauth2-with-django-react-part-2 any specific blog or implementation ?