Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Seeking Guidance on Migrating Django Project to Golang and Finding Equivalent to reversion Library
We are currently migrating a project from Python (Django) to Golang (Gin). In our application, we use the reversion library. Is there an equivalent in Golang? If not, how can we implement the migration of this functionality in Golang? Perhaps someone has encountered this and can give me advice. @reversion.register() class DocumentRecommendationMedia(models.Model): document = models.ForeignKey("Document.Document", on_delete=models.CASCADE) file = models.FileField(upload_to=settings.DOCUMENT_RECOMMENDATION_PATH) file_name = models.CharField(max_length=100) class Meta: db_table = "document_recommendation_media" @reversion.register(fields=("recommendation", "date", "media_files")) class DocumentRecommendation(ArchivableModel): document = models.ForeignKey("Document.Document", on_delete=models.CASCADE) recommendation = models.TextField(null=True, blank=True) date = models.DateTimeField(default=timezone.now) media_files = models.ManyToManyField(DocumentRecommendationMedia, blank=True) class Meta: db_table = "document_recommendation" I am seeking possible implementation options for reversion in Golang. -
Get object by id of OneToOne related object in DRF
I have Progress model wich relates with Deck model by OneToOne relation. I want to get Progress object from API by passing deck_id to 'http://localhost/api/v1/progress/deck_id/' endpoint. How I can do this? Or may be should I consider other implementations of retrieving Progress object? Also I want all CRUD functions with this model. class Deck(models.Model): name = models.CharField(max_length=70) owner = models.ForeignKey( CustomUser, on_delete=models.CASCADE, related_name='decks', ) class Progress(models.Model): deck = models.OneToOneField(Deck) progress = models.JSONField( null=True ) class ProgressViewSet(viewsets.ModelViewSet): queryset = Progress.objects.all() serializer_class = ProgressSerializer permission_classes = (OwnerOrAdminProgress,) lookup_field = 'id' http_method_names = ['get', 'post', 'patch', 'delete'] class ProgressSerializer(serializers.ModelSerializer): progress = serializers.JSONField() class Meta: model = Progress fields = ('id', 'deck', 'progress') router_v1 = routers.DefaultRouter() router_v1.register('v1/decks', DeckViewSet, basename='decks') router_v1.register('v1/progress', ProgressViewSet, basename='progress') urlpatterns = [ path('', include(router_v1.urls)), ] -
attribute error in Django while making a urls.py file under my app
while i'm trying to create my first project and my first app i'm getting this error: of course when i removed the url of my app view.py it works perfectly (the home screen) .... File "C:\Users\pegasus\barakcapitalcom\buildtradeapp\urls.py", line 5, in <module> path('buildtradeapp/', views.index, name='index') ^^^^^^^^^^^ AttributeError: module 'buildtradeapp.views' has no attribute 'index' this is my app urls.py: from django.urls import path from . import views urlpatterns = [ path('buildtradeapp/', views.index, name='index') ] this is my app views.py: from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("Hello world!") this is my main project urls.py: from django.contrib import admin from django.urls import path, include from buildtradeapp import views urlpatterns = [ path('buildtradeapp/', include('buildtradeapp.urls')), path('admin/', admin.site.urls), ] what did i do wrong? i'm trying to create my first app and first project, printing hello world using django -
Passing Django Usernames to Streamlit
I'm working on a project using Django for user authentication and Streamlit for the front end. I'm struggling to fetch the authenticated user's information from Django and pass it to my Streamlit app. How can I efficiently retrieve user data from Django and securely transfer it to Streamlit? Any guidance or code examples for this integration would be appreciated. Thanks! Attempted to establish communication between Django and Streamlit by creating an endpoint in Django to fetch user information. I expected to retrieve the authenticated user's data from Django and then use an HTTP request in Streamlit to fetch this data from the Django endpoint. However, I encountered difficulties in properly implementing this communication and handling the data transfer securely between the two platforms. Also Tried to Use Javascript To Fetch On Screen Infomration -
getting values from the url
url: urlpatterns = [ path('', views.ProductListView.as_view(), name='product-list'), path('cat/<cat>/',views.ProductListView.as_view(),name='product-categories-list'), path('cat/<cat>/tag/<tag>/', views.ProductListView.as_view(), name='product-tag-list'), # path('<str:slug>', views.ProductDetailView.as_view(), name='product-detail'), ] views: def Product_tags_component(request:HttpRequest): category_name = request.GET.get('cat) product_tags = ProductTag.objects.filter(category__url_title__iexact=category_name,is_active=True) context = { 'product_tags':product_tags } return render(request,'product_module/components/Product_tags_component.html',context) I need to get the value of the cat through the url, I used request.GET.get('cat) and none is returned. I printed the request.GET command and returned <QueryDict: {}>. I gave the value of cat to the function like this def Product_tags_component(request:HttpRequest,cat) He said this: Product_tags_component() missing 1 required positional argument: 'cat' How can I get the values through the url, there shouldn't be any problem, thank you very much for your help. by the way i'm using the function with render_partial for another classview -
How can I avoid this Numpy ArrayMemoryError when using scikit-learn's DictVectorizer on my data?
I'm getting a numpy.core._exceptions._ArrayMemoryError when I try to use scikit-learn's DictVectorizer on my data. I'm using Python 3.9 in PyCharm on Windows 10, and my system has 64 GB of RAM. I'm pre-processing text data for training a Keras POS-tagger. The data starts in this format, with lists of tokens for each sentence: sentences = [['Eorum', 'fines', 'Nervii', 'attingebant'], ['ait', 'enim'], ['scriptum', 'est', 'enim', 'in', 'lege', 'Mosi'], ...] I then use the following function to extract useful features from the dataset: def get_word_features(words, word_index): """Return a dictionary of important word features for an individual word in the context of its sentence""" word = words[word_index] return { 'word': word, 'sent_len': len(words), 'word_len': len(word), 'first_word': word_index == 0, 'last_word': word_index == len(words) - 1, 'start_letter': word[0], 'start_letters-2': word[:2], 'start_letters-3': word[:3], 'end_letter': word[-1], 'end_letters-2': word[-2:], 'end_letters-3': word[-3:], 'previous_word': '' if word_index == 0 else words[word_index - 1], 'following_word': '' if word_index == len(words) - 1 else words[word_index + 1] } word_dicts = list() for sentence in sentences: for index, token in enumerate(sentence): word_dicts.append(get_word_features(sentence, index)) In this format the data isn't very large. It seems to only be about 3.3 MB. Next I setup DictVectorizer, fit it to the data, and try to transform … -
my site is showing me integrity error something regarding POST
[[enter image description here](https://i.stack.imgur.com/aICfo.png)](https://i.stack.imgur.com/5Kday.png) i am facing this error and i am currently new to django and don't know how to overcome it i have pasted the error page and the page of my contact form i wanted to save the information that i get by filling the form to be saved in my data base/admin -
How to really completely completely remove pgadmin4 web version from ubuntu (nothing works)
I have tried this: sudo apt -y remove pgadmin4 sudo apt -y autoremove pgadmin4* It does not work I have tried this: pip3 uninstall pgadmin4 it does not work while it says "successfully removed" it is not! The problem is that I have forgotten the password so uninstalling and installing does not help because it does not give me a chance to reenter the new data: So I have gone to env/lib/python3.10/site-packages/pgadmin4/config_local.py LOG_FILE = '/var/log/pgadmin4/pgadmin4.log' SQLITE_PATH = '/var/lib/pgadmin4/pgadmin4.db' SESSION_DB_PATH = '/var/lib/pgadmin4/sessions' STORAGE_DIR = '/var/lib/pgadmin4/storage' SERVER_MODE = True and removed the stored sessions, the config_loca.py file and still does not work because when I run this: python3 venv/lib/python3.10/site-packages/pgadmin4/setup.py it does not pop me up to enter email and password like the first time I installed it but it just reads: pgadmin4 application initialisation I am going insane about it. I cannot use the reset password because I still don't have the SMTP mail thing installed on my web. -
Want to use Django as a full stack framework for my to-do web application project
I want to make a to-do web application project using only Django for both frontend and backend,suggest me how to do it , I'm beginner student. I want to do it using only Django beacusecurrently I'm learning python so this project will help me to learn things more accurately about Django and backend also frontend . -
Authentication issue when sending emails with Gmail API in Django using Django Rest Framework
class SendEmailView(APIView): serializer_class=SendEmailSerializer permission_classes = [IsAuthenticated] def post(self, request): user = request.user if not user.gmail_credentials: return Response({"error": "Gmail not linked"}, status=status.HTTP_400_BAD_REQUEST) creds = Credentials.from_authorized_user_info(json.loads(user.gmail_credentials)) if creds.expired: creds.refresh(Request()) service = build('gmail', 'v1', credentials=creds) to_email = request.data.get("to") subject = request.data.get("subject") message_text = request.data.get("message") if not all([to_email, subject, message_text]): return Response({"error": "Missing fields"}, status=status.HTTP_400_BAD_REQUEST) try: message = MIMEText(message_text) message['to'] = to_email message['from'] = user.email # Replace with your sender address message['subject'] = subject raw_message = base64.urlsafe_b64encode(message.as_string().encode("utf-8")).decode("utf-8") message_body = {'raw': raw_message} sent_message = service.users().messages().send(userId='me', body=message_body).execute() return Response({"message_id": sent_message['id']}, status=status.HTTP_200_OK) except Exception as e: return Response({"error": str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) { "error": { "code": 401, "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.", "errors": [ { "message": "Login Required.", "domain": "global", "reason": "required", "location": "Authorization", "locationType": "header" } ], "status": "UNAUTHENTICATED", "details": [ { "@type": "type.googleapis.com/google.rpc.ErrorInfo", "reason": "CREDENTIALS_MISSING", "domain": "googleapis.com", "metadata": { "method": "caribou.api.proto.MailboxService.GetMessage", "service": "gmail.googleapis.com" } } ] } } im trying to send the email thrugh django, but i keep getting the same error. -
How to create and add items on manytomanyfields instance in django
Here in this code I have Order model with OrderStatus and i want to create OrderStatus instance when Order is created. The OrderStatus is being created when Order is created but its not being added to the manytomanyfields of Order models *This code is not working instance.order_status.add(status_instance)* Can anyone help me? class Order(RandomIDModel): order_status = models.ManyToManyField(OrderStatus,blank=True) @receiver(m2m_changed, sender = Order.carts.through) def order_carts_changed(sender, instance, action, **kwargs): if action == 'post_add': # Accessing individual carts for cart in instance.carts.all(): status_instance = OrderStatus.objects.create(Details='Pending',price=cart.price, quantity=cart.quantity, Product=cart.Product, buyer=instance.user, seller=cart.Product.user) print("hello") instance.save() instance.order_status.add(status_instance) instance. Save() I tried this too instance.save() instance_add = OrderStatus.objects.get(id=status_instance.id) instance.order_status.add(instance_add) -
Deploy React app in vercel with backend in render
Hi Everyone! Happy New Year I was trying to deploy my vite react application in vercel or netlify. I hosted it's backend part in render, Now backend is working, but when i hosted in frontend, the request URL change to hosted URL because I used vite proxy to use shortcut URL but it's not working in devlopment, Example of my vite cconfig // https://vitejs.dev/config/ export default defineConfig({ plugins: [ VitePWA(manifestForPlugin), react(), ], server: { proxy: { "/api": { target: "https://sample__.onrender.com", changeOrigin: true, secure: false, rewrite: (path) => path.replace("/api", ""), }, }, }, build: { proxy: { "/api": { target: "https://sample__.onrender.com/", changeOrigin: true, secure: false, rewrite: (path) => path.replace("/api", ""), } } } }); so when i call api my url is like: api/auth/login/ so in localhost, it will became, localhost:8000/auth/login/ but when i did it from dev server of netlify or vercel it become like vercel/netlify url/api/auth/login/ In localhost my backend is runnning in 8000 and frontend is runningin 5173 -
Django value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.']
i have a Django proj,I want to press button and date time save to db but error ,help please! view.py def confirm_order(request, pk): get_emp = get_object_or_404(Employee, pk=pk) if request.method == 'POST': new_end_date = request.POST['new_date'] get_emp.end_date = new_end_date get_emp.save() return redirect('all_emp') else: context = { 'get_emp': get_emp, } return render(request, 'confirm_order.html', context) ValidationError at /confirm_order/5/ ['“Feb. 29, 2023, 3:48 p.m.” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.'] Request Method: POST Request URL: http://127.0.0.1:8001/confirm_order/5/ Django Version: 4.2.1 Exception Type: ValidationError Exception Value: ['“Feb. 29, 2023, 3:48 p.m.” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.'] Exception Location: /home/gino/PycharmProjects/office_emp_proj/venv/lib/python3.10/site-packages/django/db/models/fields/__init__.py, line 1567, in to_python Raised during: emp_app.views.confirm_order Python Executable: /home/gino/PycharmProjects/office_emp_proj/venv/bin/python Python Version: 3.10.12 Python Path: ['/home/gino/PycharmProjects/office_emp_proj', '/home/gino/PycharmProjects/office_emp_proj', '/snap/pycharm-professional/364/plugins/python/helpers/pycharm_display', '/usr/lib/python310.zip', '/usr/lib/python3.10', '/usr/lib/python3.10/lib-dynload', '/home/gino/PycharmProjects/office_emp_proj/venv/lib/python3.10/site-packages', '/usr/local/lib/python3.10/dist-packages', '/usr/lib/python3/dist-packages', '/snap/pycharm-professional/364/plugins/python/helpers/pycharm_matplotlib_backend'] Server time: Mon, 01 Jan 2024 09:10:25 +0800 error_image ,how to resolve,Thanks i have a Django proj,I want to press button and date time save to db but error ,help please! -
How to deploy a remote production server using Jenkins?
We currently have our Dev server and Jenkins server on the same Cloud instance1. OS user: djDev Jenkins install owner: jenkins We are able to deploy our Django application build on this same instance1 using Jenkins and application is accessible fine but the files are deployed in /var/lib/jenkins folder. This is because Jenkins configuration is pointing to /var/lib/jenkins Is this possible to deploy the application in OS user folder, like /home/djDev/djApp While we try to modify the above folders and keep this instance1 for both Dev and Jenkins server, we need to deploy a production server on a remote cloud instance2 and deploy the application in a desired OS user´s using the same Jenkins server. (ex: user: djProd and /home/djProd/djApp) Our plan is to deploy the Production server as soon as automated tests are passed on Dev. server. Our repository is in Github. Please let me if there is any recommended steps to achieve the above deployment especially for Django application and also when users are different on each instance? Best Regards -
My React app isn't rendering the page right, it just shows a blank page
I'm following a YouTube video tutorial. I have the Django API setup and working. But I ran into an issue with the React frontend I can't figure out. React is rendering a blank white page when I run "npm start". Here's my Header.js: import React from 'react'; import AppBar from '@material-ui/core/AppBar'; import Toolbar from '@material-ui/core/Toolbar'; import Typography from '@material-ui/core/Typography'; import CssBaseline from '@material-ui/core/CssBaseline'; import { makeStyles } from '@material-ui/core/styles'; const useStyles = makeStyles((theme) => ({ appBar: { borderBottom: `1px solid ${theme.palette.divider}`, }, })); function Header() { const classes = useStyles(); return ( <React.Fragment> <CssBaseline /> <AppBar position="static" color="white" elevation={0} className={classes.appBar} > <Toolbar> <Typography variant="h6" color="inherit" noWrap> BlogmeUp </Typography> </Toolbar> </AppBar> </React.Fragment> ); } export default Header; Here's my App.js: import logo from './logo.svg'; import './App.css'; function App() { return ( <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <p> Edit <code>src/App.js</code> and save to reload. </p> <a className="App-link" href="https://reactjs.org" target="_blank" rel="noopener noreferrer" > Learn React </a> </header> </div> ); } export default App; And here's my index.js: import React from 'react'; import ReactDOM from 'react-dom'; import * as serviceWorker from './serviceWorker'; import './index.css'; import { Route, BrowserRouter as Router, Switch } from 'react-router-dom'; // import { Route, BrowserRouter as … -
Django admin panel css not showing
Django css files not loading in admin panel I created a new project pro-a And I start a new app core Than I migrate and made superuser And open localhost:8000/admin Everything is ok I didn't change or update anything enter image description here Admin panel I also reinstall django -
Is there a way to define multiple actions in django model admin, without specifying their number?
i have 3 models: Team, TeamDetail and Sheet. in SheetModelAdmin, I want to have as many actions as my teams. And it is not known how many teams I will have. Is there a way to solve this? The following code only adds the first team actions = list() teams = Team.objects.filter() if teams: for team in teams: actions.append('add_team_to_attendance') @admin.action(description=f"Add team {team.name} to selected attendance") def add_team_to_attendance(self, request, queryset, team=team): team_details = TeamDetail.objects.filter(team=team) for td in team_details: for query in queryset: AttendanceDetail.objects.create(attendane=query, player=td.player) -
Django 5 and Python 3.12.1 send_mail fails with SSL error
I have a working application using Django 3.2.6 and Python 3.9.6. I'm trying to upgrade to Django 5 and Python 3.12.1. So far, I've managed to track down and fix a number of problems caused by various changes and deprecations but this one has had me stumped for several days. Using Django send_mail() in the new environment fails with ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: IP address mismatch, certificate is not valid for '40.99.213.34'. (_ssl.c:1000). Here's a code extract: settings.py EMAIL_HOST = socket.gethostbyname('smtp.office365.com') # resolves IPV4 address EMAIL_PORT = 587 EMAIL_HOST_USER = 'name@company.co.uk' EMAIL_HOST_PASSWORD = 'password' EMAIL_USE_TLS = True views.py send_mail('Subject','Message Body','name@company.co.uk',['name@gmail.com']) If I add the following line to my settings (gleaned from SO after hours of searching), the error changes to something even less helpful: [SSL] PEM Lib (_ssl.c:3917) import certifi EMAIL_SSL_CERTFILE = certifi.where() It seems clear that something has changed in the way ssl connects, maybe it's insisting on verifying certs in a different way than it did in Python 3.9.6. I've spent many hours fruitlessly searching for a solution. I've looked at the source for the django smtp module and the python ssl module and in desperation even the cpython _ssl module, but I can't figure out … -
Issue in email login with customUser in Django rest framework
i'm working on a school projet , and i basically have an issue with the login i canot make it work no matter how many overrding im doing it always show me that my query doesnt match any existing user ( whe its the correct email/password combination ) custom user model : class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_("email address"), unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(auto_now_add=True) is_company = models.BooleanField(blank=True,null=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email custom email backend: class EmailBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): try: user = UserModel.objects.get(Q(email__iexact=username)) except UserModel.DoesNotExist: UserModel().set_password(password) except MultipleObjectsReturned: return CustomUser.objects.filter(email=username).order_by('id').first() else: if user.check_password(password) and self.user_can_authenticate(user): return user def get_user(self, user_id): try: user = UserModel.objects.get(pk=user_id) except UserModel.DoesNotExist: return None return user if self.user_can_authenticate(user) else None login view class LoginAPIView(APIView): def post(self,request): serializer = LoginSerializer(data = request.data) if serializer.is_valid(): email = serializer.validated_data["email"] password = serializer.validated_data["password"] user = authenticate(request, username=email, password=password) if user is not None: #We are reterving the token for authenticated user. token = Token.objects.get(user=user) response = { "status": status.HTTP_200_OK, "message": "success", "data": { "Token" : token.key } } return Response(response, status = status.HTTP_200_OK) else : response = { "status": status.HTTP_401_UNAUTHORIZED, "message": "Invalid Email … -
Python Django - Not able to download video completely in the client's machine using FileResponse
I'm building a video downloader using Django. I have the url from where the video is played. Inside the download view, first, I'm sending a request using requests library to that url with stream=True and storing the response in a res variable. And finally, I'm returning the a FileResponse with the res and 'Content-Disposition' = 'attachment; filename="downloaded_video.mp4"' and with content length. def download(request): url = "https://rr-rkf.com/lkdlfj8eijkjjoifu99ooijLKJr8goijoijrg0j94" res = requests.get(url, stream=True) content_length = res.headers.get('Content-Length') content_type = 'video/mp4' file_response = FileResponse(res, content_type = content_type) file_response['Content-Disposition'] = 'attachment; filename="download_video.mp4"' file_response['Content-Length'] = content_length url_patterns url_patterns = [ path('/download', views.download, name='download') ] When I go \download, the video started downloading and struck after downloading some bytes. In the browser it shows resuming for long time but there is no progress. But in the terminal, I got this error Traceback (most recent call last): File "C:\Users\USER\OneDrive\Documents\DownloaderWebDjango\env\Lib\site-packages\urllib3\response.py", line 712, in _error_catcher yield File "C:\Users\USER\OneDrive\Documents\DownloaderWebDjango\env\Lib\site-packages\urllib3\response.py", line 833, in _raw_read raise IncompleteRead(self._fp_bytes_read, self.length_remaining) urllib3.exceptions.IncompleteRead: IncompleteRead(212992 bytes read, 614518 more expected) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\USER\OneDrive\Documents\DownloaderWebDjango\env\Lib\site-packages\requests\models.py", line 816, in generate yield from self.raw.stream(chunk_size, decode_content=True) File "C:\Users\USER\OneDrive\Documents\DownloaderWebDjango\env\Lib\site-packages\urllib3\response.py", line 934, in stream data = self.read(amt=amt, decode_content=decode_content) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\USER\OneDrive\Documents\DownloaderWebDjango\env\Lib\site-packages\urllib3\response.py", … -
Unsaved model instances to related filters in tests for django 5.0
In Django 5 "passing unsaved model instances to related filters is no longer allowed" (https://docs.djangoproject.com/en/5.0/releases/5.0/). Basically before I had this method (only relevant code shown): def make_payload(user, nonce, exclude_groups=None): exclude_groups = set(exclude_groups or []) relevant_groups = Group.objects.filter(internal_only=False).order_by("internal_name") filter_q = Q(user=user) & ~Q(pk__in=exclude_groups) add_groups = relevant_groups.filter(filter_q).values_list("internal_name", flat=True) ... And tested it using this test method (only relevant code shown): def test_builds_payload_not_activated(self): user = accounts.tests.factories.UserFactory.build(email_verified=False) payload = utils.make_payload(user, "nonce-nce") ... Now obviously the instance as not been saved as it's a unit and not an integration test. This leads to relevant_groups.filter(filter_q) failing with ValueError: Model instances passed to related filters must be saved. Basically I've no idea how to fix the test as the code is still working in a real environment. Ideas welcome. -
Django MultiSelectField Error: 'super' object has no attribute '_get_flatchoices'
I tried to use Django Multiselectfield library but i got this error: I already installed it properly by command: pip install django-multiselectfield I also added in my settings.py INSTALLED_APPS = [ ..... 'multiselectfield', ] My models.py: from multiselectfield import MultiSelectField from django.db import models CATEGORY = [ ('CP', 'Computer Programming'), ('LG', 'Language'), ('MA', 'Mathematics'), ('BM', 'Business Management'), ('GK', 'General Knowledge') ] class Quiz(models.Model): ... title = models.CharField(max_length=256) category = MultiSelectField(choices=CATEGORY, max_choices=2, max_length=5) ... def save(self, *args, **kwargs): if not self.category: self.category = ['GK'] super(Quiz, self).save(*args, **kwargs) def __str__(self): return self.title The error: 'super' object has no attribute '_get_flatchoices' However this is located in the Multiselectfield library code. Because of this error, even my data cannot be saved. I tried to find out what am I missing, but I have no idea. Any idea what's wrong with my code? Appreciate your help ^_^ -
Integrate webpack template with Django
I'm working on a Django project, and I'm trying to integrate an HTML template built with npm using webpack into the Django project. I'm curious about the necessity of these {% static %} tags in the HTML templates. Issue: When visiting a URL like /view/user, static files are being loaded from /view/user instead of the expected /static. This happens because I am not adding the {% static %} template tag in the html templates. Question: Is there is a Django setting in order to avoid adding the {% static %} template tag to each line and save time? Has anyone encountered this problem before? settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'events_core/frontend/dist')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'events_core/frontend/dist'), ] -
I get the following error while registrating: "The view account_module.views.view didn't return an HttpResponse object. It returned None instead"
I used HttpResponseRedirect and redirect but didn't work: your text class RegisterView(View): def get(self, request): registration_form = RegisterForm() context = {"registration_form": registration_form} return render(request, "account_module/registration.html", context) def post(self, request): registration_form = RegisterForm(request.POST) if registration_form.is_valid(): user_email = registration_form.cleaned_data.get("email") user = User.objects.filter(email__iexact=user_email).exists() if user: registration_form.add_error("email", "This email is already taken") else: new_user = registration_form.save(commit=False) new_user.is_active = False new_user.save() # Todo send_email return redirect(reverse("login")) # return HttpResponseRedirect(reverse_lazy("login")) context = {"registration_form": registration_form} return render(request, "account_module/registration.html", context) this is urls.py: your text from django.urls import path from . import views urlpatterns = [ path("registration/", views.RegisterView.as_view(), name="register"), path("login/", views.LoginView.as_view(), name="login"), ] -
Why am I having a key error on my target column and a value error that says; A given column is not a column of the dataframe
# firstly, I split my data target = 'member_casual' X_train = train.drop(target, axis=1) y_train = train[target] # Then, transformed my numerical and categorical columns cat_trans = Pipeline([("imputer", SimpleImputer(strategy="most_frequent")),('encoder',OneHotEncoder(handle_unknown="ignore", drop="first", sparse=False))]) num_trans = Pipeline([("imputer", SimpleImputer(strategy="mean")),("scaler", MinMaxScaler())]) preprocessor = ColumnTransformer(transformers=[('num', num_trans, num),('cat', cat_trans, cat)]) pipeline = Pipeline([('preprocessor', preprocessor)]) # then this next code gave me errors pipe_fit = pipeline.fit(x_train) A key error and value error: A given column is not a column of the dataframe