Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
nvim pyright issue with django BigAutoField
I am using nvim with pyright and I have this error, I use Coc picture -
I need to test this in django
this is my code, and already done testing others but this one, I do not know yet -
django 4.1.1 redirect is not working if request.method=='POST'
I have tried to implement redirect in django 4.1.1 views. Please find the following code. redirect is working def customer_registration(request): return redirect('customer_login') redirect not working def customer_registration(request): print("ASFADFAd") if request.method == 'POST': return redirect('customer_login') return render(request, 'registration/registration.html') Can anyone help what is the problem, I have already gone through the internet none of the solutions working. Please help me. -
Searching for JSON in Django
I was able to import my data.json into Django after some time. Right now when a request is sent, the view.py function spits out the whole data.json file. I want to create a view.py function that only returns the results of a search request that was submitted and not the whole data.json. If I search for apple, I want the definition for apple to be returned from within data.json. I don't even know what I need to do. Do I convert the data.json file into SQL or python dictionary? Do I convert data.json into a model? The data.json files doesn't specify keys or values. views.py def searchbar(request): if request.method == 'GET': file_path = os.path.join(os.environ.get('HOME'), 'data.json') with open(file_path, 'r') as f: context = {"file_path": f} return render(request, 'movies/searchbar.html', context) searchbar.html {%block content%} {% for i in file_path %} {{i}} {%empty%} There is nothing here {%endfor%} {%endblock content%} home.html <form action ="{% url 'searchbar' %}"method="get"> <input type="text" name="search"/> <button type="submit"> Search</button> </form> data.json contents in searchbar.html when search is pressed: -
Is there a way to disable django models and auth?
I newie in Django but I really like it and I have to work with raw SQL and I want to disable all django apps and use only with rest framework. I tried it but it doesnt work and I want to know if there is any way to disable Django models and auth and that things. -
Django forms not returning result or errors
I am trying to use a Django form for a login page, but the form is returning False whenever I call form.is_valid(). I tried to print the errors in the console and in the HTML file but there's nothing displaying. I tried to get data from the form with form["email"].value() and it's returning None, even when I input data into the email field. Here's views.py: def postlogin(request): form = BootstrapAuthenticationForm(request.POST) # This prints out None into the console print(form["email"].value()) if form.is_valid(): # This code never runs! Even when there are no errors in the form fields! return render(request, "app/home.html") # If form is invalid, return to login page # This always runs, meaning form.is_valid() keeps being false! return render(request,"app/login.html", {"form":form}) Here's my forms.py: from django import forms from django.contrib.auth.forms import AuthenticationForm from django.utils.translation import ugettext_lazy as _ class BootstrapAuthenticationForm(AuthenticationForm): """Authentication form which uses boostrap CSS.""" email = forms.CharField(max_length=254,label=('Email'), widget=forms.TextInput({ 'class': 'form-control', 'placeholder': 'Email'})) password = forms.CharField(label=("Password"), widget=forms.PasswordInput({ 'class': 'form-control', 'placeholder':'Password'})) Here's my login.html: {% extends "app/layout.html" %} {% block content %} <h2>{{ title }}</h2> <div class="row"> <div class="col-md-8"> <section id="loginForm"> <form action="/postlogin/" method="post" class="form-horizontal"> {% csrf_token %} <h4>Use a local account to log in.</h4> <hr /> <div class="form-group"> <label for="id_username" … -
Why Django Messages Won't Work for logout but it work for my sing up?
I wrote this code: my view: from django.contrib.auth.views import LoginView, LogoutView class CustomLogout(LogoutView): def post(self, request, *args, **kwargs): messages.success(request, 'Logout was successfully') return super(CustomLogout, self).get(request, *args, **kwargs) This is my url: urlpatterns = [ ... path('logout/', CustomLogout.as_view(template_name='core/index.html'), name='logout'), ] and I have this in my template: {% if messages %} <div class="alert alert-dismissible" role="alert"> {% for message in messages %} <div class="alert alert-{{ message.tags }}">{{ message }} </div> {% endfor %} </div> {% endif %} I write something like this for SignUp and it works well and show the messages but in this case for logout it won't show any message in template... -
Markdown is not showing up on my Django/HTML web page
I already converted the Markdown page, but it is not showing. Here is how my page looks like when I try to enter to any markdown content: VIEWS: from django.shortcuts import render from markdown2 import Markdown from . import util def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) def entry(request, entry): markdowner = Markdown() entrypage = util.get_entry(entry) if entrypage is None: return render(request, "encyclopedia/NonExisting.html", { "entrytitle": entry }) else: return render(request, "encyclopedia/entry.html", { "entry": markdowner.convert(entrypage), "entrytitle": entry } ) URLS: from xml.etree.ElementInclude import include from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("wiki/<str:entry>/", views.entry, name="entry") ] and that Edit button in the image does not work either. -
TypeError: __init__() takes 1 positional argument but 2 were given new one
I am develop a simple authentication application in django but I get this error: TypeError: init() takes 1 positional argument but 2 were given my view from .forms import RegisterForm, LoginForm from django.contrib.auth.views import LoginView from django.shortcuts import render, redirect from django.contrib import messages from django.views import View from .forms import RegisterForm def home(request): return render(request, 'users/home.html') class RegisterView(View): form_class = RegisterForm initial = {'key': 'value'} template_name = 'users/register.html' def dispatch(self, request, *args, **kwargs): if request.user.is_authenticated: return redirect(to='/') return super(RegisterView, self).dispatch(request, *args, **kwargs) def get(self, request, *args, **kwargs): form = self.form_class(initial=self.initial) return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}') return redirect(to='/') return render(request, self.template_name, {'form': form}) class CustomLoginView(LoginView): form_class = LoginForm def form_valid(self, form): remember_me = form.cleaned_data.get('remember_me') if not remember_me: self.request.session.set_expiry(0) self.request.session.modified = True return super(CustomLoginView, self).form_valid(form) application urls urlpatterns = [ path('', home, name='users-home'), path('register/', RegisterView.as_view(), name='users-register'), # This is what we added path('login/', CustomLoginView.as_view(redirect_authenticated_user=True, template_name='users/login.html', authentication_form=LoginForm), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), ] my form from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm, AuthenticationForm class RegisterForm(UserCreationForm): first_name = forms.CharField(max_length=100, required=True, widget=forms.TextInput(attrs={'placeholder': 'First Name', 'class': 'form-control', })) last_name = forms.CharField(max_length=100, required=True, … -
Suitescript that attempts to set an amount for sales order items causes "unexpected error"
I have this code that, in theory, changes the amount on the sublist of a sales order in Netsuite, but for one reason or another it tells me that an unexpected error happened. Nothing I've looked at has been particularly helpful Edit: To be clear, the error happens when I go to saved mass updates and execute it, not when saving it /** *@NApiVersion 2.1 *@NScriptType MassUpdateScript */ define(['N/record'], (record) => { function each(params) { let rec = record.load({ type: params.type, id: params.id }); var quant = rec.getValue('custrecordeconomcap'); rec.setCurrentSublistValue({ sublistId: 'item', filedId: 'quantity', value: quant }); rec.save(); } return { each: each }; }); -
I got error while attempting to serialize product's images
AttributeError: Got AttributeError when attempting to get a value for field picture on serializer ProductSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Product instance. Original exception text was: 'Product' object has no attribute 'picture'. class ProductImageSerializer(serializers.ModelSerializer): class Meta: model = Picture fields = ['picture'] class ProductSerializer(serializers.ModelSerializer): category = serializers.ReadOnlyField(source='category.name') discount = serializers.ReadOnlyField(source='discount.name') picture = ProductImageSerializer(many=True) class Meta: model = Product fields = ['_id', 'category', 'discount', 'name_geo', 'picture', 'brand', 'size', 'technicalRequirements', 'instructionForUse', 'safetyStandard', 'youtubeUrl', 'price', 'createdAt', 'user'] class Picture(models.Model): picture = models.ImageField(null=True, blank=True, default='/placeholder.png') product = models.ForeignKey(Product, on_delete=models.CASCADE) def __str__(self): return str(self.picture) -
Query to calculate user balances
In my project there are coins that users can buy, use to perform certain actions and convert to real money. A user can only convert coins earned (by receiving gifts for example) into real money, not those bought from the site directly. Therefore, two balances are calculated internally: coins bought and coins earned (the total balance is the sum of these two). The following model contains coin transactions (it's simplified): class CoinTransaction(models.Model): class TransactionTypes(Enum): purchase_of_coins = ('pu', 'Purchase of Coins') # Will have a positive amount conversion_into_money = ('co', 'Conversion Into Money') # Will have a negative amount earning = ('ea', 'Earning') # Will have a positive amount expense = ('ex', 'Expense') # Will have a negative amount @classmethod def get_value(cls, member): return cls[member].value[0] user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name='coin_transactions') amount = models.IntegerField() transaction_type = models.CharField(max_length=2, choices=[x.value for x in TransactionTypes]) The earned coin balance is increased by all income except coin purchases, while the bought coin balance is increased only by coin purchases. Coins from conversion_into_money transactions are subtracted from the earned coin balance, while all other expenses are first subtracted from the bought coin balance if greater than 0. Note that the two balances cannot go below 0. To … -
Django filters just returns all objects
So I have model like this class Research(models.Model): CATEGORIES = (...) name = models.CharField(max_length=80) date = models.DateField() category = models.CharField(max_length=10, choices=CATEGORIES) public_use = models.CharField(max_length=17, choices=PUBLIC_USE_CHOICES) This filter: class ResarchFilter(filters.FilterSet): year = filters.DateFilter(field_name='date', lookup_expr='year') category = filters.CharFilter(field_name='category', lookup_expr='iexact') class Meta: model = Research fields = ['date', 'category'] And that view: class ResarchCategoryYear(generics.ListCreateAPIView): queryset = Research.objects.all() serializer_class = ResearchSerializer filter_backends = (filters.DjangoFilterBackend,) # filterset_fields = ['date', 'category'] filter_class = ResarchFilter So when I'm uncomment filterset_fields and comment filter_class it all works well but I can't filter by the year and not by the full date. So when I'm do it like in code above and goes to http://127.0.0.1:8000/...?year=2000 It literally do nothing, just gives me all of the Research objects. So what I'm doing wrong and how to enable this filtering? -
TypeError: Field.__init__() got an unexpected keyword argument 'max_lenght'
from django.db import models class Coustomer (models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=100) locality = models.CharField(max_lenght=150) zipcode= models.IntegerField() state = models.CharField(choices=STATE_CHOICES,max_lenght=100) class Product(models.Model): title = models.CharField(max_lenght=100) selling_price = models.FloatField() discount_price = models.FloatField() description = models.TextField() brand = models.CharField(max_lenght = 100) category = models.CharField(choices=CATEGORY_CHOICE, max_lenght=2) prodect_image = models.ImageField(uploded_to = 'Productimg') enter code here -
Performance: Best way to send large amounts of data
On my website, users can upload posts with or without files (images, audios, videos, etc.) to the database. I have two options now: Send a very large request containing the posts data as well as maybe multiple GB of data. Then create a post object and connect the files to it. Send one very small request with only the content of the post and creating one in the backend. Then sending back the UUID to the post. Then automatically sending a large request containing the files & the UUID to the backend and connecting post & files afterwards. The pro (at least IMO) to the second solution is that users could already see their posts while the files are still being processed by the backend celery worker. Would this be considered bad or good user experience? Not sure how well both solutions might scale in the future and if it'd be a difference in traffic load when there's two requests being sent. -
How to use JavaScript client-side encryption/decryption in django forms / crispy forms? Is there any python package available which can do this
Django Form fields needs to be encrypted at server side and needs to be decrypted in client browser while rendering and vice versa for form submission One approach is using JS cryptographic libraries or to use custom encryption code. But, Is there any python package available which implements this where we use this as django form widget along with js library at client side. An example will be a package like the django-autocomplete-light package which provides a widget for autocompletion for the particular field. How to implement this or Is there any package available which can be used. -
Django: in views how can a redirect if the paramater(linked to a url pattern) does not match a model result?
I apologize am still learning django and am just hitting my head on a wall with some of it. The current issue is that I have a view linked through a URL parameter the issue and it works for showing my model info but if you hard type the url to a different parameter it shows the page. I have tried to redirect it but that is not working I feel like it might because of how and where I return my render. Any advice on how to set up url's base off model and if that model info doesn't exist either through a 404 or redirect to a different page? View: @login_required(login_url='login_register') def project_page(request, name): project = Project.objects.all() issueticket1 = Issue.objects.filter(related_project__name__exact=name) table = IssueTable(issueticket1) project_list = {} for p in project: if p.name == name: project_list = {'id': p.project_id, 'startdate': p.start_date, 'enddate': p.end_date, 'description': p.description} return render(request, 'main_projects.html', {'name': name, 'project_list': project_list, 'project': project, 'table': table}) URL CONFIG: path('projects/<str:name>/', views.project_page, name="project_page"), -
How change filter variable in view from Django template?
I have review model that has reviews made by users. In view I do pagination for it. Then I do filter the reviews by variable type = 'art' How i can change variable filter for type = 'music' from template to display selectet reviews? How then use all() to display all of them? Do I have to make separate templates for each view variable or is simpler way? My view.py: def viewrevs(request): rev = Reviews.objects.filter(type = 'art') paginator = Paginator(rev,2) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) ... My template.html {% for rev in page_obj %} {{ rev.name }} {{ rev.size }} {{ rev.data }} ... {% enfor %} -
requests are working locally but not on Heroku. Getting internal server error 500 and JSON not valid
I built a web application with django and react. It is working perfectly fine locally and the heroku deployment worked fine without issues. When I am testing the heroku app some of my requests are working fine like login/register. However the request where information is being sent back from the server to be displayed or post requests sending information are giving me the following error GET [request name] 500 (Internal Server Error) and Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON Would this issue be related to my requirements.txt or Procfile? Since the issue is not happening when the project is run locally and only on heroku. Could anyone point me in the right direction? -
Django/Python Runtime Error: RecursionError at /blog/cubs/
I have created a website, and I keep getting recursion errors on my /blog/cubs page, I have 2 identical pages for Beavers and Scouts but when I view the cubs equivalent I keep getting this recursion error. Below is the tracefile: pastebin of tracefile as it's too large to post here Here is the urlpatterns variable from cubs/urls.py: urlpatterns = [ path('', PostList.as_view(), name='cubs_blog_home'), path('about/', views.AboutView.as_view(), name='cubs_blog_about'), path('search/', views.SearchView.as_view(), name='cubs_blog_search'), path('file_upload/', views.upload, name='cubs_blog_file_upload'), path('downloads/', views.DownloadView.as_view(), name='cubs_blog_downloads'), path('badge_placement', views.BadgePlacementView.as_view(), name='cubs_blog_badge_placement'), path('user/<str:username>', UserPostList.as_view(), name='cubs_blog_user_posts'), path('post/new_post/', PostCreate.as_view(), name='cubs_blog_post_create'), path('post/<slug:slug>/like/', views.PostLikeView, name='cubs_blog_post_like'), path('post/<slug:slug>/', views.PostDetail.as_view(), name='cubs_blog_post_detail'), path('post/update/<slug:slug>/', PostUpdate.as_view(), name='cubs_blog_post_update'), path('post/delete/<slug:slug>/', PostDelete.as_view(), name='cubs_blog_post_delete'), #path('posts/<int:year>/<int:month>/', main_website_views.CubsPostMonthArchiveView.as_view(month_format='%m'), name="cubs_blog_post_archive_month"), #path('post/tag/<slug:slug>/', views.tagged, name="cubs_blog_post_tags"), ] And this is my woodhall_website/urls.py file: urlpatterns = [ path('admin/', admin.site.urls), path('blog/beavers/', include('beavers.urls')), path('blog/cubs/', include('cubs.urls')), path('blog/scouts/', include('scouts.urls')), path('executive/', include('executive.urls')), path('', include('accounts.urls')), path('', include('main_website.urls')), path('summernote/', include('django_summernote.urls')), path('sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), path('admin/password_reset/', auth_views.PasswordResetView.as_view(), name='admin_password_reset'), path('admin/password_reset/done/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('password_reset/', auth_views.PasswordResetView.as_view(template_name='accounts/password_reset.html'), name='password_reset'), path('password_reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='accounts/password_reset_done.html'), name='password_reset_done'), path('password_reset_confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='accounts/password_reset_confirm.html'), name='password_reset_confirm'), path('password_reset_complete/', auth_views.PasswordResetCompleteView.as_view(template_name='accounts/password_reset_complete.html'), name='password_reset_complete'), -
How to restrict a child table from referencing a parent table based on specific property in Django
Consider the following example: class Car(models.Model): def __str__(self): return self.name name = models.CharField(max_length=255) type_choices = [ ('Sedan','Sedan'), ('SUV','SUV'), ('Truck','Truck'), ] type = models.CharField('Type', max_length=255, choices=type_choices) class Sedan(models.Model): models.ForeignKey(Car, on_delete=models.CASCADE) class SUV(models.Model): models.ForeignKey(Car, on_delete=models.CASCADE) class Truck(models.Model): models.ForeignKey(Car, on_delete=models.CASCADE) How can I prevent a Sedan model record from referencing a Car model record with the type set as a Truck in the context of the admin dashboard? is there a better way to design this relationship? -
ReferenceError: file is not defined - Suitescript
I resolved some earlier issues and got the below script to validate and deploy. However it fails and in the logs I see this error: ReferenceError: file is not defined [at Object.execute (/SuiteScripts/purchasing.js:11:9)] but my file is definitely there in that location and is defined in the script. All help greatly appreciated. /** * @NApiVersion 2.1 * @NScriptType ScheduledScript */ define(['N/task'], function (task) { function execute(scriptContext){ var scriptTask = task.create({taskType: task.TaskType.CSV_IMPORT}); scriptTask.mappingId = 212; var f = file.load('SuiteScripts/purchasing2.csv'); scriptTask.importFile = f; var csvImportTaskId = scriptTask.submit(); }; return{ execute: execute }; }); -
How to aggregate annotate fields of related models in django
My problem is a little more complicated, but I'm posting the question in the simplest possible way. Annotated total_score in Photo. I would like to annotate max_total_score in Person. I wrote get_queryset of PersonManager, but the following error occurred. Is there a new way? models.py from django.db import models class PersonManager(models.Manager): def get_queryset(self): photos_prefetch = models.Prefetch( 'photos', Photo.objects.annotate(total_score=models.Sum('features__score')) ) return super().get_queryset() \ .prefetch_related(photos_prefetch) \ .annotate(max_total_score=models.Max('photos__total_score')) class Person(models.Model): objects = PersonManager() class Photo(models.Model): person = models.ForeignKey(Person, models.CASCADE, related_name='photos') class Feature(models.Model): photo = models.ForeignKey(Photo, models.CASCADE, related_name='features') name = models.CharField(max_length=100) score = models.IntegerField() shell >> Person.objects.all() # Unsupported lookup 'total_score' for BigAutoField or join on the field not permitted -
Nginx frontend not calling Nginx in backend
So I am using Django + react with nginx both on backend and frontend, containerized in docker. The following image will clarify how I want to serve the whole application: Having been googling but couldn't make sense of the solutions. Issue is that Nginx in frontend not connecting with nginx on backend on port 8082. Following are docker, nginx and docker-compose files. Nginx configurations for frontend: upstream react { server reactapp:3000; } server { listen 80; client_max_body_size 100M; proxy_set_header X-Forwarded-Proto $scheme; location / { root /usr/share/nginx/html; } location /add-to-waiting/ { proxy_pass http://0.0.0.0:8082; } } Dockerfile for react and nginx for frontend: # build environment FROM node as build WORKDIR /app ENV PATH /app/node_modules/.bin:$PATH COPY package.json ./ COPY package-lock.json ./ RUN npm i --silent RUN npm install react-scripts@3.4.1 -g --silent COPY . ./ RUN npm run build # production environment FROM nginx:stable-alpine COPY --from=build /app/build /usr/share/nginx/html EXPOSE 80 EXPOSE 443 CMD ["nginx", "-g", "daemon off;"] docker-compose.yml for frontend: services: frontend: build: . ports: - "8090:80" container_name: irisfrontend Nginx configurations for backend upstream django { server website:8000; } server { listen 80; client_max_body_size 100M; proxy_set_header X-Forwarded-Proto $scheme; location / { proxy_pass http://django; } location /media/ { alias /app/media/; } location /static/ { … -
How to correctly type utf-8 characters?
Azerbaijan language info = "Çox da uzaq olmayan gələcəkdə, tənha yazıçı Teodor" <p class="card-text"> {{ info|slice:"0:54" }} </p> <p class="card-text"> Çox da uzaq olmayan gələcəkdə, tənha yazı&ccedi </p> ç = &ccedi How to write utf-8 characters correctly?