Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django template url issue
I have set up dynamic linking from a ListView which worked fine, but now that I am filtering the ListView any links from the template are appending the current url. Here is my urls.py: urlpatterns = [ path('list/<area>/', ProjectListView.as_view(), name='project-list'), path('project-create/', ProjectCreateView.as_view(), name='project-create'), path('<slug:slug>/update/', project_update_view, name='project-update'), path('search/', search, name='search'), ] in the template my link looks like this: <h3><a href="{{ project.slug }}/update">{{ project.title }}</a></h3> and I was hoping it would look here: http://127.0.0.1:8000/si/ but instead it is looking here: http://127.0.0.1:8000/si/list/All/ of which "list" was added to prevent other urls matching wrongly, which I can just add if necessary, and "All" which comes from a dynamic variable from the filter and will be one of 8 different strings. How can I get this url to look at where I specified in the urls.py and not just append the current url? -
Get data from one model to another in form of check buttons and then save the checked buttons in different model
I am working on a problem that requires to add choices. User will enter the things they Like one by one. I'll use formset for that. My Like model is like this class Likee(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ans = models.CharField(max_length=1024) Let's suppose User has entered 10 things here. What I want to do is to present a form that has Checkbuttons against the entries provided by user. These will define all the things that the user Need. I want user to select/descelect from all the entries and once he presses Next button, I want to save all the in the DB in a Need model. How can this be achieved? What will the Need model,form,view be like? I am out of ideas here. -
Django form template doesn't show form-field
My form: <form id="myform2" method="get" > {{ filter.form}} </form> I need to custom django-filter form template like this: <form id="myform2" method="get" > <div class='myClass'> <label>Label: </label> {{ filter.age_filter}} </div> </form> But html page doesn't show {{ filter.age_filter}} and I don't understand why. Can somebody help me please? My filter.py: class EventFilter(django_filters.FilterSet): AGE_CHOICES = ( ('18+', '18+'), ('19+', '19+'), ('21+', '21+'), ) age_filter = django_filters.ChoiceFilter(label='🔞', choices=AGE_CHOICES, method='filter_by_age') class Meta: model = Event fields = [] def filter_by_age(self, queryset, name, value): return queryset.filter(age_limit=value) -
Cannot convert Django Queryset to a List [duplicate]
This question already has an answer here: Django values_list vs values 3 answers at first I want to mention that I have already searched in stackoverflow for an answer. However the answers I found did not solve my problem (and one answer was too complicated to understand and therefore did't work). My problem is: I created the following query: my_books = Book.objects.values('title') print(my_books) The output is: <QuerySet [{'title': 'It do go down'}, {'title': 'Second Post'}, {'title': 'Tesla - A New Generation'}]> Now I want to change the QuerySet to give me back a list which should look like this: ['It do go down', 'Second Post', 'Tesla - A New Generation'] What do I have to do in order to get the result above? Best regards Lambrini PS: What I tried was an answer to a related question: print(list(my_books)) which showed the following: [{'title': 'It do go down'}, {'title': 'Second Post'}, {'title': 'Tesla - A New Generation'}] Furthermore I tried an iteration, which didn't work at all. -
Role Based Access Control for different API methods in Django REST Framework
I am creating REST API for Product, which has following Permission, (create_product, view_product, edit_product). In my Project I am having various users with different roles (Ex: Producer, Retailer, Consumer,...etc). I am assigning permission to individual Roles. Example: The "Producer" role has "create_product" and "view_product" permission. The "Retailer" role has "edit_product" permission. The "Consumer" role has no permission. I want to restrict the Access based on the permission code. I need a generic approach to solve this. I want to use the same approach for different views with different permission codes. In my view.py, class Product(viewsets.ModelViewSet): serializer_class = ProductSerializer queryset = Product.objects.all() In settings.py, I have added following code. REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', ), } Thanks in advance. -
How to run waitress on Django app deployed on Heroku with specified port on windows
I am trying to host my django app using heroku and waitress package in windows environment. I have defined the procfile for running wsgi application . Where do we need to define the correct port and run the heroku app? This is for a new windows server running django app and heroku. In the past, I have tried on defining various port numbers on procfile to run the app,but it not worked and shows error on permission. Procfile: web: waitress-serve --port=80 ACE:wsgi.application I expect the django app to run on heroku inn browser, using command -heroku local web The output which I got is: [OKAY] Loaded ENV .env File as KEY=VALUE Format 16:15:41 web.1 | Traceback (most recent call last): 16:15:41 web.1 | File "c:\users\ramakrishnan_k\appdata\local\programs\python\python36-32\lib\runpy.py", line 193, in _run_module_as_main 16:15:41 web.1 | "main", mod_spec) 16:15:41 web.1 | File "c:\users\ramakrishnan_k\appdata\local\programs\python\python36-32\lib\runpy.py", line 85, in _run_code 16:15:41 web.1 | exec(code, run_globals) 16:15:41 web.1 | File "C:\Users\ramakrishnan_k\AppData\Local\Programs\Python\Python36-32\Scripts\waitress-serve.exe__main__.py", line 9, in 16:15:41 web.1 | File "c:\users\ramakrishnan_k\appdata\local\programs\python\python36-32\lib\site-packages\waitress\runner.py", line 279, in run 16:15:41 web.1 | _serve(app, **kw) 16:15:41 web.1 | File "c:\users\ramakrishnan_k\appdata\local\programs\python\python36-32\lib\site-packages\waitress__init__.py", line 11, in serve 16:15:41 web.1 | server = _server(app, **kw) 16:15:41 web.1 | File "c:\users\ramakrishnan_k\appdata\local\programs\python\python36-32\lib\site-packages\waitress\server.py", line 85, in create_server 16:15:41 web.1 | sockinfo=sockinfo) 16:15:41 … -
ModelForm and ModelSelect2Widget (django-select2)
I have a ModelForm which includes a ModelSelect2Widget from django-select2 https://github.com/applegrew/django-select2 Following the Documentation from here: https://django-select2.readthedocs.io/en/latest/django_select2.html#django_select2.forms.ModelSelect2Widget forms.py class RentalForm(forms.ModelForm): name = forms.ChoiceField( widget=ModelSelect2Widget( model=ldap_data, search_fields=['user__icontains'] ) ) date_start = forms.CharField(label="Datum Ausleihe", help_text="", widget=forms.TextInput(attrs={'class': 'form-control form-control-sm', 'placeholder': '01.01.2019' })) date_end = forms.CharField(label="Datum Rückgabe", help_text="", widget=forms.TextInput(attrs={'class': 'form-control form-control-sm', 'placeholder': '01.01.2019' })) class Meta: model = Rental fields = ['device', 'name', 'date_start', 'date_end',] models.py class ldap_data(models.Model): user = models.CharField(max_length=1024) def __str__(self): return self.user ldap_data contains around 100 entries. In my opinion everything looks fine, but in the rendered template no data is available in the name dropdown. -
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' %}">