Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django rest framework 'NoneType' object is not callable
I am new to django and drf. I've created a viewset for getting list of elements, adding new, updating and deleting, but I have some troubles when I try to create a viewset for getting detailed info about 1 element. Here is my urls.py urlpatterns = [ path('tasks', views.TaskViewset.as_view( { 'get':'list', 'post':'add', 'put':'update', 'delete':'delete' } )), path('tasks/<int:pk>', views.TaskDetailViewset.as_view( { 'get':'detail' } )) ] and here is my TaskDetailViewset from views.py class TaskDetailViewset(viewsets.ViewSet): def detail(self, request, pk, *args, **kwargs): #data = request.query_params task = models.Task.objects.get(id=pk) serializer = serializers.TaskSerializer(task) if serializer.is_valid(): return Response(data=serializer.data, status=status.HTTP_200_OK) return Response(status=status.HTTP_404_NOT_FOUND) When I try to send request to http://127.0.0.1:8000/api/v1/tasks/1 I get 'NoneType' object is not callable and I don't understand where is the problem here -
VSCode showing choosing debugger instead of debug configuration when I try to create a launch.json file of django
I am currently following a tutorial for django and when I try and create a launch.json file through VSCode's debug, it only shows select debugger and prompts me to use Chrome or Edge as options for the debugger. I want to select django at the debug configuration menu, and I am wondering how I would get that to open/ -
django-unicorn resets mounted data after button click
I've built several small apps over the last weeks and stumbled every time over the same problem I couldn't figure out a solution with the docs or a google search. TL;DR I can't keep the results of a queryset initialized inside __init__ or mount() after clicking a button and changing any other value unrelated to the queryset. Is there a way to save/cache the results? Simple Example Initial position components/simple_unicorn.py from django_unicorn.components import UnicornView from any.app.models import MyObject class SimpleUnicornView(UnicornView): # Initialize my sample objects empty as I don't have any filter data, yet objects: MyObject = MyObject.objects.none() # A single filter value - In reality thos are multiple buttons filter_y: str = "" # any variable unrelated to the queryset show_button_x: bool = False def mount(self): self.load_data() def load_data(self): self.objects = MyObject.objects.filter(any_value=self.filter_y) # the execution of this query takes very long def updated_filter_y(self, value): # after changing varables related to the qs it is obvious the reload the data self.load_data() # this is where the problem pops up def toggle_button_x(self): # I'm only changing a variable not connected to the loaded data self.show_button_x = not self.show_button_x # Now I must execute the query again, otherwise self.objects is empty self.load_data() … -
Python regEx won't identify whitespace
I'm trying to replace some keywords in a document using Django Template, but unfortunately i'm dealing with normal user data, so my function receives a dictionary with keys that i'm pretty sure will contain a space. To deal with this risk i'm trying to do this workaround using regEx: from typing import Dict, List from django.template import Context, Template import docx from docxcompose.composer import Composer import re import django from django.conf import settings settings.configure(TEMPLATES=[ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['.'], 'APP_DIRS': False }, ]) django.setup() def combine_documents(documents: List[dict], template_data: Dict): document_paths = [] placeholder = docx.Document() composer = Composer(placeholder) for i in range(len(documents)): document_paths.append(docx.Document(documents[i]["path"])) composer.append(document_paths[i]) composer.doc.add_page_break() context = Context(template_data, autoescape=False) document = composer.doc pattern = re.compile(r"\{{[\s\S]*\}}", re.IGNORECASE) for paragraph in document.paragraphs: for word in paragraph.text.split(): matches = pattern.finditer(word) # print(word) for match in matches: print(match.group()) if " " in match.group() and match.group() == word: print(match.group()) print("it's here") paragraph.text = paragraph.text.replace(" ", "_") template = Template(paragraph.text) print(template.render(context)) return "Ok!" combine_documents(documents = [{ "title": "Titulo", "path": "libs/plugins/signature/signature_providers/documents/Contrato de Prestação de Serviço - Exemplo.docx" }, { "title": "Outro título", "path": "libs/plugins/signature/signature_providers/documents/Contrato de Prestação de Serviço - Exemplo.docx" }], template_data={"Empresa": "FakeCompany", "Endereço Completo": "Rua 1", "Cidade": "São Paulo", "Estado": "São Paulo", "CEP": "12345678", "CNPJ": "317637667-0001", … -
Getting forbidden error when fetching endpoint when logged into account
Using React for the frontend and Django for the backend. I have a page in my website that displays all the user settings. When they load the page it fetches the data from the backend and fills out the form, when they submit the updated form it posts it to the backend. When I go to post this data when I'm logged into an account it gives me a forbidden error but when I'm logged out and post the form it goes through. Why would it be doing this? react post const onSubmit = async (e) => { e.preventDefault() const res = await fetch('/api/account/updatesettings', { method: "POST", headers: { 'Content-type': 'application/json' }, body: JSON.stringify({ "test": "test" }) }) const data = await res.json() } api endpoint: class UpdateSettings(APIView): serializer_class = AccountSettingsSerializer def post(self, request, format=None): print("test") serializer = self.serializer_class(data=request.data) print(serializer.data) if serializer.is_valid(): pass -
Transcribe Streams of Audio Data in Real-Time with Python
I developed a web app using Django as a backend and a Frontend library. I have used django-channels, for WebSocket and I am able to record the audio stream from the front end and send it to Django over WebSocket and then Django sends it to the group. So I'm able to do live audio calls (let's say) but I have to transcribe the audio at the backend. (the main goal of the project) Things I'm looking forward to use this package to achieve transcription. I send base64 encoded opus codecs string from the front end to Django every second. It sends recorded audio every 1 second. My doubts - If we play Audio streams independently, we are only able to play the first string. We are not able to play 2nd, 3rd .... independently (padding issues or maybe more I'm not aware of), so I have used MediaSource at front end to buffer the streams and play. The question is can we convert this 2nd 3rd audio stream into text using the above-mentioned package? or I will have to do something else. (I'm looking for ideas here on how will this work) Also, the above-mentioned package uses a wav … -
Django click confirm pop then call function in views.py
I have a Django project ,now after clicking the url ,it will directly trigger the function in veiws.py. But I now want to add a JavaScript or bootstrap pop window, inside the window there is 2 buttons ,cancel or confirm, only when confirm button has been clicked ,the function in views.py will be called ,otherwise if cancel is clicked, just return to pervious page. url: path('wLoadr/', wLoadr_func, name='wLoadr_func'), template html: <li><a class="dropdown-item" href="{% url 'wLoadr_func' %}">wLoadr</a></li> views.py: def wLoadr_func(request): # there are some wLoadr_func code here .....omit code return render(request, 'wLoadr/wLoadr_base.html') Any friend can help ? -
Django Form fields disappearing after redirect to login page
I am using a Django form for a user login page. When the user has an incorrect login, it goes back to the login page. However, when it does this, the form input fields are gone, and the user can't enter anything, because the inputs just... aren't there. Note that it displays and functions correctly when I click on the login button in the navbar that goes to "\login". It's just after the postlogin view is run that the inputs disappear. After I run the postlogin view, it looks like this: what it looks like after I redirect to the login page It's supposed to look like this: what it is supposed to look like Here is my login and my post login view: def login(request): # Rendering login page assert isinstance(request, HttpRequest) return render( request, 'app/login.html', { 'title': 'Login', 'message': 'Login to your account', 'year': datetime.now().year, 'form':form } ) def postlogin(request): email=request.POST.get('email') pasw=request.POST.get('password') try: # if there is no error then signin the user with given email and password user = authe.sign_in_with_email_and_password(email, pasw) except: message="Invalid credentials!" # return to login page if password and email was invalid return render(request,"app/login.html", {'message':message, 'current_user': authe.current_user}) # set current session with user token … -
How do i pre-populate Django ModelForm fields
This form requires a student to login before filling it out. I want the input field with placeholder Enter Your Username to be pre-populated with the username of the individual filling it out. Here is my models.py class User_detail(models.Model): username = models.CharField(max_length=255, default="") first_name = models.CharField(max_length=255, default="") last_name = models.CharField(max_length=255, default="") email = models.EmailField(max_length=255, default="") date_of_birth = models.DateField(null=False, blank=False, default="") gender = models.CharField(max_length=50, choices=GENDER, default="") tel = PhoneNumberField() def __str__(self): return self.email Here is my views.py from django.contrib.auth.decorators import login_required from .forms import * def signin(request): if request.user.is_authenticated: return redirect(profile) if request.method == "POST": form = Signin(request.POST) if form.is_valid(): username = request.POST["username"] password = request.POST["password"] user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return redirect("profile") else: messages.error(request, "Invalid credentials") return redirect("signin") else: form = Signin() return render(request, "accounts/login.html", {"form": form}) @login_required(login_url="signin") def user(request): if request.method == "POST": form = Userdetail(request.POST) if form.is_valid(): user = form.save(commit=False) user.save() messages.success(request, "You Have Successfully updated your details") return render(request, "thanks.html") else: form = Userdetail() return render(request, "accounts/User details.html", {"form": form}) Here is my Forms.py class Signin(forms.Form): username = forms.CharField( max_length=255, widget=forms.TextInput(attrs={"placeholder": "Enter Your Userame"}), ) password = forms.CharField( max_length=255, widget=forms.PasswordInput( attrs={"placeholder": "Enter Your Password", "id": "password"} ), ) class Userdetail(forms.ModelForm): class … -
Export data as excel from class based view
I have class based view and when request is post, self.readdb() will give dictionary result to self.db_result variable which will be populated as html table. This is working fine. I need to export this table as excel. My view.py class Download(View): def __init__(self, logger=None, **kwargs): self.logger = logging.getLogger(__name__) self.db_result = [] def post(self, request): if request.method == 'POST': form = DownloadForm(request.POST, request.FILES) if form.is_valid(): self.db_result = self.readdb() if self.db_result != False: return render(request,'download.html',{'present': self.db_result[0]}) <table class="presenttb"> <caption>Present in DB</caption> <tbody> {% for key, value in present.items %} <tr> <td> {{ key }} </td> <td> {{ value }} </td> </tr> {% endfor %} </tbody> <a href="{% url 'export_excel' %}">Download excel file</a> </table> {% endif %} I tried following which is generating excel file when click but it doesn't have any data. print(self.db_result) in get function is printing []. Looks like result from "post" is not available in "get". def get(self, request): if request.method == 'GET': if request.path_info == '/export/excel': print(self.db_result) response = self.export_users_xls() return response def export_users_xls(self): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachement; filename="report.csv"' print(self.db_result) writer = csv.writer(response) writer.writerow(['Command', 'XML data']) return response How can I access self.db_result from "post" function in "get" so that I can generate excel file. If … -
Output Blog Posts on Profile w/ Python & Django
I've been trying to output a specific user's blog posts to their profile page and can't seem to figure it out. I'm relatively new to Django and have yet to see an entry here with class-based views. Here is what I have so far: views.py class ProfilePageView(DetailView): model = Profile template_name = 'registration/user_profile.html' def get_context_data(self, *args, **kwargs): #users = Profile.objects.all() user_posts = blogPost.objects.filter(author=self.request.user) page_user = get_object_or_404(Profile, id=self.kwargs['pk']) context = super(ProfilePageView, self).get_context_data(*args, **kwargs) context["page_user"] = page_user return context models.py class Profile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) bio = models.TextField() profile_pic = models.ImageField(blank=True, null=True, upload_to='images/profile/') twitter_url = models.CharField(max_length=255, null=True, blank=True) linkedIn_url = models.CharField(max_length=255, null=True, blank=True) github_url = models.CharField(max_length=255, null=True, blank=True) def __str__(self): return str(self.user) def get_absolute_url(self): #return reverse("details", args=(str(self.id))) return reverse('home') -
How to tell if the current user is authenticated in Firebase using Django
I'm using Django with Pyrebase to access Firebase for authentication and logins. I'm new to all of them so bear with me. I think I am able to successfully log the user in, but at that point I can't figure out how to change the html file to only show certain parts if the user is logged in. I've tried {% if user.is_authenticated %} as well as {% if current_user.is_authenticated %} as well as {% request.user.is_authenticated %} and {% request.current_user.is_authenticated %} but all of them act as if they've returned false even though the user is authenticated via user = authe.sign_in_with_email_and_password(email, password). Here's my views.py: def login(request): # Rendering login page assert isinstance(request, HttpRequest) return render( request, 'app/login.html', { 'title': 'Login', 'message': 'Login to your account', 'year': datetime.now().year } ) def postlogin(request): email=request.POST.get('username') password=request.POST.get('password') try: # if there is no error then log in the user with given email and password user = authe.sign_in_with_email_and_password(email, password) except: message="Invalid credentials." print("invalid") return render(request,"app/login.html",{'message':message }) session_id=user['idToken'] request.session['uid']=str(session_id) return render(request,"app/home.html",{"email":email}) And my login.html: {% if request.current_user.is_authenticated %} <form id="logoutForm" action="/logout/" method="post" class="navbar-right"> {% csrf_token %} <ul class="nav navbar-nav navbar-right"> <li><span class="navbar-brand">Hello {{ user.username }}!</span></li> <li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li> </ul> </form> {% else %} <ul class="nav … -
(Django) Can't Update Post On My Blog (function based view)
After displaying my posts, I don't manage to Edit any of them. When I print the instance variable which is in views.py in my terminal, it displays only the title and the author like this title - author, which is the method defined in models.py. Help please! Views.py @login_required(login_url='login_view') def update_post_view(request, post_id, slug=None): instance = Article.objects.get(id = post_id) if request.method == 'POST': form = UpdatePostForm(request.POST, request.FILES, instance=instance) if form.is_valid(): form.save() return redirect('posts_view') else: form = UpdatePostForm(instance=instance) return render(request,'update_post.html', {'form':form}) forms.py class UpdatePostForm(forms.ModelForm): class Meta: model = Article fields = ('author',) title = forms.CharField(max_length=255, label='username', widget= forms.TextInput(attrs= {'placeholder':'Title...', 'class': 'title'})) body = forms.CharField(max_length=255, label='body', required=True, widget=forms.Textarea(attrs={'placeholder':'Start writing your post...'})) urls.py path('update_post/<int:post_id>/<slug:slug>', views.update_post_view, name='update_post_view') update_post.html {% extends 'base.html' %} {% block title %}Update Post{% endblock %} {% block content %} <h2>Update Posts...</h2> <form action="" method="POST"> {% csrf_token %} <div> <h3>{{form.title}}</h3> <small>{{form.author}}</small> <p>{{form.body}}</p> </div> <button class="btn btn-secondary">Update</button> </form> {% endblock %} -
TemplateDoesNotExist at / template not defined
I have tried to set-up my first simple CBV in Django but despite reading literally all related information and trying out all possible path options to my index.html I receive the same message from above. Last version follows: Python-Version: 3.9.13 Django: 4.1 **urls.py** from django.urls import path from core.views import Servicelist urlpatterns = [ path('', Servicelist.as_view(), name='service') ] **views.py** from core.models import Item from django.views.generic.list import ListView class Servicelist(ListView): model = Item template_name:'paraticosmetics/index.html' context_object_name = "items" I receive message that index is not defined Pylance(reportundefinedVariable) **setting.py** **setting.py** INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'core.apps.CoreConfig', ] TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [BASE_DIR/'core/templates/paraticosmetics/'], "APP_DIRS": True, .... -
Django Folium Marker
I am newbie and I am making a map visualization in Django. I will use both heatmap and marker on my website. I have not encountered any error in my heat map but when I put on the folium markers, I encountered an error in the markers: 'tuple' object is not callable. How can this be fix? Is there a way? Views def index(request): data = IncidentGeneral.objects.all() data_list = IncidentGeneral.objects.values_list('user_report__latitude', 'user_report__longitude', 'accident_factor') address = IncidentGeneral.objects.values('user_report__address') latitude = IncidentGeneral.objects.values('user_report__latitude') longitude = IncidentGeneral.objects.values('user_report__longitude') coordenadas = list(IncidentGeneral.objects.values_list('user_report__latitude','user_report__longitude'))[-1] map1 = folium.Map(location=[14.676208, 121.043861], tiles='CartoDB Dark_Matter', zoom_start=12) plugins.HeatMap(data_list).add_to(map1) plugins.Fullscreen(position='topright').add_to(map1) # folium.Marker(tooltip = 'Click for more', popup=address).add_to(map1) # map1.add_child(folium.Marker(location=[latitude, longitude],popup="Hi I am a Marker",icon=folium.Icon(color="green"))) for id,row in coordenadas(): folium.Marker(location=[row['latitude'],row['longitude']], popup=row['Confirmed']).add_to(map1) # folium.Marker(coordenadas).add_to(map1) map1 = map1._repr_html_() context = { 'map1': map1 } return render(request, 'index.html', context) Models class IncidentGeneral(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, editable=False, null=True, blank=True) user_report = models.OneToOneField(UserReport, on_delete=models.CASCADE) accident_factor = models.ForeignKey(AccidentCausation, on_delete=models.SET_NULL, blank=True, null=True) accident_subcategory = models.ForeignKey(AccidentCausationSub, on_delete=models.SET_NULL, blank=True, null=True) collision_type = models.ForeignKey(CollisionType, on_delete=models.SET_NULL, blank=True, null=True) collision_subcategory = models.ForeignKey(CollisionTypeSub, on_delete=models.SET_NULL, blank=True, null=True) crash_type = models.ForeignKey(CrashType, on_delete=models.SET_NULL, blank=True, null=True) weather = models.PositiveSmallIntegerField(choices=WEATHER, blank=True, null=True) light = models.PositiveSmallIntegerField(choices=LIGHT, blank=True, null=True) severity = models.PositiveSmallIntegerField(choices=SEVERITY, blank=True, null=True) movement_code = models.CharField(max_length=250, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class UserReport(models.Model): PENDING … -
Django DeleteView only works on second attempt
Bit of a strange one and wondering if anyone else here has come across this. I have a standard DeleteView with the GET showing a confirmation page containing a form that posts to the delete view. Whenever I click confirm nothing happens - the post to the view occurs and it redirects as intended, however the object is not deleted. If I then perform the action a second time the object is deleted. class MetricDeleteView(DeleteView): template_name = "dashboard/administration/metric/delete.html" button_title = "Update metric" form_class = MetricUpdateForm model = dashboard_metric # Override post to test manually delete object but same thing happens def post(self, request, *args, **kwargs): self.object = self.get_object() success_url = self.get_success_url() print(self.object) self.object.delete() return HttpResponseRedirect(success_url) @cached_property def dashboard_score(self): return self.get_object().score def get_success_url(self): return reverse_lazy("administration:dashboard:update_score", kwargs={ 'dashboard': self.dashboard_score.dashboard.id, 'pk': self.dashboard_score.id }) I can't for the life of me figure out why this is occurring across all some models on my site. -
How to access key values of ordered dict in django serializer query
I work with Django-Rest api and have serializer that returns me the data like this my_ordered = [OrderedDict([('idx', '1231233'), ('rock', None), ('Email', 'albundy@abc.com')]), OrderedDict([('idx', '1212333'), ('paper', None), ('Email', 'peggybundy@abc.com')])] type(my_ordered) <class 'collections.OrderedDict'> I tried to access its 'Email' key like this for trainer, training in my_ordered.items(): print(training['Email']) NameError: name 'OrderedDict' is not defined Also tried import collections my_ordered = [collections.OrderedDict([('idx', '1231233'), ('rock', None), ('Email', 'albundy@abc.com')]), collections.OrderedDict([('idx', '1212333'), ('paper', None), ('Email', 'peggybundy@abc.com')])] #my_ordered.keys()[2] for trainer, training in my_ordered.items(): print(training['Email']) my_ordered.keys()[2] AttributeError: 'list' object has no attribute 'items' but this also not helped. How to access key values in ordered dictionary -
Is it possible to use import_export Django lib to export data from more than one table in a same xls doc?
class OrderResource(resources.ModelResource): class Meta: model = Order class PaymentOrderAdmin( ImportExportMixin, admin.ModelAdmin): resource_class = OrderResource -
Using Django Template Tags in Markdown
I am using Markdown to format/style my blog posts in Django. The problem is that the Django template tags in Markdown don't seem to work for me. More details: Markdown module: Markdown==3.2.1 details.html (my blog posts template file) {% block content %} ... </p> {{ post.body|markdown }} <p> ... {% endblock %} Next, in the body of my blog post, I tried to add an HTML tag that includes a django template tag: <img src="{% static '/img/image.jpg' %}" alt="image"> and I see this in the result: Any ideas what I'm doing wrong? -
Django: can I save a model from two modelforms?
I decided to organize my page using two separated forms to build a single model: class MandateForm1(forms.ModelForm): class Meta: model = Mandate fields = ("field_a", "field_b"), class MandateForm2(forms.ModelForm): class Meta: model = Mandate fields = ("field_c", "field_d"), In my view, I would get something like: form_1 = MandateForm1(request.POST) form_2 = MandateForm2(request.POST) This way, how can I create my model using Form save() method? As a current workaround, I'm using Mandate.objects.create(**form_1.cleaned_data, **form_2.cleaned_data). The drawback is I need to handle M2M manually with this method. Thanks. -
How can I sort my Django Rest Framework results?
I have tried doing this with dynamic-rest and couldn't get it to work, now I am trying with the built in ordering method in django rest-framework, still can't get it to work. I have a feeling it is the method I am using get get these results from the database, but I do not know of any other way, so if anyone knows how to get this working, in any way, please let me know, thank you! models.py class Notifications(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateTimeField('date transacted') read = models.BooleanField(default=False) message = models.CharField(max_length=300) views.py class getnotifications(viewsets.ModelViewSet): # Database model queryset = User.objects.all() # Serializer - this performs the actions on the queried database entry serializer_class = NotificationsSerializer # What field in database model will be used to search lookup_field = 'username' filter_backends = [filters.OrderingFilter] ordering_fields = ['notifications'] ordering = ['notifications'] I have tried setting ordering/ordering_fields to notifications_set.pk, this does not work either. serializers.py class NotificationsSerializer(serializers.ModelSerializer): notifications_set = ListNotificationsSerializer(many=True) class Meta: model = User fields = ['notifications_set'] class ListNotificationsSerializer(serializers.ModelSerializer): class Meta: model=Notifications name='notifications_set' fields=['pk','date','read','message'] This does not work with a default ordering specified (with ordering flag in view), or with ?ordering=field in the GET request -
How to test delete instance in Django
Running Django, I have a view to delete logged-in user on POST request. @login_required def delete_user(request): """Delete user from DB.""" if request.method == "POST": get_object_or_404(User, pk=request.user.pk).delete() messages.success(request, _("User deleted!"), extra_tags="success") return redirect("home") return render(request, "accounts/delete-user.html") HTML form is: <form method="POST" name="delete-user-form" id="delete-user-form"> {% csrf_token %} <button class="mt-4 btn btn-danger" name="delete-user-btn" id="delete-user-btn" type="submit">{% translate "Delete my profile" %}</button> </form> My test class with user: class ViewsWithLoggedInUserTest(TestCase): @classmethod def setUpClass(cls): super().setUpClass() User.objects.create_user( email="test@test.com", password="test", first_name="TestFirstName", last_name="TestLastName", hometown="Kiev", facebook_link="https://www.facebook.com/profile.php?id=1000", contacts="+380991111111", start_coordinates="50.45, 30.52", avatar="avatar/default_avatar.jpg", ) def setUp(self): self.user = User.objects.get(email="test@test.com") self.client.force_login(user=self.user) print("setUp") def test_delete_user_post(self): """Test delete user post.""" response = self.client.post(path=reverse("delete_user")) self.assertFalse(self.user) self.assertEqual(response.status_code, 302) self.assertRedirects(response, expected_url=reverse("home")) I can not undrstand how to test this function, my test_delete_user_post gives me AssertionError: <User: test@test.com> is not false -
Django/Wagtail How to get multiline help_text
When working in the admin portal I have found a way to get multi-line help text. It took a long time to find this answer so I figured I would post about it for others to fine. The secret is the mark_safe from django.utils.safestring import mark_safe item = models.IntegerField(blank=True, null=True, help_text=mark_safe('Line 1 <br />Line 2)) -
How to run django server from docker in wsl? Error in absolute path
enter image description here For the first time I'm trying to set up my project on win 10. I have set these settings for my django server, which uses an interpreter from docker running on ubuntu. After the launch, I received an error message. \\wsl$\Ubuntu\home\alexander\work\integrationservice: "\\\\wsl$\\Ubuntu\\home\\alexander\\work\\integrationservice" includes invalid characters for a local volume name, only "[a-zA-Z0-9][a-zA-Z0-9_.-]" are allowed. If you intended to pass a host directory, use absolute path How to solve this problem? -
How to change the user details in Django
I am making a Django project where users can sign up, sign in, view their profile and change it if they want to. I want to know how to implement the functionality of a user changing their profile? Here is my user form in forms.py class CustomerForm(forms.Form): username = forms.CharField(label='Desired Username', max_length=150, validators=[validate_username]) first_name = forms.CharField(label='First Name', max_length=150) last_name = forms.CharField(label='Last Name', max_length=150) email = forms.EmailField(label='Your Email', validators=[validate_email]) password1 = forms.CharField(label='Enter Password', widget=forms.PasswordInput, min_length=8) password2 = forms.CharField(label='Retype Password', widget=forms.PasswordInput, min_length=8) def clean(self): cleaned_data = super().clean() password1 = cleaned_data.get("password1") password2 = cleaned_data.get("password2") if password1 != password2: raise ValidationError( "Passwords do not match" ) Here is my sign-up method in views.py """Function for sign up.""" def sign_up(request): if request.method == 'POST': form = CustomerForm(request. POST) if form.is_valid(): try: user = User.objects.create_user( request.POST['username'], request.POST['email'], request.POST['password1'] ) user.first_name = request.POST['first_name'] user.last_name = request.POST['last_name'] user.save() request.session['normal_username'] = request.POST['username'] login(request, user) return redirect('../book/') except Exception: return HttpResponse("Something went wrong. Please try again.") else: context = {'form': form} return render(request, 'sign_up.html', context) context = {'form': CustomerForm()} return render(request, 'sign_up.html', context) Any help will be appreciated.