Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'user' field keeps getting nulled
I want to create something where the current logged user can create 'posts'. Here's my codes: models.py from django.contrib.auth.models import User # Posts class Post(models.Model): user = models.ForeignKey(User) date = models.DateField(auto_now_add=True) content = models.TextField(max_length=500, blank=False) forms.py class PostForm(forms.ModelForm): class Meta: model = models.Post labels = { 'content': '' } widgets = { 'user': forms.HiddenInput() } fields = '__all__' # exclude = ('user',) views.py def my_profile(request): user = request.user profile_info = request.user.userprofileinfo if request.method == 'POST': post = forms.PostForm(data=request.POST) if post.is_valid(): post.save(commit=False) post.user = user post.save(commit=True) return HttpResponseRedirect(reverse('td_app:index')) else: print(post.errors) return HttpResponseRedirect(reverse('td_app:my_profile')) else: form = forms.PostForm data = { 'user': user, 'profile_info': profile_info, 'form': form } return render(request, 'td_app/my_profile.html', context=data) I have declared the 'user' field to be 'hidden' since we don't want users pretending to be someone else when they post - the 'user' field should automatically register the current logged user. However it keeps giving me this error: <ul class="errorlist"><li>user<ul class="errorlist"><li>This field is required.</li></ul></li></ul> When I do this instead: class PostForm(forms.ModelForm): class Meta: model = models.Post labels = { 'content': '' } # widgets = { # 'user': forms.HiddenInput() # } fields = '__all__' exclude = ('user',) It will now give me a null error: The above exception (null … -
Finding unique query values when using Django/Python
Hey guys I'm trying to print out a page with all the available categories of an auction site on it. Right now it's printing out every instance of whats in the table. For instance, there are multiple print outs of Animals as a category - but I just want it to show one. What's the best way to do this? I tried the "distinct" method but it doesn't seem to be doing anything. Below is my relevant code: views.py: def categories(request): query = NewPost.objects.all().distinct() return render(request, "auctions/categories.html", { "queries": query }) categories.html: {% extends "auctions/layout.html" %} {% block body %} <h2>Categories</h2> {% for query in queries %} <li><a href="/categories/{{ query.category }}">{{ query.category }}</a></li> {% endfor %} {% endblock %} -
'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte
I'm trying to mock an image for the test case scenario where a user uploads a photo. Upon trying to create it, I'm getting the error: UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte I have followed the following topics to do the very such thing but I'm still getting this error. Unit Testing a Django Form with a FileField Django testing model with ImageField. How can remedy this so that I get a working mock image for my test? class RedundantImageUpload(TestCase): @classmethod def setUpTestData(cls): f = BytesIO() image = Image.new("RGB", (100, 100)) image.save(f, 'png') f.seek(0) test_image = SimpleUploadedFile( "test_image.png", content=open(f.read(), 'rb'), content_type="image/png" ) user = User.objects.create_user("User") import pdb; pdb.set_trace() form = PhotoForm({'title': "Image Title"}, {'source': test_image}) instance = form.save(commit=False) instance.photographer = user instance.save() cls.submitted_form = PhotoForm( {'title': "Image Title"}, {'source': test_image} ) def test_image_upload_path_exists(self): print(self.submitted_form.errors) -
Django redirect to external link with parrameters
everyone. I have problem with redirection. I have urls: path('some/<int:pk>/', RedirectView.as_view(), name='redirect'), My target is: in RedirectView I have to get pk, take it and pass to 'url' variable inside view: class RedirectView(RedirectView): ? any_url = Model2.objects.filter(name='something') ? link = any_url.name ? any_url.save() ? url = link + <int:pk> ? redirect to url I mean, I have to take pk from url and attach it to external link, that I got from db. pk is id from Model_1. external url is any_url I take from Model_2, it was saved like CharField. Also, when I take url address from db I need resave this instance. I understand how it works if I make redirect inside project (thru pattern_name). Could you help me? -
Why DB dont save comment(Django)
The entered comments in the form are not saved in the database, and are not displayed anywhere. After clicking the save button, it simply redirects to another page and the comments are not displayed. I'm trying to make a form for entering comments directly from the site page, I have already configured it from the administration panel. Thanks! models.py class BarbersPage(ListView): model = Post template_name = 'main/barbers.html' context_object_name = 'posts' def post_new(request): post = get_object_or_404(Post) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): form.save() return redirect('barbers') else: form = CommentForm() return render(request, 'main/post_detail.html', {'form': form}) views.py class BarbersPage(ListView): model = Post template_name = 'main/barbers.html' context_object_name = 'posts' def post_new(request): post = get_object_or_404(Post) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): form.save() return redirect('barbers') else: form = CommentForm() return render(request, 'main/post_detail.html', {'form': form}) barbers.html {% for post in posts %} <img src="{{MEDIA_URL}}{{post.photo.url}}" width="800" /> <h3> {{ post.name_barber}} </h3> <p>{{ post.description}}</p> <h3> Comments.. </h3> {% if not post.comments.all %} no comments yet...<a href = "#">Add one</a> {% else %} {% for comment in post.comments.all %} <strong> {{ comment.name }} {{ comment.add_date }} </strong> <p>{{comment.body }}</p> {% endfor %} {% endif %} {% endfor %} post_detail.html <h1>New comment</h1> <form method="POST" class="post-form">{% … -
How to avoid the COUNT query Django's paginator does?
Paginator.page() causes the evaluation of the cached property count, which performs a COUNT query on the database. My problem is that the average query execution time for that COUNT is 1.06 seconds while the average time of the main query is 1.04 seconds. In effect I have a duplicated query. Is there a way to avoid that COUNT query? -
How can I include a python module in order to run a server on django?
I'm very new to coding python, and I'm following a tutorial on django for creating a simple website: < https://docs.djangoproject.com/en/3.1/intro/tutorial01/ > The problem I'm encountering is when I attempt to execute 'manage.py runserver'. I receive a "Module not found" error for my 'urls.py' file. This sort of makes sense as I created the file myself because I needed to, whereas the rest were automatically generated. Does anyone know of any way I can fix this error, and get the 'urls.py' file on the path or make it accessible? If any extra information is needed I can try to provide it. -
Comments aren't printing out on my Django Python site
Hey guys I'm making an auction site and I'm having trouble with the comments for some reason. I'm not getting an error when I add a new comment but when I try to print out the results, I'm getting nothing - no errors - just nothing. When I do a query in my view for Comments.objects.all() and try to print it to the terminal, I'm getting nothing printed out. I'm thinking perhaps it's something to do with the action in the form? Or the urls.py? Anyone see why? I provided relevant code - please let me know if you need any more. Thanks! urls.py: from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("auction", views.auction, name="auction"), path("watchlist/<str:username>", views.watchlist, name="watchlist"), path("categories", views.categories, name="categories"), path("post/<str:title><str:description><int:price><str:category>", views.post, name="post"), path("bid/<str:username>", views.bid, name="bid"), path("comment", views.post, name="comment"), path("closeAuction", views.closeAuction, name="closeAuction") ] views.py: def comment(request): username = request.POST.get("username") itemID = request.POST.get("itemID") comment = request.POST.get("comment") new = Comment.objects.create(username = username, comment = comment, itemID = itemID) new.save() commentQuery = Comment.objects.all() print(commentQuery) return render(request, "auctions/post.html", { "commentQuery": commentQuery}) models.py: class Comment(models.Model): username = models.CharField(max_length=64) comment = models.CharField(max_length=64) itemID = models.CharField(max_length=64) post.html: <form name="comment" action="/post/{{p.title}}{{p.price}}" method="post"> … -
Pythin Django - Disply result in html page one after each other
Python - Django def integration(request): 1. pushing config to the device 2. checking the config 3. update database with new status The function above run three tasks. How can I display the result in the html page after each result done. Now it work perfectly but I need to wait until all tasks done to see the result in the html page. Thanks, -
Adding a Condition in Payment System to include PayPal
I am trying to integrate PayPal to my E-commerce Project, so the flow of the checkout process is as following after adding items to cart: In the checkout page the user types the address and select the payment option through a radio button Now when the user selects the stripe it directs to core:payment in this template I am trying to add a condition so that if the selected payment option is paypal the paypal icons is appearing instead of the stripe payment form. Here is the models.py class Payment(models.Model): stripe_charge_id = models.CharField(max_length=50) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, blank=True, null=True) amount = models.FloatField() timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.user.username Here is the views.py class CheckoutView(View): def get(self, *args, **kwargs): try: order = Order.objects.get(user=self.request.user, ordered=False) form = CheckoutForm() context = { 'form': form, 'couponform': CouponForm(), 'order': order, 'DISPLAY_COUPON_FORM': True } -----------------Shipping address codes----------------------------- payment_option = form.cleaned_data.get('payment_option') if payment_option == 'S': return redirect('core:payment', payment_option='stripe') elif payment_option == 'P': return redirect('core:payment', payment_option='paypal') else: messages.warning( self.request, "Invalid payment option selected") return redirect('core:checkout') except ObjectDoesNotExist: messages.warning(self.request, "You do not have an active order") return redirect("core:order-summary") here is the url.py urlpatterns = [ path('payment/<payment_option>/', PaymentView.as_view(), name='payment'), here is the template <!------------Add an if statmenet if the … -
django-compressor Uncaught SyntaxError: import declarations may only appear at top level of a module
This is my JS structure: This is the beginning index.js import { elements } from './views/base'; const state = {}; const controlRandomPhrasal = async () => {} My base.js: export const elements = { searchFrom: document.querySelector('.search'), } I invoke the compressor like this: {% compress js %} <script src="{% static "phrasals/js/jquery.js" %}"></script> <script src="{% static "phrasals/js/index.js" %}"></script> {% endcompress %} How can I configure my project to avoid that error? Or can you suggest me an easier/better bundler? -
With Django, how do you update a value with the click of a button in a template?
In my app, "employees" can be assigned to different "supervisors". The html template for an individual employee page contains a list of all available supervisors. I want to put a button next to each supervisor in the list so that when you click the button, the employee.assigned_supervisor value is updated. Even once a supervisor is assigned, I'd like to be able to change which supervisor is assigned by clicking a button next to a different supervisor in the list. I've combed through the documentation and lots of other sites/examples, and all I've been able to find is examples of forms where you visit a separate page, complete/update the form, and submit. I want to update the value just by clicking the button. I'm using Django 3.1. models.py class Supervisor(models.Model): name = models.CharField(max_length=30) class Employee(models.Model): name = models.CharField(max_length=30) assigned_supervisor = models.ForeignKey(Supervisor) forms.py class EmployeeForm(forms.ModelForm): class Meta: model = Employee fields = ['name', 'assigned_supervisor'] views.py def new_employee(request): if request.method != 'POST': form = EmployeeForm() else: form = EmployeeForm(data=request.POST) if form.is_valid(): form.save() return redirect('my_app:employees') context = {'form': form} return render(request, 'schedules/new_employee.html', context) employee.html <p>Employee: {{ employee }}</p> <p>Available Supervisors:</p> <li> {% for supervisor in supervisors %} <li>{{ supervisor }}</li> <!-- Insert "Assign" button … -
AttributeError at / 'list' object has no attribute 'values'
I am new to django and trying to build social network system. Here in my view I am importing my friend list using profile variable. Now I want to show post only from my friends. but cant make the logic for how to filter through all the post. this is the view: @login_required def post_comment_create_and_list_view(request): profile = Profile.objects.select_related('user').get(user=request.user).get_all_friends_list() #profile contains list of the friends i have queryset = Post.objects.all_posts().filter(author__icontains=profile.values()) #post form post_form = PostModelForm() if 'submit_p_form' in request.POST: post_form = PostModelForm(request.POST or None, request.FILES or None) if post_form.is_valid(): instance = post_form.save(commit=False) instance.author = profile instance.save() post_form = PostModelForm() messages.success(request, 'Post published') return redirect('posts:main_post_list') #comment form comment_form = CommentModelForm() if 'submit_c_form' in request.POST: comment_form = CommentModelForm(request.POST or None) if comment_form.is_valid(): instance = comment_form.save(commit=False) instance.user = profile post_id = request.POST.get('post_id') instance.post = Post.objects.get(id=post_id) instance.save() comment_form = CommentModelForm() return redirect('posts:main_post_list') context = { 'queryset': queryset, 'profile': profile, 'post_form': post_form, 'comment_form': comment_form, } return render(request, 'posts/main.html', context) this is the post model: class PostManager(models.Manager): def all_posts(self): posts = Post.objects.prefetch_related('author',"comment_posted__user", "comment_posted__user__user",'likes') return posts class Post(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True, db_index=True) content = models.TextField(db_index=True) image = models.ImageField(upload_to='posts', validators=[FileExtensionValidator(['png', 'jpg', 'jpeg'])], blank=True) likes = models.ManyToManyField(Profile, blank=True, related_name='profile_liked') updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(Profile, on_delete=models.CASCADE, … -
Django: Integrating PayPal to payment options
Helloo, I need guidance on how to integrate PayPal radio buttons to replace my Django Radio buttons for the found in the below link https://developer.paypal.com/demo/checkout/#/pattern/radio I have set my payment options in the forms.py and I am stuck and don't know how to proceed The stripe payment method is working perfectly fine I just want to add the PayPal payment option. This is how my project is arranged: Forms.py PAYMENT_CHOICES = ( ('S', 'Stripe'), ('P', 'Paypal') ) class CheckoutForm(forms.Form): ----address related forms----------------------------------- payment_option = forms.ChoiceField( widget=forms.RadioSelect, choices=PAYMENT_CHOICES) Here is the checokout template <h3>Payment option</h3> <div class="d-block my-3"> {% for value, name in form.fields.payment_option.choices %} <div class="custom-control custom-radio"> <input id="{{ name }}" name="payment_option" value="{{ value }}" type="radio" class="custom-control-input" required> <label class="custom-control-label" for="{{ name }}">{{ name }}</label> </div> {% endfor %} </div> here is the views.py class CheckoutView(View): def get(self, *args, **kwargs): try: order = Order.objects.get(user=self.request.user, ordered=False) form = CheckoutForm() context = { 'form': form, 'couponform': CouponForm(), 'order': order, 'DISPLAY_COUPON_FORM': True } -----------------Shipping address codes----------------------------- payment_option = form.cleaned_data.get('payment_option') if payment_option == 'S': return redirect('core:payment', payment_option='stripe') elif payment_option == 'P': return redirect('core:payment', payment_option='paypal') else: messages.warning( self.request, "Invalid payment option selected") return redirect('core:checkout') except ObjectDoesNotExist: messages.warning(self.request, "You do not have an active order") return … -
Django (Password_change) doesn't work url
I'm learning Django book named by (Django for beginners) I have a problem with password _change Below my code from urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('',include('pages.urls')), path('admin/', admin.site.urls), path('users/', include('users.urls')), path('users/',include('django.contrib.auth.urls')), ] Next is password_change_form.html {% extends 'base.html' %} {% block title %} Password Change {% endblock %} {% block content %} <h1>Password change</h1> <p>Please enter your old password, for security's sake, and then enter your new password twice so we can verify you typed it in correctly.</p> <form method="POST"> {% csrf_token %} {{form.as_p}} <input type="submit" class="btn btn-success" value="Change my password"> </form> {% endblock %} my content does'nt linking to password_change_form.html Via versa linking to password_change from Django adminstration -
Change FileField in Django Model
I want to update the pre-created model field which is FileField; this file is stored in the server, not in request.FILES. My Model config is: class File(models.Model): fileID = models.AutoField(primary_key=True) apkToolFile = models.FileField(null=True,upload_to='{}'.format(join(getattr(settings,'FILES_BASE'),getattr(settings,'APKTOOL_DIR_BASE')))) apkFile = models.FileField(null=True,upload_to='{}'.format(join(getattr(settings,'FILES_BASE'),getattr(settings,'APK_DIR_BASE')))) appPackage = models.CharField(null=True, max_length=30) appName = models.CharField(null=True, max_length=30) appIcon = models.FileField(upload_to='{}'.format(join(getattr(settings,'FILES_BASE'),getattr(settings,'APP_ICON_DIR'))),null=True) appVersion = models.CharField(null=True, max_length=20) hashFile = models.CharField(null=True,max_length=64) jadxFile = models.FileField(null=True,upload_to='{}'.format(join(getattr(settings,'FILES_BASE'),getattr(settings,'JADX_DIR_BASE')))) def __str__(self): return "FileName: {apkFile} - HashFile: {hashFile}".format( apkFile = self.apkFile, hashFile=self.hashFile ) And my Model serilazer is: from rest_framework import serializers from .models import File class FileSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = File fields = [ 'fileID', 'apkToolFile', 'apkFile', 'appPackage', 'appName', 'appIcon', 'appVersion', 'hashFile', 'jadxFile' ] I want to update appIcon with the file which is stored in the server storage. How can i do this? Tank you -
FATAL: password authentication failed for user "siteadmin"
I am trying to run python manage.py makemigrations to initiliaze the data fields in my database, but I keep getting this error. Siteadmin is the user on my server, not even a user on my postgres database. I am trying to use the user "dbadmin" to create these datafields. local_settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'cramnation_prod', 'User': 'dbadmin', 'PASSWORD': 'abc123!', 'HOST': 'localhost', } } Dbadmin is a user in my postgres with sudo privileges and I have made sure that the passwords match. Why is it trying to use the name of my server user "siteadmin" instead of my postgres user "dbadmin"? -
User ModelForm not getting saved in database (Django)
I have a ModelForm that creates an instance of a custom user (AbstractUser model). Whenever I try to submit the form, nothing happens except a reload of the page (because of the action), and nothing is getting saved in the database. The code is as following: def sign_up(request): if request.method == 'POST': print("test") form = UserForm(request.POST) if form.is_valid(): form.save() data = form.cleaned_data user = authenticate( username=data['username'], password=data['password'] ) user_login(request, user) else: form = UserForm() return render(request, 'schedules/signup/signup.html', {'form':form}) class ClientUser(AbstractUser): classes = models.ManyToManyField(ScheduleClass) personal_changes = models.TextField(name="personal_changes", default="none") schedule = models.ManyToManyField(Schedule) def get_classes(self): return self.classes class UserForm(forms.ModelForm): class Meta: model = ClientUser fields = ['username', 'password', 'classes', 'schedule'] <form method="post" action="http://127.0.0.1:8000/"> {% csrf_token %} {{ form }} <input type="submit"> </form> For some reason, it's also not even printing the line I wrote on line 3 of the sign_up func, even when I post. Is there something I am doing wrong? -
How to use Django's session engine with subdomains?
I need to access a user's sessionid from within a subdomain on my site, so I can enable "single sign-on", but I can't seem to get it to work, despite changing SESSION_COOKIE_DOMAIN = '.localtest' in my settings. MRE You need to modify /etc/hosts to include localtest if you want to reproduce the error. Also note that this is only tested on macOS, so YMMV. urls.py: from django.contrib.auth import views from django.contrib.auth.decorators import login_required from django.urls import path @login_required def home_view(request): raise Exception('user was logged in') urlpatterns = [ path('login', views.LoginView.as_view(), name='login'), path('home', home_view, name='home'), ] settings.py: BASE_DOMAIN = 'localtest' SESSION_COOKIE_DOMAIN = '.' + BASE_DOMAIN LOGIN_URL = '/login' LOGIN_REDIRECT_URL = '/home' When I attempt to log a user in via the builtin LoginView, the login is successful, and the user is redirected to /home (which is on the same domain as the login). After the login redirect, the user's session gets dropped, and the login_required triggers, sending the user back to the login page. Why is this happening? Is this a bug, or am I missing something? If you want to reproduce this on your machine, here is a repo. The database has a test user set with the username root … -
How to create score from multiple choice site using Django, and then allow user to see their current/progressive score?
to programming and Django here. I'm creating a multiple choice quiz using Python and would like to calculate and keep track of the score. Also the user should be able view their current score from one question to the next (.html). Score to add 10 points for each correct answer selected. Total 10 questions, with each multiple choice question having 4 choices. What would be the best way to go about this? -
Django: Pass paramter to view funciton, but not in url
What I'm trying to do is allow my login page to be told whether to show an alert by through reverse without using the url from a redirect from another view function. My login view function looks like: def login(request, alert=False): ... context = generate_basic_context(request) if (alert): context['alert'] = { 'type': 'danger', 'text': 'You need to be logged in to do that!' } return render(request, 'login.html', context) My urls.py: urlpatterns = [ ... path('login/', views.login, {'alert': False}, name='login'), ... ] And my reverse (function is called from other view functions): def makeauthenticate(): return HttpResponseRedirect(reverse('login', kwargs={'alert': True'})) Error: django.urls.exceptions.NoReverseMatch: Reverse for 'login' with keyword arguments '{'alert': True}' not found. 1 pattern(s) tried: ['dashboard/login/$'] -
Things don't appear to be working at the moment. Please try again later. django-paystack
Im am getting this error; "Things don't appear to be working at the moment. Please try again later." It might be configuration settings but so far I don't what I'm missing, the documentation specifies 2 settings. django-paystack settings; I added the sendbox business email generated by paypal to PAYPAL_RECEIVER_EMAIL but I get the above error. PAYPAL_TEST = True PAYPAL_RECEIVER_EMAIL = '' Here is the views I'm testing out with. def process_payment(request): paypal_dict = { "cmd": "_xclick-subscriptions", "business": settings.PAYPAL_RECEIVER_EMAIL, "amount": "10000000.00", "item_name": "name of the item", "invoice": "unique-invoice-id", "notify_url": request.build_absolute_uri(reverse('paypal-ipn')), "return": request.build_absolute_uri(reverse('user_profile:success')), "cancel_return": request.build_absolute_uri(reverse('user_profile:cancelled')), # noqa "custom": "premium_plan", form = PayPalPaymentsForm(initial=paypal_dict, button_type="subscribe") return render(request, 'user_profile/process_payment.html', {'form': form}) } -
Django Formset - Update Value in Views.py before saving
I am trying to set a value on each form in the formset to a single value. I am not sure how to accomplish this... views.py function below: def customer_contacts(request, id): ContactFormSet = modelformset_factory(AppContactCnt, can_delete=True, fields=( 'name_cnt', 'phone_cnt', 'email_cnt', 'note_cnt', 'receives_emails_cnt'), max_num=3, extra=3) formset = ContactFormSet(queryset=AppContactCnt.objects.filter(idcst_cnt=id), prefix='contact') if request.method == 'GET': context = {'formset': formset} return render(request, 'customer_contacts.html', context=context) if request.method == 'POST': formset = ContactFormSet(request.POST, prefix='contact') if formset.is_valid(): print("we're updating contacts for " + str(id)) # formset.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER')) -
Display django registration form errors
I want to display registration errors when the user is trying to register but he does somthing wrong like typing an existing email address or the two passwords don't match or when one of the django's default password validator is not considred like typing a short password, and be able to style each error with bootstrap alert as i'm showing below in the template the user model in models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.conf import settings class User(AbstractBaseUser): email = models.EmailField(verbose_name="Email",max_length=250, unique=True) username = models.CharField(max_length=30, unique=True, null=True) date_joined = models.DateTimeField(verbose_name='Date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='Last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) full_name = models.CharField(verbose_name="Full name", max_length=150, null=True) profile_pic = models.ImageField(null=True, blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['full_name'] objects = MyAccountManager() def __str__(self): return self.full_name # For checking permissions. def has_perm(self, perm, obj=None): return self.is_admin # For which users are able to view the app (everyone is) def has_module_perms(self, app_label): return True the view that has the sign up/registration form in views.py def home(request): user = request.user # for rendring texts form = TextForm() if request.method == "POST": form = TextForm(request.POST) if form.is_valid(): obj = form.save(commit=False) author … -
Breaking Sting data into multiple display columns with Django
I have a string from dns zone file something like this: example.com. 98465 IN A 127.0.0.1 anotherExample.com. 98464 IN B 127.0.0.2 I use pre tag to split them into lines because i need to show them in a web page for users. <pre> <p> {{ dnsFileString }}</p> </pre> And I need to split them to show them in a nice way something like this: example.com. 98465 IN A 127.0.0.1 anotherExample.com. 98464 IN B 127.0.0.2 An Example how it should looks like: https://help.dyn.com/how-to-format-a-zone-file/ Is there is any way to make that?