Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django Tests with django-hosts
How can I test in Django using django-hosts? I have main app urls in ROOT_URLCONF and it works fine, but how can I test using reverse_lazy for subdomains using django-hosts? I have tried below and it doesn't work. class IndexViewTest(TestCase): urls = 'subdomain_name.urls' url = reverse_lazy('index') client = Client() def test_http_status_code_302(self): response = self.client.get(self.url) self.assertEqual(response.status_code, 302) -
URL working on localhost but not in production
I have build a website using django and uplaoded it but url redirection within the website is not working. It gives 404 error. The home page is loading fine but other links are not working. It works perfectly fine on local machine. Please help as unable to figure out the reason -
error when trying to makemigrations/migrate in django
i just made made a new project and when i try to to run a command like makemigration, migrate or runserver it gives the following error, i've followed a tutorial video just as he did it but it didn't give him an error but it gave me an error. here is the error i get: Traceback (most recent call last): File "C:\Users\upbeat\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\upbeat\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 361, in execute self.check() File "C:\Users\upbeat\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 387, in check all_issues = self._run_checks( File "C:\Users\upbeat\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\upbeat\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\upbeat\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\checks\urls.py", line 100, in check_url_settings value = getattr(settings, name) File "C:\Users\upbeat\AppData\Local\Programs\Python\Python38\lib\site-packages\django\conf\__init__.py", line 79, in __getattr__ self._setup(name) File "C:\Users\upbeat\AppData\Local\Programs\Python\Python38\lib\site-packages\django\conf\__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) File "C:\Users\upbeat\AppData\Local\Programs\Python\Python38\lib\site-packages\django\conf\__init__.py", line 157, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\upbeat\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'telsem.settings' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) … -
Keep getting this error of Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name
Hey guys i keep getting this error while doing this feature on my web app for reseting passwords Idk why it happens Here is my urls.py code: from django.urls import path from .views import * from django.contrib.auth import views as auth_views Full traceback: NoReverseMatch at /accounts/password_reset/ Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. Request Method: POST Request URL: http://127.0.0.1:8000/accounts/password_reset/ Django Version: 3.1.6 Exception Type: NoReverseMatch Exception Value: Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. Exception Location: C:\Users\Dominique\Desktop\STUFF\dev\car_sales\env\lib\site-packages\django\urls\resolvers.py, line 685, in _reverse_with_prefix Python Executable: C:\Users\Dominique\Desktop\STUFF\dev\car_sales\env\Scripts\python.exe Python Version: 3.8.5 Python Path: ['C:\\Users\\Dominique\\Desktop\\STUFF\\dev\\car_sales\\src', 'c:\\users\\dominique\\appdata\\local\\programs\\python\\python38-32\\python38.zip', 'c:\\users\\dominique\\appdata\\local\\programs\\python\\python38-32\\DLLs', 'c:\\users\\dominique\\appdata\\local\\programs\\python\\python38-32\\lib', 'c:\\users\\dominique\\appdata\\local\\programs\\python\\python38-32', 'C:\\Users\\Dominique\\Desktop\\STUFF\\dev\\car_sales\\env', 'C:\\Users\\Dominique\\Desktop\\STUFF\\dev\\car_sales\\env\\lib\\site-packages'] Server time: Sun, 28 Feb 2021 06:42:15 +0000 app_name = 'accounts' urlpatterns = [ path('create-user/', registerview, name='register'), path('login/', loginview, name='login'), path('logout/', logoutview, name='logout'), path('password_reset/', auth_views.PasswordResetView.as_view(template_name='accounts/reset_password.html'), name="password_reset"), path('password_reset_done/', auth_views.PasswordResetDoneView.as_view(template_name='accounts/reset_password_sent.html'), name="password_reset_done"), path('password_reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='accounts/reset_password_form.html'), name="password_reset_confirm"), path('password_reset_complete/', auth_views.PasswordResetCompleteView.as_view(template_name='accounts/reset_password_sucess.html'), name="password_reset_complete"), ] and here is one of my templates that im using to override the default one reset_password.html: <h2>Introduza o email para mudar a sua password</h2> <form method="POST"> {% csrf_token %} {{ form }} <input type="submit" value="Enviar email de atualizacao de password"> </form> -
is it possible to import a variable inside a function from one python script to another python script?
Apparently i have found out a way to import functions from one python script to another. from file_name.py import function_name But is it possible to transfer variables as well. Apologies cause I'm new to python. -
Test that Django sends the e-mail for password reset
Good morning, I would like to test that Django properly sends an e-mail for password reset as I have customised the routes. However I get a <HttpResponseForbidden status_code=403, "text/html"> and the e-mail is not implemented when I test it. Here are the main features: url : path('password_reset/', auth_views.PasswordResetView.as_view(template_name="customer/password_reset_form.html", email_template_name="customer/password_reset_e-mail.html", success_url="done/"), test method: from django.contrib.auth import views as auth_views from django.test import RequestFactory from django.contrib.auth.models import AnonymousUser class PasswordResetTest(TestCase): def setUp(self): self.factory = RequestFactory() self.user = User.objects.create_user( username="user", email="user@mail.com", password="pwd") def test_send_mail(self): request = self.factory.post('/customer/password_reset', {'email': 'user@mail.com'}) response = auth_views.PasswordResetView.as_view()(request) self.assertTemplateUsed('password_reset_e-mail.html') print(response) self.assertEqual(len(mail.outbox), 1) Throught the print command, I can see an error 403 and that the outbox is empty. I just cannot find proper documentation to build a test on this very part of Django. Thank you for your support. -
Pulling Data From Other Data Bases In Django
I'm new to Django . I am totally confused now . I am going to create a new feature to our product. In this users can connect their data bases and pull data from their data bases . The main challange is that, user can connect data bases like Oracle , Sql Server, Mysql etc.... I have done lots of research , but I am not able to found any package for this . So now , I am confused that , is it possible to connect an external data base and copy the data from that data bases to our project. I have seen one package called "Appache airflow" (https://airflow.apache.org/) But I am not sure this will support for Django . If some one having any idea please help to solve this issue . -
how to have Google Captcha for 2 Django Form on One Page
I am getting bots on my website, so I want a captcha to stop bots from submitting forms. I have a login and a register Django form on a single page. My current code puts a captcha under each submit button, but it is not forcing the user to complete the captcha before submitting, and rather allows the user to just submit the form without filling out the captcha. How can I make sure the user completes the captcha before submitting the form, so only real humans can login and register. This is my current code: <script src="https://www.google.com/recaptcha/api.js?onload=CaptchaCallback&render=explicit" async defer></script> <script type="text/javascript"> var CaptchaCallback = function () { grecaptcha.render('RecaptchaField1', {'sitekey': 'my_sitekey'}); grecaptcha.render('RecaptchaField2', {'sitekey': 'my_sitekey'}); }; </script> <body> <h2>Login</h2> <form> {% csrf_token %} {{ login.as_p }} <button>Login</button> <div id="RecaptchaField1"></div> </form> <h2>Register</h2> <form> {% csrf_token %} {{ signup.as_p}} <button>Register</button> <div id="RecaptchaField2"></div> </form> </body> -
Trying to save the data of logged in user to db along with form data
i am trying to save the form data and logged in users data like gender and user to my model. everything is working fine but only gender is not showing up in admin panel here is what i have done def predict(request): Prediction=polyu=polyd=swl=par_par=polyp=BMI=irrit=alop=v_bull=wkns=Gender = 0 if request.method=='POST': form = PredForm(request.POST) if form.is_valid(): polyu = form.cleaned_data['Polyuria'] polyd = form.cleaned_data['Polydipsia'] swl = form.cleaned_data['Sudden_weight_loss'] par_par = form.cleaned_data['Partial_paresis'] polyp = form.cleaned_data['Polyphagia'] irrit = form.cleaned_data['Irritability'] alop = form.cleaned_data['Alopecia'] v_bull = form.cleaned_data['Visual_blurring'] wkns = form.cleaned_data['Weakness'] instance = form.save(commit=False) instance.patient= request.user instance.gender= request.user.profile.gender Gender= instance.gender print(Gender) Prediction = getPredictions(polyu, polyd, Gender, swl, par_par, polyp, irrit, alop, v_bull,wkns) instance.Prediction = Prediction print(Prediction) instance.save() print(Gender) -
django : <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777)>
My django project is deployed using wamp and has ssl certifcate added. For a specific page, which contains a form to upload a csv and convert it into txt file, the file gets uploaded (the file gets added to the media folder of the project ) but then i get <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777)> error. I have tried adding my domain's crt file's content into the certifi's cacert.pem file but the issue still isn't resolved. Environment: Request Method: POST Request URL: https://api.tpglobalfx.com/create_file_for_upload/ Django Version: 3.1.7 Python Version: 3.6.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'core_engine'] 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'] Traceback (most recent call last): File "c:\python3.6\lib\urllib\request.py", line 1318, in do_open encode_chunked=req.has_header('Transfer-encoding')) File "c:\python3.6\lib\http\client.py", line 1239, in request self._send_request(method, url, body, headers, encode_chunked) File "c:\python3.6\lib\http\client.py", line 1285, in _send_request self.endheaders(body, encode_chunked=encode_chunked) File "c:\python3.6\lib\http\client.py", line 1234, in endheaders self._send_output(message_body, encode_chunked=encode_chunked) File "c:\python3.6\lib\http\client.py", line 1026, in _send_output self.send(msg) File "c:\python3.6\lib\http\client.py", line 964, in send self.connect() File "c:\python3.6\lib\http\client.py", line 1400, in connect server_hostname=server_hostname) File "c:\python3.6\lib\ssl.py", line 407, in wrap_socket _context=self, _session=session) File "c:\python3.6\lib\ssl.py", line 814, in __init__ self.do_handshake() File "c:\python3.6\lib\ssl.py", line 1068, in do_handshake self._sslobj.do_handshake() File "c:\python3.6\lib\ssl.py", line 689, in do_handshake self._sslobj.do_handshake() During … -
I'm tring to pre-populate my edit page in django
I want to pre-populate my form fields with the title and its content that can be edited. I have tried all possible ways but it still doesn't show the initial value. view.py: class EditPageForm(forms.Form): title = forms.CharField(max_length=100) content = forms.CharField(widget=forms.Textarea) def edit_page(request,pre_title): # if this is a POST request we need to process the form data if request.method == 'POST': # dictionary for the intial values intial_dict = { "title": pre_title, "content": util.get_entries(pre_title) } # create a form instance : form = EditPageForm(request.POST,initial=intial_dict) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required title = form.cleaned_data['title'] content = form.cleaned_data['content'] util.save_entries(title,content) # redirect to a new URL: return HttpResponseRedirect(reverse('wikiapp:index')) # if data is not valid we'll return the form with error message else: return render(request,"encyclopedia\edit_page.html",{ "form": form }) # if a GET (or any other method) we'll create a blank form return render(request,"encyclopedia\edit_page.html",{ "form": EditPageForm() }) -
AttributeError: 'rfi' object has no attribute 'report_data'
I am implementing a web-vulnerable scanner. I have created a class rfi.py I am trying to get the report after scanning the URL . I crated the object of rfi.py classes and call the rfi_obj.scan() But It's given error as below: Exception in thread Thread-8: Traceback (most recent call last): File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/home/azharul/Django-projects/ThirdEye/scanner/views.py", line 28, in start_scan scanner.start_scanning() File "/home/azharul/Django-projects/ThirdEye/scanner/scanner_files/scanner_OOP.py", line 346, in start_scanning self.full_report.append(self.rfi_obj.report_data) ***AttributeError: 'rfi' object has no attribute 'report_data'*** ** The report_data ** ... report["status"] = "Vulnerable" report["threat"] = "Crtical" report["endpoints"].append(web0x0) .... **I declared the report at first ** report = { "type" : "Remote File Inclution", "status" : "Not Vulnerable", "endpoints" : [], "threat" : "None" } rfi.py #!/usr/bin/env python3 # coding: utf-8 import os import sys import time import urllib.request from time import sleep from tidos_core.Core.colors import * from tidos_core.methods.tor import session info = "This module scans the target site for Remote File Inclusion vulnerabilities by either a specific attack, or by brute force." searchinfo = "Remote File Inclusion Scanner" properties = {"PARAM":["Directory and Parameter to attack (eg /vuln/page.php?q=lmao)", " "], "PARALLEL":["Parallelise Attack? [1/0]", " "], "DICT":["Path to dictionary to be … -
Django static files loaded but not applied
Goal: I have some frontend pages (consist of HTML and the assets (images, CSS, JS)). Now just want to move those pages to a new Django project. Problem: In the browser, all the static files are not applied but loaded successfully. From the chrome dev tools, I can see that everything is 202 . Also all the static files are correct. Similar problems: CSS Loaded but not being applied CSS loaded but not applied Static Files not getting loaded in Django Python Django staic and admin static css files loaded but not applied to page Django: CSS and Images (Static Files) loaded successfully but not applied Django Static Files - CSS File Won't Load None of them works for me. Code details: Python 3.7.6 Django 3.1.7 Project tree: ~/SETH/SETH_A$ tree -L 1 . ├── A_WEB ├── db.sqlite3 ├── facial_simple ├── __init__.py ├── manage.py ├── node_modules ├── open ├── package.json ├── SETH_A ├── static ├── staticfiles └── templates static dir (make sure the permission is enough): ~/SETH/SETH_A$ ls static/assets css demo img js test ~/SETH/SETH_A$ ls -l static/assets total 20 drwxrwxrwx 2 kevin kevin 4096 Feb 9 17:46 css drwxrwxrwx 2 kevin kevin 4096 Feb 9 17:46 demo drwxrwxrwx 3 kevin … -
Is there a more elegant way to implement an modification to save() method when using CreateView and ModelForm in Django?
I'm learning the Class-Based View and ModelForm of Django, and I feel so confused with those things. I want to create a page where users can post articles. My implementation is as following: models.py class Post(models.Model): id = models.CharField(primary_key=True, null=False, max_length=20) owner = models.ForeignKey(User, on_delete=models.CASCADE, null=False) content = models.TextField() count_like = models.IntegerField(default=0) created_time = models.DateTimeField() last_modified = models.DateTimeField() def save(self, *args, **kwargs): ''' On save, update last_modified ''' if not self.id: count = Post.objects.count() self.id = "PO" + str(count) self.created_time = timezone.now() self.last_modified = timezone.now() return super(Post, self).save(*args, **kwargs) def get_absolute_url(self): print("pk"*100, self.pk) return reverse('post_detail', kwargs={'pk': self.pk}) forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ['content'] def save(self): return super().save(commit=False) views.py class PostCreateView(generic.CreateView): model = Post form_class = PostForm template_name="post/create.jinja" def form_valid(self, form): self.object = form.save() self.object.owner = self.request.user self.object.save() return HttpResponseRedirect(self.get_success_url()) urlpatterns path('create/', PostCreateView.as_view(), name="post_create") I checked and this works. As you can see, the Post model has many attributes, but I just want users to fill 1 field content, the others would be automatically initiated. Is there any way to improve my implementation, because it's seperated into many places (model save() method, form save() method, valid_form() method). One more question is what is self.object role? After … -
How to adjust Django query set value?
I have a view: def get_comment_tree(request): news_id = request.GET.get("news_id") ret = list(Comment.objects.filter(news_id=news_id).values("nid", "content", "parent_comment_id", "user", "create_time")) return JsonResponse(ret, safe=False) The return of the view will be sent back to ajax.Now problems are,how can I convert the value "user" to "username",and the "create_time" to naturalday or naturaltime format. If I use python to convert these data I think it would be a little complicated,any friend can help? -
Django on mac Catalina
When I run python manage.py migrate I get the error: ModuleNotFoundError: No module named 'safetobeme' And what's bizarre is that when I search for "safetebeme" on google I get nothing. I'm on Mac Catalina. -
Video control during infinite scroll
I'm an beginner who is starting to develop with django. It consists of a web page similar to Facebook or Instagram and all the contents are videos. Currently, we have configured the infinity scroll, and jquery has played the video on the screen and stopped the invisible video. We also configured the script with onclick so that when you click on the video, you can only mute it and play it again. There was a problem here. Videos that are not visible on the <!> screen should stop playing, but videos that are unmuted cannot be played without being visible on the screen. here is my code <div class="container text-center infinite-container"> {% for video in video_list %} <div class="card text-center mt-5 infinite-item"> <div> {{video.author }} {% if request.session.user == 'gkuer' %} <button class="btn btn-info" onclick="location.href = '{% url 'video:video_delete' video.pk %}'">삭제</button> {% else %} video{{ video.id }} {{ video.pk }} {{ video.self.pk }} {{ video.self.id }} dd {% endif %} </div> <div class="card-header bg-transparent"> <div class="row"> <a class="nav-link navbar-brand text-muted mr-0" href="#"> <h4>{{video.restaurant}}</h4> </a> <a class="nav-link navbar-brand text-muted ml-0 mt-1" href="#"><small>{{video.distance}}km</small></a> <a class="nav-link navbar-brand text-muted ml-auto" href="#">{{video.author}}</a> </li> </div> <div class="row"> <a class="nav-link navbar-brand text-muted mr-0" href="#">{{video.foodname}}</a> <a class="nav-link navbar-brand … -
escaping single quote in csv extract
I'm trying to figure out how to escape a single quote in the extract to csv. The following string: My name's Jimmy shows up as this in my csv My name&#x27;s Jimmy Below is my code from django.template.loader import get_template from django.template import loader response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="prospects.csv"' t = loader.get_template('accounts/prospect_extract.txt') c = {'data': csv_data} response.write(t.render(c)) return response Thanks! -
Write to file using Django?
I'm trying to do what I thought was straightforward but am discovering is not. I'm hosting a webserver locally on a Raspberry Pi using Django and I want to allow the user to browse to the server, type something in a text box and then have that appended to a file sitting on the Pi. So far, I have Django displaying a really basic HTML page, but I can't get it to execute any of the functions in my views file and I also don't know if the easiest route here is to work with a POST request and have some function set up to listen and write the contents of that? -
Inserting data from Mongodb (stored as pandas dataframe) to SQLite db efficiently
I received a pickled dataframe file that had data extracted from a Mongodb collection of hotel information. I needed to add each document to several different models (Hotel, Facilities, Room_facilities etc) in my SQLite database, some of which had a foreign key or many to many relationship such as facilities. What I did was I looped through the dataframe and for each hotel I would create the hotel in the Hotel model, add the other models and link them to the hotel. I don't have the actual code I used anymore but the logic was something like this for each hotel in dataframe: new_hotel = Hotel.objects.create(name=hotel.name, country = hotel.country...) facilities = hotel.facilities.split(',') for i in facilities: try: obj = Facility.objects.get(facility = i) except: obj = Facility.objects.create(facility = i) new_hotel.facility.add(obj) # three more for loops for many to many models. There were around 95,000 rows in the dataframe and this took over an hour to loop through the entire file and populate my database with this data. I ran this on a pretty decent PC (i7, 16gb ram) The code seemed to work but I obviously didn't check all the entries in the SQLite db. I tried looking for a built-in … -
Placing items below category in template
So I wrote a small shopping list application using Django. Users may enter their desired items which are stored in a database alongside a category they reside in to make the list presented to the user more clean and giving them (the users) a good overview of what they are going to buy. The goal is to show the user a list which is categorized, something like this: VEGETABLES Paprika Tomatoes VARIOUS Toothpaste Toilet Paper And so on. I have like five categories saved in my database and users may choose one corresponding category once they add an item to the list below which the item will be displayed in the list. These are my database models: from django.db import models class Category(models.Model): name = models.CharField(max_length=20) tag = models.CharField(max_length=2) def __str__(self): return self.name class Item(models.Model): text = models.CharField(max_length=40) count = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE) complete = models.BooleanField(default=False) def __str__(self): return self.text this is my views.py def items(request): item_list = Item.objects.order_by('id') categories = Category.objects.all() form = ItemForm() context = {'item_list' : item_list, 'form' : form, 'categories' : categories} return render(request, 'buyit/index.html', context) and this is my index.html (very basic, stripped off all the css and html stuff): {% for category … -
TypeError at /admin/newebs/itens/add/1/change/ _getfullpathname: path should be string, bytes or os.PathLike, not list
TypeError at /admin/news/itnews/add/ _getfullpathname: path should be string, bytes or os.PathLike, not list Request Method: POST Request URL: http://localhost:8080/admin/newebs/itens/add/ Django Version: 3.1.6 Exception Type: TypeError Exception Value: _getfullpathname: path should be string, bytes or os.PathLike, not list Exception Location: C:\Program Files (x86)\Python38-32\lib\ntpath.py, line 527, in abspath Python Executable: C:\Djangos\MultWebsites\virtual\Scripts\python.exe Python Version: 3.8.8 Python Path: ['C:\Djangos\MultWebsites\websites', 'C:\Program Files (x86)\Python38-32\python38.zip', 'C:\Program Files (x86)\Python38-32\DLLs', 'C:\Program Files (x86)\Python38-32\lib', 'C:\Program Files (x86)\Python38-32', 'C:\Djangos\MultWebsites\virtual', 'C:\Djangos\MultWebsites\virtual\lib\site-packages'] My problem is in the add in the admin images, I put all the information written there and I put an image from a directory of an application different from the others; this problem happens I've done everything, someone helps me with a solution that I will have no problem saving this information from this application and the others that are in the same project. Here is what the site I build is using STATIC_URL = '/ static /' STATICFILES_DIRS = [os.path.join (BASE_DIR, "static")] STATIC_DIRS = [os.path.join (WEBSITE_DIR, 'static / website' )] MEDIA_URL = '/ website /' MEDIA_ROOT = [os.path.join (WEBSITE_DIR, 'website / media')] - -
form field inline with label using django-crispy-forms
I am using crispy to render my forms, but I got problems rendering a single field inline without affecting the other fields. This form: class SettingsUpdateForm(forms.ModelForm): class Meta: model = User fields = ('about_text', 'github_name') labels = { 'about_text': '', 'github_name': 'github.com/' # TODO make inline with field } widgets = { 'about_text': forms.Textarea(attrs={'placeholder': 'Describe yourself!💯'}), 'github_name': forms.TextInput(attrs={'placeholder': 'your_github_name'}) } help_texts = { 'github_name': 'Showcase a project instead: <em>/username/fav_project</em>', } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper(self) # this is required to display the help_texts renders like this: I want to have the github/ label on the same line with the input field. How do I do that? Horizontal Forms would make all labels be part of bootstraps grid model - which I do not want. I tried to use Inline Forms as well which did not work either. -
Django won't add new field
I have a model that looked like this.. class Property(models.Model): name = models.CharField(max_length=255) description = models.CharField(max_length=512, blank=True) Then I added a field and it looks like this.. class Property(models.Model): name = models.CharField(max_length=255) description = models.CharField(max_length=512, blank=True) spec_link = models.CharField(max_length=512, blank=True) Then I ran python manage.py makemigrations and python manage.py migrate But when I look into the database I am not seeing this field. I am using a postgresql database. -
django dj-rest-auth custom user registration
I'm trying to implement custom registration using dj-rest-auth library. Unfortunately I'm unable to make custom field of user to save. When i try to register I get null constraint failed on year field. I tried saving it by setting user.year and by setting custom_signup class RegisterSerializer(serializers.Serializer): username = serializers.CharField( max_length=40, min_length=3, required=True ) email = serializers.EmailField(required=True) password1 = serializers.CharField(write_only=True) password2 = serializers.CharField(write_only=True) year = serializers.IntegerField(required=True) def validate_username(self, username): username = get_adapter().clean_username(username) return username def validate_email(self, email): email = get_adapter().clean_email(email) if allauth_settings.UNIQUE_EMAIL: if email and email_address_exists(email): raise serializers.ValidationError( _("A user is already registered with this e-mail address.")) return email def validate_password1(self, password): return get_adapter().clean_password(password) def validate(self, data): if data['password1'] != data['password2']: raise serializers.ValidationError(_("The two password fields didn't match.")) return data def custom_signup(self, request, user): user.year = self.validated_data('year', '') user.save(update_fields=['year']) def get_cleaned_data(self): return { 'username': self.validated_data.get('username', ''), 'password1': self.validated_data.get('password1', ''), 'email': self.validated_data.get('email', ''), 'year': self.validated_data.get('year', '') } def save(self, request): adapter = get_adapter() user = adapter.new_user(request) self.cleaned_data = self.get_cleaned_data() adapter.save_user(request, user, self) self.custom_signup(request, user) setup_user_email(request, user, []) return user