Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
My sqlite3 database does not creates new post when its deployed in heroku [duplicate]
I have created a site for posting blogs and sites . Here is the link . But the point is after I have created it and hosted it. And when I am creating new posts in the deployed site. The posts disappear after some time and the posts which I have deleted again get showing up . I want to know why this happens and how can I overcome the situation and make the site working . I am beginner in django . Any kind of suggestion will be very helpful and it will help me a lot . Also the new users which were created after the deployment of the site also were deleted or disappeared and the posts created by the new users were deleted . Kindle help me . Any thing which you want I will provide all the things here . This is the github repository for the site Github link -
Multiple languages on individual fields for ElasticSearch
I've got a django app and am using django_elasticsearch_dsl_drf for managing the documents for Elasticsearch (7.1) and handling multiple languages through django-parler. I've got a bunch of documents and some fields have multiple languages. I thought I'd deal with this like so: topic = fields.ObjectField(properties={ 'id': fields.IntegerField(attr='id'), 'name': StringField( analyzer=html_strip, fields={ 'raw': StringField(analyzer='keyword'), 'suggest': fields.CompletionField() } ), 'about': fields.ObjectField(properties={ 'en': StringField( analyzer=html_strip_english, fields={ 'raw': StringField(analyzer="keyword") }), 'es': StringField( analyzer=html_strip_english, fields={ 'raw': StringField(analyzer="keyword") }) }) }) This is HTML text in a particular language. The problem is en doesn't exist so I thought the best way to do this is use prepare_en etc: def prepare_en(self, instance): // query to get the en for that instance However this throws an error VariableLookupError: Failed lookup for key [en] and this doesn't really solve the issue where there is multiple fields that have a translation, I can't really see the difference between about in this case name (if it was translated). How do I go about prepare for a nested field like this and if there is a way, how do I go about differentiating between the two fields? Or is there a better way to do this? This is a related_models definition rather … -
connection to server at "localhost" (::1), port 5432 failed:
connection to server at "localhost" (::1), port 5432 failed: Connection refused (0x0000274D/10061) Is the server running on that host and accepting TCP/IP connections? connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused (0x0000274D/10061) Is the server running on that host and accepting TCP/IP connections? not to connect server and password is right but not to accept and connection lost? please answer and give your suggestion. -
Trying to customize the error messages with serializers.EmailField() in Django
I want to customize the validation error messages with an additional key "message". I try to add a new dict to the EmailField. But When I check the response with Postman, I have got only a key. Is there any idea how to figure this out to prompt the result as below? { 'email':{ 'message':'Enter a valid email address.' } } -
TypeError: ModelSerializer.create() got an unexpected keyword argument 'image'
models.py file class Product(models.Model): """ This is The Product table contining all product items. """ name = models.CharField(max_length=255) title = models.CharField(max_length=255) slug = models.SlugField(max_length=255, unique=True) brand = models.ForeignKey(to='brands.BrandProfile', on_delete=models.DO_NOTHING, related_name='brand_product') # brand=models.CharField(max_length=30) category = models.ForeignKey( to='products.Category', on_delete=models.DO_NOTHING) # sizes = ArrayField( # models.CharField(max_length=10), # ) # colors = ArrayField( # models.CharField(max_length=56) # ) is_available = models.BooleanField(default=True) market_price = models.IntegerField() selling_price = models.IntegerField() description = models.TextField() # stock_status , visibility_status # product won't delete if category deleted, we have to do it manually. visiblity = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True, editable=False) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ('-created_at',) verbose_name = "Product" verbose_name_plural = "Products" def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(str(self.name.lower()) + str(uuid.uuid4())) return super().save(*args, **kwargs) def __str__(self): return str(self.title) @property def discount_percent(self): if self.selling_price: discount_percent = 100 - \ (self.selling_price * 100) / self.market_price return int(discount_percent) return 0 class ProductImage(models.Model): """ The Product Image Table """ product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name='product_images') image = models.ImageField( upload_to=brand_product_image_file_path, blank=False, null=False) product_color = models.CharField(max_length=56) alt_text = models.CharField(max_length=24) is_featured = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True, editable=False) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name = "Product Image" verbose_name_plural = "Product Images" def __str__(self): return str(self.alt_text) serializers.py file class ProductImageSerializer(serializers.ModelSerializer): # product=serializers.SerializerMethodField(required=False) class Meta: model … -
How to handle BadNameSpaceError in Socketio?
I am seeing this issue after creating my server using django. I want to understand why this happened and how can i resolve this issue? wsgi.py import os import socketio import eventlet import eventlet.wsgi from django.core.wsgi import get_wsgi_application from django.contrib.staticfiles.handlers import StaticFilesHandler from sioapp.views import sio application = get_wsgi_application() os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ESIProject.settings') django_app = StaticFilesHandler(application) application = socketio.Middleware(sio, wsgi_app=django_app, socketio_path='socket.io') eventlet.wsgi.server(eventlet.listen(('0.0.0.0', 5100)), application) Django socketio server Error: gunicorn ESIProject.wsgi:application -b 0.0.0.0:8080 [2022-02-08 00:28:48 -0500] [27642] [INFO] Starting gunicorn 20.1.0 [2022-02-08 00:28:48 -0500] [27642] [INFO] Listening at: http://0.0.0.0:8080 (27642) [2022-02-08 00:28:48 -0500] [27642] [INFO] Using worker: sync [2022-02-08 00:28:48 -0500] [27643] [INFO] Booting worker with pid: 27643 (27643) wsgi starting up on http://0.0.0.0:5100 (27643) accepted ('76.65.195.88', 24604) 76.65.195.88 - - [08/Feb/2022 05:28:55] "GET /socket.io/?transport=polling&EIO=4&t=1644298135.4189525 HTTP/1.1" 200 278 0.000718 (27643) accepted ('76.65.195.88', 56916) [INFO] Connect to client y5sIMdDrSe1G_3AgAAAB [2022-02-08 00:29:18 -0500] [27642] [CRITICAL] WORKER TIMEOUT (pid:27643) wsgi exiting disconnect y5sIMdDrSe1G_3AgAAAB 76.65.195.88 - - [08/Feb/2022 05:29:18] "GET /socket.io/?transport=websocket&EIO=4&sid=r4dC0S8vf0a09AXxAAAA&t=1644298135.7191956 HTTP/1.1" 200 0 22.338442 (27643) wsgi exited, is_accepting=True [2022-02-08 05:29:18 +0000] [27643] [INFO] Worker exiting (pid: 27643) [2022-02-08 00:29:18 -0500] [28218] [INFO] Booting worker with pid: 28218 (28218) wsgi starting up on http://0.0.0.0:5100 (28218) accepted ('76.65.195.88', 35122) 76.65.195.88 - - [08/Feb/2022 05:29:26] "GET /socket.io/?transport=polling&EIO=4&t=1644298166.7089198 HTTP/1.1" 200 … -
Modify django simple captcha
I'm using django-simple-captcha and crispy form Here is my code: forms.py from django import forms from captcha.fields import CaptchaField class ContactEntryForm(forms.Form): name = forms.CharField( label="", widget=forms.TextInput(attrs={'placeholder': 'Full Name'}) ) email = forms.CharField( label="", widget=forms.TextInput(attrs={'placeholder': 'Email', 'type': 'email'}) ) subject = forms.CharField( label="", widget=forms.TextInput(attrs={'placeholder': 'Subject'}) ) message = forms.CharField( label="", widget=forms.Textarea(attrs={'placeholder': 'Message', 'rows': 5}) ) captcha = CaptchaField() page.html <form method="POST"> {% csrf_token %} {{ contact_entry_form|crispy }} <input type="submit" value="Submit" class="btn btn-dark" style="width: 100%" /> </form> But the image and text fields in the captcha section are too narrow. I want to add some margin between the image and text field. Can I do some HTML formatting on forms.py? For example: captcha = CaptchaField(attrs={'style': 'margin:10px'}) Or is there any better solution to add some margin from forms.py? -
Django - two different urls calling same method which throws error
project urls.py urlpatterns = [ path('', include('products.urls')), ] application urls.py path('p/a/s/',views.get_product_store_data,name='get_product_store_data'), # store by url path('<str:store_url>/',views.store_from_url, name="store_from_url"), path('p/',views.show_product_list, name="show_product_list"), # Random store detail path('s/d/<store_id>/',views.random_store_detail, name="random_store_detail"), # Random Service List path('sr/',views.get_random_service_list, name="get_random_service_list"), in application urls.py the 2nd url is http://127.0.0.1:8000/expert-elektronikfachhandel which take me to the store detail page and 3rd url is http://127.0.0.1:8000/p which take me to the product page I'm calling the 1st url with the below function def get_product_store_data(request): """ get all product list and store list for search text """ try: if request.method == 'GET': if category == 'all': data = logic.get_product_store_data(request) return render(request, 'list_product_and_store.html', data) elif category == 'stores': return HttpResponseRedirect(f"/s/?s={request.session['search_text']}") elif category == 'services': return HttpResponseRedirect(f"/sr/?s={request.session['search_text']}") elif category == 'products': return HttpResponseRedirect(f"/p/?s={request.session['search_text']}&p=0") elif category == 'events': return redirect("all_events") elif category == 'restaurants': return redirect("restaurant") elif category == 'public_service': return redirect("public_service", -1) except Exception as e: logger.error(f'{repr(e)} -->{request.user.username}') return redirect("error404") i'm using return HttpResponseRedirect(f"/p/?s={request.session['search_text']}&p=0") to redirect to p/?s={request.session['search_text']}&p=0 as GET request, and passing search value and page no. as parameter using the above code now the problem is when i call the 2nd url then it is calling the 1st url throws an error(both are in same page). Why this is happening i'm not able to find … -
django : __str__ returned non-string (type NoneType), only when __str__ defined
I knew there is tons of post regarding this error. I think what I got is pretty strange. Ok here it is. models.py class Axie(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=30, blank=True, null=True) sire = models.ForeignKey("Axie", related_name= "mysire", blank=True, null=True, on_delete=models.SET_NULL) matron = models.ForeignKey("Axie", related_name= "mymatron", blank=True, null=True, on_delete=models.SET_NULL) scholar= models.ForeignKey(Scholar,null=True, blank=True, on_delete=models.SET_NULL) def __str__(self): return self.name With that code, I got a normal basic list as usual But I got error on every 'change view' This is the traceback from debug page Environment: Request Method: GET Request URL: http://127.0.0.1:8000/admin/university/axie/10277276/change/ Django Version: 4.0.2 Python Version: 3.8.10 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'university.apps.UniversityConfig'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template /home/bino/.local/share/virtualenvs/djenv-loPXW3SM/lib/python3.8/site-packages/django/contrib/admin/templates/admin/includes/fieldset.html, error at line 19 __str__ returned non-string (type NoneType) 9 : {% for field in line %} 10 : <div{% if not line.fields|length_is:'1' %} class="fieldBox{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% if not field.is_readonly and field.errors %} errors{% endif %}{% if field.field.is_hidden %} hidden{% endif %}"{% elif field.is_checkbox %} class="checkbox-row"{% endif %}> 11 : {% if not line.fields|length_is:'1' and not field.is_readonly %}{{ field.errors }}{% endif %} 12 : {% if field.is_checkbox %} 13 : {{ field.field }}{{ field.label_tag }} … -
Django: How to serve media to authenticated users from private digital ocean spaces?
I have set up a private space on DigitalOcean and can successfully upload image files to it using django-storages, according to the method of subclassing S3Boto3Storage shown here by Vitor Freitas. I'll omit all the S3 settings from settings.py unless someone asks for it. Most documentation I have found seems to focus on generating temporary sharing links to files via pre-signed urls, which is not a requirement for me, and generates more questions than answers. Do all pre-signed urls need to expire? To show private space media in my template, do I need to generate pre-signed urls through django's "upload_to=" field parameter, with something like: def url_generator(instance, filename): new_file_path = # using some pre-signed url generator function using boto3? return new_file_path class Photo(models.Model): image_file = models.ImageField(storage=PrivateMediaStorage(), upload_to=url_generator) def __str__(self): return str(self.image_file.name) ... or is that some kind of anti-pattern? Do pre-signed urls need to be generated in my view logic? def view_photo_grid(request): images = Photo.objects.all() for i in images: # create some presigned url for each and render it to the template return render (request, 'pages/gallery.html', {'images':images_with_url}) ...or is it a matter of writing a custom url generator function to use in the template, something like: {% for image in … -
How to exclude a specific value from a list and get the rest of the values in django template
I'm using Django, and I want to output the values excluding a specific value from a list using a template tag. {{ backup.teacher }}: 'Adam/Helen/Edward' <tbody> {% for backup in backup %} {% for leave in leave %} <tr> <td>{{ leave.name }}</td> --> ex: Helen <td>{{ backup.teacher|split:'/' }}</td> --> ex: ['Adam',' Helen', 'Edward'] </tr> {% endfor %} {% endfor %} </tbody> I want the value of the second cell to come out of the list excluding the name from the first cell. Heading 1 Heading 2 Helen Adam Helen Edward I tried to apply custome filter in template tag. However, the value None is output. @register.filter @register.simple_tag def three_teacher(value, teacher): list_teacher = value.split('/') return list_teacher.remove(teacher) -
Django - get data from form and return to user so they can edit/delete
New to Django and making a restuarant booking system. I have everything going to my database but now i'm trying to return the info back to the user, ideally in a similar form view to what i have, so they can edit or delete the booking. My code so far is as follows: models.py: class Reservations(models.Model): reservation form categories and attributes name = models.CharField(max_length=50) phone_number = models.CharField(validators=[phoneNumberRegex], max_length=16, unique=True) email = models.EmailField() date = models.DateField() time = models.CharField(choices=time_options, default="12pm", max_length=10) number_of_party = models.IntegerField(choices=party_size, default=1) reservation_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, max_length=15) class Meta: ordering = ['date'] verbose_name = 'Reservation' verbose_name_plural = 'Reservations' def __str__(self): return self.name Then my form looks like this: form.py: class ReservationForm(forms.ModelForm): class Meta: model = Reservations fields = ['name', 'phone_number', 'email', 'date', 'time', 'number_of_party'] widgets = { 'date': DatePickerInput(format='%d-%m-%Y'), } Then where I think i'm really getting lost is with the views. view.py: class ReservationsFormView(CreateView): model = Reservations template_name = "reservations/reservations.html" form_class = ReservationForm success_url = "reservation_complete/" def form_valid(self, form): return super().form_valid(form) class EditReservationView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Reservations template_name = "reservations/edit_reservations.html" form_class = ReservationForm success_url = "reservation_complete/" def test_func(self): return self.request.user == self.get_object().user class ReservationCompleteView(CreateView): template_name = "reservations/reservation_complete.html" success_url = "/reservation_complete/" form_class = ReservationForm model = … -
How to go through a Django dictionary in HTML template
Im new to Django and I don't really have a clear idea how the Django Template language works but I have a dictionary that is something like this: { "info":{ "a":"test1", "b":"test2", } } How can I get the values for "a" and "b" in Django template. I'm not sure if that makes sense but what I mean would look something like this in Python: for i in info: print(info.i) I already tried this but it didn't work {%for i in info %} {% if info.i %} console.log('{{info.i}}') {% endif %} {% endear %} -
Deploy socketio Django application using gunicorn and Nginx
I am using Django for my application and socketio library it works quit well, but i have few questions and concerns. I want to know that is the best way to deploy this application using Nginx and gunicorn with eventlet. wsgi.py import os import socketio import eventlet import eventlet.wsgi from django.core.wsgi import get_wsgi_application from django.contrib.staticfiles.handlers import StaticFilesHandler from sioapp.views import sio application = get_wsgi_application() os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ESIProject.settings') django_app = StaticFilesHandler(application) application = socketio.Middleware(sio, wsgi_app=django_app, socketio_path='socket.io') eventlet.wsgi.server(eventlet.listen(('0.0.0.0', 5100)), application) First Question: I am taking many sensor readying every second from my Raspberry Pi and I am consuming quite lot of data but not sure if I should use async functionality or just keep regular functions? Second Question: When I run my django application locally with manage.py I see two address and not sure if port 8000 is getting override by 5100. please explain this below. Django version 4.0.2, using settings 'ESIProject.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. (9320) wsgi starting up on http://0.0.0.0:5100 Third Question: I am also using React as client (socket.io-client) for my Front-end application but not sure if that should be implementing in Nginx. I have a lot going on in my mind and I … -
Django - Celery cant find my tasks. How can I configure for this project structure?
I get KeyError: 'example_app.tasks.example_task' whenever I try to execute a task (example_task.delay()) Project Structure: |-- config | |-- celery.py | |-- settings.py | |-- src |-- example_app | |-- tasks.py | |-- example_app2 |-- tasks.py celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings') app = Celery('config') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() example_app -> tasks.py from config.celery import app @app.task def example_task(): print('task') return I've tried adding a list to app.autodiscover_tasks() like ['example_app'] or ['src.example_app'], but can't seem to get it to register. Thanks -
Cookie not set in request header when request is sent from React
My backend is in Django and Frontend is in React. I have set up CROS header and added settings as follows. Django settings For sending request I am using fetch and i have set credentials: 'include'. I am using the session based authentication, So when I signin session of a user starts. Then from the parent component (from useEffect) I send a request to backend to fetch Jobs. Things work fine in this case. Below is the header of this particular request. It has COOKIE Request header 1 when I send request from child component of react, COOKIE is not present in the header. Below is the header of this particular request. Request header 2 I am not able to get why this thing is happening, One more difference in both the request headers is the value of HTTP_SEC_FETCH_SITE in request header. In first request value of HTTP_SEC_FETCH_SITE is same-site whereas in second request HTTP_SEC_FETCH_SITE is cross-site. Even though request is sent through http://localhost:3000 in both cases why value of HTTP_SEC_FETCH_SITE is different. -
Problem with the django authentication by using username and face
Up to now, I can do the two-factor authentication(username + password + face) I want to know how to modify the authentication by only using the username and face only. view.py def face_login(request): if request.method == 'POST': form = AuthenticationForm(request, request.POST) if form.is_valid(): username = form.cleaned_data ['username'] password = form.cleaned_data['password'] face_image = prepare_image(form.cleaned_data['image']) face_id = FaceIdAuthBackend() user = face_id.authenticate(username=username,password=password,face_id=face_image) if user is not None: login(request, user) return redirect('home') else: messages.info(request, "Username, password or face id didn't match.") return redirect('facelogin') else: form = AuthenticationForm() context = {'form': form} return render(request, 'django_two_factor_face_auth/facelogin.html', context) enter code here model.py class UserFaceImage(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(upload_to=content_file_name, blank=False) authenticate.py class FaceIdAuthBackend(ModelBackend): def authenticate(self, username=None, password=None, face_id=None, **kwargs): try: user = User.objects.get(username=username) if self.check_face_id(face_id=user.userfaceimage.image, uploaded_face_id=face_id): return user except User.DoesNotExist: User().set_password(password) def check_face_id(self, face_id=None, uploaded_face_id=None): confirmed_image = face_recognition.load_image_file(face_id) uploaded_image = face_recognition.load_image_file(uploaded_face_id) face_locations = face_recognition.face_locations(uploaded_image) if len(face_locations) == 0: return False confirmed_encoding = face_recognition.face_encodings(confirmed_image)[0] unknown_encoding = face_recognition.face_encodings(uploaded_image)[0] results = face_recognition.compare_faces([confirmed_encoding], unknown_encoding) if results[0] == True: return True return False -
Why won't my Django template display the correct date listed in the database?
My model contains a datefield, 'valid_until'. Even though an entry contains the date '12/25/2022', the update template literally displays as its contents 'mm/dd/yyyy' when the user tries to modify the date. Why? Also, there seems to be no way to create a placeholder text or even change that date format (it always renders in that same format---even though I specify '%m/%d/%y' in forms.py and settings.py contains the format '%m/%d/%y'). Why? settings.py: TIME_ZONE = 'US/Eastern' USE_I18N = True USE_L10N = True DATE_INPUT_FORMATS = '%m/%d/%y' models.py: class DecisionsList(models.Model): summary = models.CharField(default="", max_length=75, ` verbose_name="Decision Summary") description = models.CharField(max_length=100, verbose_name="Decision Description") valid_until = models.DateField(default=timezone.now, verbose_name="Voting End Date") date_created = models.DateTimeField(default=timezone.now) views.py: class UpdateDecisionView(LoginRequiredMixin, UpdateView): model = DecisionsList form_class = DecisionForm template_name = "users/update_decision.html" forms.py: class DecisionForm(forms.ModelForm): class Meta: model = DecisionsList fields = ['summary', 'description', 'valid_until'] widgets = { 'valid_until': forms.DateInput( format='%m/%d/%y', attrs={'type': 'date', 'placeholder': "Select a date" }), 'description': forms.Textarea( attrs={'line-height': '50px', }) } update_decision.html: {% extends "users/base_users.html" %} {% load crispy_forms_tags %} {% load crispy_forms_filters %} <body> {% block content %} <div class="nav"> <a id="company" {% block company %} class="selected" {% endblock %} href=""></a> </div> <div class="containers database-containers"> <h2>Update a Decision</h2> <form method="post"> <div class="form-group"> {% csrf_token %} {{form.summary|as_crispy_field}} <div class="text-area"> … -
Django @sync_to_async function can be used on uwsgi env?
I want to use @sync_to_async function on django. According to the Django Asynchronous support Document, Async views will still work under WSGI. Does this mean that "@sync_to_async" can also be used without adding the asgi env on uwsgi env? Also according to the documentation, it says Under a WSGI server, you will not get the benefits of an async stack.. What I want to do is add a lot of data through orm and add a lot of data to the queue. This operation is network io-intensive. Doesn't this need the benefit of the async stack? -
Django: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1123)
I'm trying to email using Python's smtplib. This is the email() function: def email(to, subject_parameter, body_parameter): subject = subject_parameter body = body_parameter sender_email = "pfcbookclub@gmail.com" receiver_email = to password = "Zt2.~[3d*.[Y5&5r" # Create a multipart message and set headers message = MIMEMultipart() message["From"] = sender_email message["To"] = receiver_email message["Subject"] = subject message["Bcc"] = "pfcbookclub@gmail.com" # Add body to email message.attach(MIMEText(body, "plain")) text = message.as_string() # Log in to server using secure context and send email context = ssl.create_default_context() with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server: server.login(sender_email, password) server.sendmail(sender_email, receiver_email, text) When someone signs up on my website, I want an email to be sent to the website's email address (not to the user). I've done this: def register(request): registered = False ctx = {} if request.method == 'POST': username = request.POST.get("username") full_name = request.POST.get("full_name") password = request.POST.get("password") email_id = request.POST.get("email") house_number = request.POST.get("house_number") phone_number = request.POST.get("phone_number") if len(User.objects.filter(username=username)) == 0: ctx["username_exists"] = False user_form = UserForm(data=request.POST) if user_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() user_profile = UserProfileInfo(user=user,full_name=full_name, email=email_id, house_number=house_number, phone_number=phone_number) user_profile.save() subject = username + " just registered" body = username + " just registered on pfcbookclub.com. Link to admin: https://pfcbookclub.com/Caput_Draconis/" email("pfcbookclub@gmail.com", subject, body) # Error on this line username = request.POST.get('username') … -
Сохранение формы, связанной с внешним ключом, в Django
Моя модель: class User(AbstractBaseUser,PermissionsMixin): email = models.EmailField(db_index=True, unique=True, max_length=254) phone = models.CharField(max_length=20,help_text='Номер телефона') is_staff = models.BooleanField(default=True) # must needed, otherwise you won't be at is_active = models.BooleanField(default=True) # must needed, otherwise you won't be « is_superuser = models.BooleanField(default=False) # this field we inherit from Permis class Case(models.Model): CATEGORIES = [ ('Медицина','Медицина'),('Программирование','Программирование'), ('Архитектура','Архитектура') ] title = models.CharField(max_length=200,verbose_name='Название') description = models.TextField(verbose_name='Описание кейса') date_of_create = models.DateTimeField(auto_now=True) date_of_edit = models.DateTimeField(auto_now_add=True) date_of_close = models.DateTimeField() category = models.CharField(max_length=100,choices=CATEGORIES) user_id = models.ForeignKey(User,on_delete=models.CASCADE) Форма forms.py Нужно ли в форму добавлять user_id или к нему нужно присвоить pk? class AddCaseForm(ModelForm): class Meta: model = Case fields = ['title', 'description', 'category', 'date_of_close'] Мой views.py def createcase(request): form = AddCaseForm() error = '' if request.method == 'POST': form = AddCaseForm(request.POST) if form.is_valid(): form.save() return redirect('ShowCase') else: error = 'Форма была неверной' data = { 'form': form, 'error': error } return render(request,'createcase.html',data) Страница html createcase.html Форма должна передавать данные в базу {% extends 'base.html' %} {% block content %} <h1>Форма создания кейса</h1> <form method="post"> {% csrf_token %} {{ form.title }} <br> {{ form.description }} <br> {{ form.category }} <br> {{ form.date_of_close }} <br> <span>{{error}}</span> <button type="submit">Добавить</button> </form> {% endblock %} Как нужно правильно передать ключ и сохранить его в базу? -
Adapt my django view to form-wizard.init.js to save to database
I have a question, what happens is that I have a project in django that has the form-wizard.init.js and jquery.steps.min.js and it works quite well, I also placed a formset in django, all ok. The thing is that I just saw that for me to add to the database, my view does not work. Is there a way to save the data step by step with django and with those plugins? I also saw a way that is with django-formtools but if I implement it, what if I have already put form-wizard.init.js, it would be to put everything back from scratch. I will give an example of what I have in my code, not everything views.py def create_Presupuestos(request): extra_forms = 1 ParteFormSet = formset_factory(PresupuestosParteForm, extra=extra_forms, max_num=20) ManoObraFormSet = formset_factory(PresupuestosManoObraForm, extra=extra_forms, max_num=20) PagosFormSet = formset_factory(PresupuestosPagosForm, extra=extra_forms, max_num=20) presupuestosclientesform=PresupuestosClientesForm(request.POST or None) presupuestosvehiculosform=PresupuestosVehiculosForm(request.POST or None) presupuestosparteform=PresupuestosParteForm(request.POST or None) presupuestosmanoobraform=PresupuestosManoObraForm(request.POST or None) presupuestospagosform=PresupuestosPagosForm(request.POST or None) presupuestosfotosform=PresupuestosFotosForm(request.POST or None) if request.method == 'POST': formset = ParteFormSet(request.POST, request.FILES) manoObra_formset = ManoObraFormSet(request.POST, request.FILES,prefix='manoobra') pagos_formset = PagosFormSet(request.POST, request.FILES, prefix='pagos') #formset = ParteFormSet(request.POST, request.FILES,prefix='__form') if formset.is_valid() and manoObra_formset.is_valid() and pagos_formset.is_valid(): presupuestosclientesform.save() return redirect('presupuestos:index') else: formset = ParteFormSet() manoObra_formset = ManoObraFormSet(prefix='manoobra') pagos_formset = PagosFormSet(prefix='pagos') presupuestosfotosform = PresupuestosFotosForm(request.POST or None) return … -
TypeError at /oauth/complete/mediawiki/ when upgrading to social-auth-app-django 3.3.0
I'm running: Python 3.7.3 Django 3.1.14 social-auth-app-django 3.1.0 When I try to upgrade social-auth-app-django to 3.3.0 or 3.4.0, I get: Traceback (most recent call last): File "/data/project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/data/project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/data/project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/data/project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/data/project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/social_django/utils.py", line 49, in wrapper return func(request, backend, *args, **kwargs) File "/data/project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/social_django/views.py", line 33, in complete *args, **kwargs) File "/data/project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/social_core/actions.py", line 45, in do_complete user = backend.complete(user=user, *args, **kwargs) File "/data/project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/social_core/backends/base.py", line 40, in complete return self.auth_complete(*args, **kwargs) File "/data/project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/social_core/utils.py", line 247, in wrapper return func(*args, **kwargs) File "/data/project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/social_core/backends/oauth.py", line 181, in auth_complete return self.do_auth(access_token, *args, **kwargs) File "/data/project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/social_core/utils.py", line 247, in wrapper return func(*args, **kwargs) File "/data/project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/social_core/backends/oauth.py", line 192, in do_auth return self.strategy.authenticate(*args, **kwargs) File "/data/project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/social_django/strategy.py", line 107, in authenticate return authenticate(*args, **kwargs) File "/data/project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/django/contrib/auth/__init__.py", line 73, in authenticate user = backend.authenticate(request, **credentials) File "/data/project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/social_core/backends/base.py", line 80, in authenticate return self.pipeline(pipeline, *args, **kwargs) File "/data/project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/social_core/backends/base.py", line 83, in pipeline out = self.run_pipeline(pipeline, pipeline_index, *args, **kwargs) File "/data/project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/social_core/backends/base.py", line 113, in run_pipeline result = func(*args, **out) or {} File "/data/project/spi-tools-dev/www/python/venv/lib/python3.7/site-packages/social_core/pipeline/user.py", line 119, in user_details … -
Django - passing one model to another while creating new object
My site has multiple tests with multiple questions each. I'd like to make question creation form which will have preset test object depended on url. it's better explained in comment in views.py That's what I have already done; models class Test(models.Model): name = models.CharField(max_length=200) #questions = models.ManyToManyField(Question) author = models.ForeignKey(User, on_delete=models.CASCADE, default=None, null=True, blank=True) date_posted = models.DateTimeField(auto_now_add = True) def get_questions(self): return self.question_set.all() def __str__(self): return self.name class Question(models.Model): text = models.CharField(max_length=200, null=True) test = models.ForeignKey(Test, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add = True) def __str__(self): return self.text urls urlpatterns = [ path('', views.home, name='home'), path('test/<str:pk>/', views.test), path('test/<str:pk>/question-create/', views.QuestionCreateView, name='question-create'), ] forms from django import forms from django.forms import ModelForm from .models import Question, class QuestionCreationForm(ModelForm): class Meta: model = Question fields = '__all__' /// all except test which is set by pk in url views def QuestionCreateView(request, pk): form = QuestionCreationForm() if request.method == 'POST': test = Test.objects.get(id=pk) /// I would like to pass it to models to disallow user to choose to which test will question belong, i mean test should pe preset by <pk> in link form = QuestionCreationForm(request.POST) if form.is_valid(): form.save() return redirect('home') context = {'form':form} return render(request, 'exam/question_form.html', context) what should I add/change to disallow user to … -
Import could not be resolve after installing the dependency
I'm trying to install de messagebird dependency into my python project. I write into requirements.txt and after I run pip install -r requirements.txt as you can see below: But the pylance was still showing me the error: Then I try to install using pip install messagebird but still with no success. I also try to reopen the window but no success too.