Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Understanding how Django's cache framework works and dealing with cached pages for different user roles
I am having an issue where pages are not being displayed correctly for a certain user role and I am sure the problem is caching. The page is a partial view of a sports schedule which is loaded with AJAX: url(pattern, cache_page(CACHE_TIMEOUT)(last_modified(season_modified(dont_vary_on("Cookie")(ScheduleView.as_view()))), name='schedule_partial') Note that season_modified is a function that retuns the last time the season/schedule was modified. It is used to refresh the cache. Here is the problem: When a user browses the schedule page view as an anonymous or non-authorized user, the schedule with the non-authorized bits will be loaded and cached. Then if they log it or switch accounts as a referee, the page should load with several referee-related elements, mainly score inputs so they can keep match scores. However, it seems that the non-authorized cached version of the page is loaded, so they cannot interact with the schedule as they should. However, if I log in with my staff account, or if a schedule admin logs in, the admin/staff version of the page, which is what we want. My understanding of how this cache framework works is that once the route is accessed by anyone, the page is generated and cached. From then on, until the … -
Need guidance with FilteredSelectMultiple widget
I am sorry if it question might turn to be little broad, but since I am just learning django (and I am just hobbyist developer) I need some guidance which, I hope, will help someone like me in the future since I could not find any clear and easily comprehensible guide on using this widget. With your answers and help I will try to make this question thread at least guide-ish. Material I found somewhat helpful for this topic: Django multi-select widget? Django: Replacement for the default ManyToMany Widget of Forms Django's FilteredSelectMultiple widget only works when logged in Django FilteredSelectMultiple not rendering on page Use the Django admin app's FilteredSelectMultiple widget in form Get the chosen values from FilteredSelectMultiple widget in Django There were few others links, but they did not made anything clearer or added new information so I won't mention them. Here is what I managed to understand (please correct me if I am wrong or add anything that I missed): To create FilteredSelectMultiple widget firs I need to amend forms.py (as in any other widget creation process). Amended forms.py should have from django.contrib.admin.widgets import FilteredSelectMultiple import and Media class. forms.py code should look like this (please … -
Django How to preload Fat Class
How can I use Django preload this fat class? because when requests come in My code will do like: MyFatClass() then it's very slow to loading this class have any idea to preload this class in global and very django requests comes will take already preload's fat class? class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances:cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls] class MyFatClass(metaclass=Singleton): # something about tensorflow -
Error while extending user model in django?
I was trying to add a Staff model with an OneToOne relation to the django User Model but while trying with this code I am being unable to register Staff model.It is giving me ValueError ValueError: Cannot assign "14": "Staff.organization" must be a "Organization" instance.. It is neither saving my user_id in my Staff table.It just register the user with username password but the staff model is not registering.Here what i might be doing wrong? models.py class Staff(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user') name = models.CharField(max_length=255, blank=True, null=True) organization = models.ForeignKey(Organization, on_delete=models.SET_NULL, blank=True, null=True, related_name='organization') position = models.ForeignKey(Position, on_delete=models.SET_DEFAULT, default='staff', related_name='position') salary = models.CharField(max_length=50, blank=True, null=True) address = models.CharField(max_length=255, blank=True, null=True) phone_num = models.CharField(max_length=15, blank=True, null=True) joined_date = models.DateField(blank=True, null=True) forms.py class RegisterStaffForm(UserCreationForm): name = forms.CharField(max_length=255) organization = forms.CharField(max_length=255) position = forms.CharField(max_length=255) joined_date = forms.CharField(max_length=255) email = forms.EmailField() def clean_email(self): email = self.cleaned_data['email'] if User.objects.filter(email__iexact=email).exists(): raise ValidationError('Sorry.Email address already exists.') return email class Meta: model = User fields = ['name','email','username','password1','password2','organization','position','joined_date'] views.py def register_staff(request): form = RegisterStaffForm() organizations = Organization.objects.all() positions = Position.objects.all() if request.method == 'POST': form = RegisterStaffForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] organization = form.cleaned_data['organization'] print(organization) position = form.cleaned_data['position'] print(position) joined_date = form.cleaned_data['joined_date'] staff = form.save(commit=False) staff.is_staff = … -
Adding Django pagination code to Slider Revolution navigation arrows
I'm trying to add some Django code to Slider Revolution nagivation arrows. I don't know where to place this code. Can anyone help me, plese? Thanks in advance. -
I can't make a Django post request
I have a function based view that sends a post request to skapa-studieplan (a url) that is a function based view. I want to know why I get this error: TypeError at /skapa_studieplan Direct assignment to the forward side of a many-to-many set is prohibited. Use students.set() instead. The View: #post request checker @login_required def skapa_studieplan(request): if request.method == 'POST': name = request.POST.get('Studyplan-Name') description = request.POST.get('Studyplan-Description') students = request.POST.get('Studyplan-Students') teachers = request.POST.get('Studyplan-Teachers') canview = request.POST.get('Studyplan-Canview') parent_assignment = request.POST.get('Studyplan-ParentAssignment') studyplan = Studyplan(name=name, description=description, students=request.user, teachers=request.user, canview=request.user, parent_assignment=parent_assignment) event.save() return redirect('allaStudieplaner') in template: <form class="modal fade" id="project-add-modal" tabindex="-1" aria-hidden="true", action="{% url 'skapa-studieplan' %}" method='POST'> {% csrf_token %} <div class="modal-dialog" role="document"> <div class="modal-content"> <style> also the studyplans model class Studyplan(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=1000) parent_assignment = models.ForeignKey(Assignment, blank=True, on_delete=models.CASCADE,related_name="studyplan") deadline = models.DateField(default=date.today) students = models.ManyToManyField(UserProfile, blank=True, related_name="studyplan_students") teachers = models.ManyToManyField(UserProfile, blank=True, related_name="studyplan_teachers") canview = models.ManyToManyField(UserProfile, blank=True, related_name="studyplan_canview") notes = models.ManyToManyField(Note, blank=True, related_name="studyplan") tasks = models.ManyToManyField(Task, blank=True, related_name="studyplan") messages = models.ManyToManyField(Message, blank=True, related_name="studyplan") class Meta: verbose_name_plural = 'Studyplans' def __str__(self): return "{name}".format(name=self.name) the urls: urlpatterns = [ path('', views.landingPage), path('login', views.loginPage), path('studyplans', views.studyplanPage, name='allaStudieplaner'), path('<int:pk>/view/detail/',views.detailStudyplanPage,name='detailStudyplanPage'), path('<int:pk>/view/detailTask/',views.detailTaskPage,name='detailTaskPage'), path('assignments', views.assignmentPage), path('skapa_studieplan', views.skapa_studieplan, name="skapa-studieplan"), ] -
Creating a user profile (One-To-One Link with user model) on sign up
I am currently trying to create a profile model alongside the user model that is filled out on sign up. I have been using this article as my guide. https://simpleisbetterthancomplex.com/tutorial/2018/01/18/how-to-implement-multiple-user-types-with-django.html Currently when I try to sign up a user I get an error that says that the profile fields cannot be null. It looks like the Attendee model information is not being filled in. Models.py from django.contrib.auth.models import AbstractUser from django_countries.fields import CountryField from django.db import models class User(AbstractUser): is_attendee = models.BooleanField(default=False) is_organiser = models.BooleanField(default=False) objects = CustomUserManager() class Attendee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) country = CountryField() date_of_birth = models.DateField(help_text='DDMMYYYY') Forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.db import transaction from django_countries.fields import CountryField from .models import User, Attendee class AttendeeSignUpForm(UserCreationForm): country = CountryField().formfield(required=True) date_of_birth = forms.DateField(input_formats=['%d/%m/%Y'], widget=forms.TextInput( attrs={'placeholder': 'DD/MM/YYYY'} ), required=True) class Meta(UserCreationForm.Meta): model = User fields = ('username','first_name', 'last_name', 'email', 'password1', 'password2') @transaction.atomic def save(self): user = super().save(commit=False) user.is_attendee = True user.save() attendee = Attendee.objects.create(user=user) attendee.country.add(*self.cleaned_data.get('country')) attendee.date_of_birth.add(*self.cleaned_data.get('date_of_birth')) return user Views.py from django.contrib.auth import login as auth_login from django.shortcuts import render, redirect from django.views.generic import UpdateView, CreateView, TemplateView from django.db import transaction from .models import User from .forms import AttendeeSignUpForm, OrganiserSignUpForm class AttendeeSignUpView(CreateView): model = … -
Django AssertionError at /play/api/5/play/ The `request` argument must be instance of `django.http.HttpRequest`, not `myApp.views.TrackPlayAPIToggle`
I am trying to implement an api version of a play button on a django website. This is how far I got: models.py class Note(models.Model): plays = models.ManyToManyField(settings.AUTH_USER_MODEL,blank=True,related_name='track_plays') def get_play_url(self): return "/play/{}/play".format(self.pk) def get_api_like_url(self): return "/play/{}/play-api-toggle".format(self.pk) views.py class TrackPlayToggle(RedirectView): def get_redirect_url(self,*args,**kwargs): id = self.kwargs.get("id") obj = get_object_or_404(Note,id=id) url_ = obj.get_absolute_url() user = self.request.user if user.is_authenticated(): if user in obj.plays.all(): obj.plays.add(user) else: obj.plays.add(user) return url_ from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import authentication,permissions from rest_framework.decorators import api_view class TrackPlayAPIToggle(RedirectView): authentication_classes = (authentication.SessionAuthentication,) permission_classes = (permissions.IsAuthenticated,) @api_view(['GET', 'POST', ]) def get(self,request,format=None): obj = get_object_or_404(Note,id=id) url_ = obj.get_absolute_url() user = self.request.user updated = False played = False if user.is_authenticated(): if user in obj.plays.all(): played = True obj.plays.add(user) else: played = True obj.plays.add(user) played = False updated = True data = { "updated":updated, "played":played } return Response(data) urls.py url(r'^(?P<id>\d+)/play/', TrackPlayToggle.as_view(), name='play-toggle'), url(r'^api/(?P<id>\d+)/play/', TrackPlayAPIToggle.as_view(), name='play-api-toggle'), Ive added the API Decorator, because without it, I get a TypeError: get() got an unexpected keyword argument 'id' and when I try to add id=None I get an AssertionError: .accepted_renderer not set on Response Is this because I used id instead of slug? Thank you for any suggestions -
Pass extra field to serializer
I have a model for price tags, let's say it contains only price. I want to pass image of the price tag to serializer then call method for text recognition inside serializer and pass recognized price to model. But I don't need image field in my model. How do I add extra field to serializer which doesn't relate to model? This is the serializer: class CartProductSerializer(serializers.ModelSerializer): image = ImageField() class Meta: model = CartProduct fields = '__all__' def create(self, validated_data): data = validated_data['image'] path = default_storage.save('tmp/somename.jpg', ContentFile(data.read())) detect_pricetag(path) return super().create(validated_data) But I got this error: Got AttributeError when attempting to get a value for field `image` on serializer `CartProductSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `CartProduct` instance. Original exception text was: 'CartProduct' object has no attribute 'image'. Deleting 'image' object from validated_data doesn't help. Is there any chance to use DRF serializer field for POST request which is not in the model? -
Create a new site with a recent version or use the old one
The project I'm working on is based on Django 1.4 and I can't change / update it actually. I have to work on an API to modify data on that site. I thought I would use Django Rest Framework to do it. Would there be a problem if I start a new site from scratch using Django 3.X and the newest version of the DRF, using the same DataBase as the oldest site ? I mean, if by using the API on the new site I change data on the DataBase, this is also going to be changed on the "old" ? On the other side, I could keep working on the "old" site and use an old version of DRF but those version are less complete, less documented and less secure. Thanks a lot -
Why django transaction sends double commit?
I'm trying to create code that will add new user(django User model and Employee module). When calling the code, I get a Duplicate entry error. However, data have been added. As I try to intentionally add an existing record, Duplicate entry error appears twice. @transaction.atomic def add(self): u=User(username=new_username, ... ) e=Employee(...) try: u.save() e.save() except IntegrityError as e: print(e) -
Need help. Can't resolve getting wrong url
I have problem with url in my project. I've new to programming and I'm learning Django through Django tutorial on official website. In part 4 of the tutorial, there's a section which shows how to use generic views. I have checked my code few times and everything seems to be exactly the same as it is in tutorial. However, when I click on a link for detail.html (on index page) I'm getting a 404 error with Request URL:http://127.0.0.1:8000/1// I can't figure out how come I get this request url (ending with second forward slash). What am I doing wrong? Everything worked just fine when I used functions that returned i.e render(request, "polls/detail.html", context) Here's debug error explanation: "Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: [name='index'] <int:pk>/ [name='detail'] <int:pk>/results/ [name='results'] <int:question_id>/vote/ [name='vote'] admin/ The current path, 1//, didn't match any of these." Down below is my code for index.html, project/urls.py, app/urls.py and app/views.py project/urls.py: from django.contrib import admin from django.urls import include, path urlpatterns = [ path('', include('polls.urls')), path('admin/', admin.site.urls), ] app/urls.py: urlpatterns = [ path('', views.IndexView.as_view(), name="index"), path('<int:pk>/', views.DetailView.as_view(), name="detail"), path('<int:pk>/results/', views.ResultsView.as_view(), name="results"), path('<int:question_id>/vote/', views.vote, name="vote"), ] app/views.py from django.views import generic from … -
Django: Group query_set by answer
I am trying to get the following out but: {'male': 123, 'female': 432, 'other': 12} From there I will go and calculate the % of the distribution to the total amount: male: 123/567 = 21% female: 76% [...] Currently, that's my not working solution. The output is not what I expected. Can you help me? def get_gender_distribution(self): answers = ( Question.objects.filter( focus=QuestionFocus.GENDER, survey__event=self.request.event, survey__template=settings.SURVEY_POST_EVENT, ) .values('answers') .annotate(count=Count('answers')) ) Models: class Question(TimeStampedModel): survey = models.ForeignKey() type = models.CharField() focus = models.CharField() class Answer(TimeStampedModel): question = models.ForeignKey([...]) response = models.ForeignKey([...]) answer = models.TextField(verbose_name=_("Answer")) class Survey(TimeStampedModel): event = models.ForeignKey() template = models.CharField() -
Importing spaCy object (nlp) into a different Docker container running Django project
I am running a docker-compose file with 3 services (or containers): django-web nginx spacy-web My final goal is to create 2 nlp objects (nlp_en, nlp_fr) in spacy-web and make use of them in django-web. Does that look possible/desirable? Of course, the reason behind splitting django-web and spacy-web is to have a cleaner scheme of containers. I have created a Dockerfile for spacy-web. I install spaCy and 2 language models (English/French). With an entrypoint (which runs a python script: spacy_entrypoint.py), I then create 2 nlp objects, 1 for each language (nlp_en, nlp_fr). My first problem is that this container exits immediately after creating the nlp objects. My guess is that I should add something at the end of the python script, to keep the container running, but without using much CPU. How do we keep a python container alive, to access objects created into it from another container? If that problem can be solved, then I need to import the nlp objects (nlp_en, nlp_fr) in the other container, namely django-web. I never got there because spacy-web exits immediately after creation. In the relevant django views, I would try "from spacy-web import nlp_en, nlp_fr". Has anyone tried an python import from one … -
Django: AttributeError: 'NoneType' object has no attribute 'is_relation'
Django's new model class could not be successfully migrated, reported an error, how do I need to change this error Django 2.1.7 Python 3.6.5 In the previous version of ORM, you can also migrate normally, but after changing some code, it will not migrate properly. File "C:\Users\senyu\Anaconda3\envs\py3.6.5\lib\site-packages\django\core\management\com mands\migrate.py", line 203, in handle fake_initial=fake_initial, File "C:\Users\senyu\Anaconda3\envs\py3.6.5\lib\site-packages\django\db\migrations\execu tor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fak e_initial) File "C:\Users\senyu\Anaconda3\envs\py3.6.5\lib\site-packages\django\db\migrations\execu tor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\senyu\Anaconda3\envs\py3.6.5\lib\site-packages\django\db\migrations\execu tor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\senyu\Anaconda3\envs\py3.6.5\lib\site-packages\django\db\migrations\migra tion.py", line 114, in apply operation.state_forwards(self.app_label, project_state) File "C:\Users\senyu\Anaconda3\envs\py3.6.5\lib\site-packages\django\db\migrations\opera tions\fields.py", line 144, in state_forwards delay = not old_field.is_relation AttributeError: 'NoneType' object has no attribute 'is_relation' -
Why Django won't render the sum that implied in pandas?
I'm manipulating a Dataframe using pandas and then I'm rendering the manipulated data to the user. I don't know if that's a pandas or a Django problem (or mine?). I tried exporting my Dataframe into .csv and re-reading it with pandas nothing. Consider this Dataframe. A B C 0 foo bar 10 1 foo bar2 20 2 foo bar 10 3 foo bar2 250 In my views.py, df = df.groupby(['A', 'B']).sum().sum(level=['A', 'B']).fillna(0).reset_index() context.update({'df': df.values}) return context In my template {% for A, B, C in df %} <tr> <td>{{ A }}</td> <td>{{ B }}</td> <td>{{ C }}</td> </tr> {% endfor %} I'm expecting to see A B C 0 foo bar 20 1 foo bar2 270 And I'm seeing A B C 0 foo bar 1010 1 foo bar2 20250 It's weird because I tried to export the .csv and reimport it. I believe it's a bug. -
Web Security: Is it okay to include PKs in json response during an ajax call?
Development Language: Python Framework: Django 1.11 SQL: PostgreSQL I have this page that lists all job vacancies in a table. On each row, I have an action link at the end that opens a modal containing more information of the vacancy. Data layout of the modal is already prepared, I just execute an ajax call so that the dynamic data gets updated with values related to the selected row i.e. monthly salary, office designation, etc. Here is how my modal looks: In my views.py, the way I throw the ajax response is by returning a HttpResponse(data, content_type="application/json") which results to having this as a json response: The above response is via a SELECT * query. Some of those data are primary key value of referenced tables such as the office table. My questions are: Is it a good idea for me to return such json response? Instead of using SELECT *, should I specify the fields I only need so I don't need to worry about those PK values being available for potential hacking? -
Can Webpack process Django static files (images)?
Is it possible to make Webpack to process images used in Django html templates? My idea was to require all html files and use html-loader. But then how to handle Django static path? <img src="{% static 'assets/images/image.png' %}"> -
Django dynamic create form based on dropdown select
I'm working on with Django, question and how to, is there any way to generate dynamic form based on the dropdown selection? My form is really simple, user will need to update device information. Instead of submitting one form at a time, I would like to provide options with dropdown select number of devices, let say 10, there should be 10 new forms entries. Within 1 Form there are 4 fields needs to enter. I started something but stuck on view and display via html MODEL class Devices(DeviceINFO, models.Model): name = models.ForeignKey(DeviceTYPE, on_delete=models.SET_NULL, null=True) item1_link1 = models.CharField(max_length=5, blank=True, default='') item1_link2 = models.CharField(max_length=5, blank=True, default='') ... FORM: class Devices_form(forms.ModelForm): class Meta: model = Devices fields = '__all__' def __init__(self, n, *args, **kwargs): super(Devices_form, self).__init__(*args, **kwargs) for i in range(0, n): self.fields["item%d_link1" % i] = forms.CharField(max_length=20, blank=True, default='') self.fields["item%d_link2" % i] = forms.CharField(max_length=20, blank=True, default='') ... VIEW: def DevicesView(request, *args, **kwargs): template_name = 'DeviceView.html' seq = [2, 4, 6, 8, 10] form = Devices_form(request.POST or None) if request.method == 'POST': if form.is_valid(): print(form.cleaned_data['seq']) context = { 'num': form.cleaned_data['seq'] } return render(request, template_name, {'seq': seq}) Is that right way? How to display in html? Thanks for the help in advance. -
Ajax does not request the page with the written url
The problem is as follows: When I type on the address bar browser http://127.0.0.1:8000/For-Sale-Listings/Taiz http://127.0.0.1:8000/For-Sale-Listings/Lahj It gives us the correct data, but when you request the address in JEX, it sends the request without giving us the data [06/Sep/2019 10:20:49] "GET /For-Sale-Listings/Taiz HTTP/1.1" 200 304194 here [06/Sep/2019 10:21:55] "GET /For-Sale-Listings/Taiz HTTP/1.1" 200 304194 here [06/Sep/2019 10:22:32] "GET /For-Sale-Listings/Lahj HTTP/1.1" 200 303411 [06/Sep/2019 10:22:32] "GET /static/js/scriptMap.js HTTP/1.1" 304 0 It should go to the application and give us the data for each city by address This is the view code class For_Sale_Listings(DetailView): template_name = 'Main.html' def get(self, request, *args, **kwargs): print('here') self.kwargs.setdefault('city', 'Taiz') places = Place.objects.filter(city=self.kwargs['city']).values_list('listing__price', 'image_main_path','address', 'latitude', 'longitude') kwargs['places_json'] = json.dumps(list(places), cls=DjangoJSONEncoder) return render(request, self.template_name, kwargs) This is the Ajax code $.ajax({ url: '/For-Sale-Listings/'+City.name, type: "GET", success: function(data){ alert(data); console.log(data); } }); And accept my regards -
Django PageNumberPagination customize error if page number out of range
I'm currently trying to create an API that return list of objects with page and limit per page input from url parameter using django-rest-framework which i already done in my api view with custom Pagination class PropertyListPagination(PageNumberPagination): page_size = 20 page_size_query_param = 'page_size' def get_paginated_response(self, data): return Response({ 'code': 200, 'data': data }) @api_view(['GET']) def property_list(request): if request.method == 'GET': paginator = PropertyListPagination() queryset = Property.objects.all() context = paginator.paginate_queryset(queryset, request) serializer = PropertySerializer(context, many=True) return paginator.get_paginated_response(serializer.data) Currently if a page is out of range( for example if i have only 2 object and i set my url to page=3 and page_size=1 then it should out of range of total objects) then in the response it will return a 404 status and in the body: { "detail": "Invalid page." } Is there a way to customize for it to return 400 status and the following json body ? { "code": 400, "error": "Page out of range" } Thank you -
Login existing user from db to django
I am newbie in Django, and I have problem with authentication users in django. I write some code, display users, but cannot login existing user in database using login and password. I have error 403 "CSRF token missing or incorrect." views.py from django.shortcuts import render from django.http import HttpResponse from django.http import HttpResponseRedirect from . import dbmodel_peoples from django.template import loader from django.contrib import auth from django.template.context_processors import csrf def login(request): c = {} c.update(csrf(request)) return render(request, 'login.html ', c) def auth_view(request): username = request.Post.get('username', '') password = request.Post.get('password', '') user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return HttpResponseRedirect('/my_app/index.html') else: return HttpResponseRedirect('/my_app/index.html') def loggedin(request): return render(request, 'index.html', {'login.peo_name': request.user.username}) urls.py urlpatterns = [ path('', views.index, name='index'), path('', views.login, name='login'), url(r'^login/$', views.login), models.py class Peoples(models.Model): peo_login = models.CharField(db_column='PEO_LOGIN', primary_key=True, max_length=50) peo_name = models.CharField(db_column='PEO_IMIE', max_length=255, blank=True, null=True) peo_pass = models.CharField(db_column='PEO_PASS', max_length=255, blank=True, null=True) login.html <form action="" method="post"> {% csrf_token %} <select list="employees" id="username" name="username"> <option hidden="">Login</option> {% for login in peoples %} <option value="{{login.peo_login}}">{{ login.peo_name }} </option> {% endfor %} </select> <br> <input placeholder="PASSWORD" value="" type="password" id="password" name="password">{{ login.peo_pass }} <br> <input type="submit" value="login" /> </form> Please, a help, how can I login users to my django app. -
Send two models to a template in django
I'm having a eCommerce web application in django and I have a base.html that my navigation bar and other stuff is included in that and other necessary templates extended from that. now I have a home.html that has a navbar that is extended from base.html and also my home page is going to show list of products. I want to show my categories from category table or model that I created and list the items from Product table or model. How should I do that??? Thanks in advance. -
Best practises in case of possibly large requested file which is needed to be fully displayed
The case Firstly I am a total beginner and unaware of web-related terminology, so sorry if this post is a duplicate. I am implementing a web app with Angular@6 and Django@2.2. In my app, I provide the users with a form with options. Based on the selected options, I request the backend for the relative results. The results are rows of the form {orderNumer: integer, message: string}. The number of rows, that the backend responds with, ranges from 0 up to 20k. The Problem and what I have done I am currently using Angular Material Table, requesting the whole file from django (no streaming) and since angular get the results, I am passing them into angular material table. The problem is that in case of 14k rows, the table displays this result with a delay of 12secs. I mean that from the time that all 14k rows are fetched to Angular from Django, there are 12 secs passed to be displayed. Some Limitations I have noticed about pagination, i.e. requesting data in chunks either when user scrolls or gets to the results next page. However, this is not the desired behavior in my app. I want the user to be … -
How to show the csv file on frontend in Django?
I am a beginner in Django and have a project of data scraping. I am trying to show CSV file on the front end. I have tried to send p_name variable to frontend but that doesn't work at all def index(request): if request.method == "POST": url = request.POST.get('url', '') r = requests.get(url) soup = BeautifulSoup(r.content, features="lxml") p_name = soup.find_all("h2",attrs={"class": "a-size-mini"}) p_price = soup.find_all("span",attrs={"class": "a-price-whole"}) with open('product_file.csv', mode='w') as product_file: product_writer = csv.writer(product_file) for name,price in zip(p_name,p_price): product_writer.writerow([name.text, price.text]) for name,price in zip(p_name,p_price): print(name.text) return render(request, 'index.html') `` index = <ul> {% if request.method == 'POST' %} {% for name in p_name %} <li> {% autoescape off %} {{name}} {% endautoescape %} </li> {% endfor %} {% endif %} </ul>