Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Best way to display quantity, product, brand and allow only quantity to be updated for all list
In Django 2.1 I need to be able to update the quantities in an order when click save button at the bottom of the page. So far the approach is to use a modelformset_factory but this leaves the product and brand open to be by the user and it is needed to display them as non-editable text. Is this the best aproach and how can I make ready only or display as normal text the fields product and brand while leaving quantity enabled to be changed? Here is the code: models.py class OrderLine(models.Model): order_number = models.ForeignKey('Order', blank=False, null=False, on_delete=models.CASCADE) product = models.ForeignKey('Product', blank=True, null=True, on_delete=models.CASCADE) quantity = models.DecimalField(max_digits=10, decimal_places=0, blank=True, null=True) brand = models.ForeignKey('Brand', blank=True, null=True, on_delete=models.CASCADE) forms.py class OrderLineForm(forms.ModelForm): class Meta: model = OrderLine fields = ['quantity','product','brand'] views.py def OrderLineUpdate(request): OrderLineFormSet = modelformset_factory(Levantamiento, form=OrderLineForm, extra=0) if request.method == "POST": formset = OrderLineFormSet(request.POST) if formset.is_valid(): formset.save() return HttpResponseRedirect('/orders/order-detail') else: formset = OrderLineFormSet(queryset=OrderLine.objects.all()) return render(request, 'order/detail/update.html', {'formset': formset} template update.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ formset.management_form }} {{ formset }} <input type = "submit" class ="btn btn-primary" value="Save"> -
How to enable column sorting on foreign fields in Django Admin
The following are my models: class A(models.Model): a_one = models.CharField() a_two = model.ForeignKey(B) class B(models.Model): b_one = models.Charfield() b_two = models.ForeignKey(C) class C(models.Model): c_one = models.CharField() c_two = models.CharField() I would like to create a table in django admin for model A with columns a_one, a_two, b_one, c_one, and c_two where all of them are sortable. How can I achieve this? -
TypeError: TypeError: expected string or bytes-like object. While i am trying to create django object
I am faced with issue while trying to create object from django models. I have the Fixture model from django.db import models from django.contrib.postgres.fields import JSONField import datetime from django.utils import timezone class Fixture(models.Model): fixture = models.IntegerField(primary_key=True) league_id = models.ForeignKey('League',null=True, on_delete=models.SET_NULL, to_field="league") event_date = models.DateTimeField(null=True) event_timestamp = models.DateTimeField(null=True) firstHalfStart = models.DateTimeField(null=True) secondHalfStart = models.DateTimeField(null=True) round_count = models.CharField(max_length=10) status = models.CharField(max_length=20) statusShort = models.CharField(max_length=15) elapsed = models.IntegerField(null=True) venue = models.CharField(max_length=170) referee = models.CharField(max_length=70) home_team_id = models.IntegerField(null=True) away_team_id = models.IntegerField(null=True) goal_of_home_team = models.IntegerField(null=True) goal_of_away_team = models.IntegerField(null=True) half_time_score = models.CharField(max_length=15) full_time_score = models.CharField(max_length=15) extratime = models.CharField(max_length=50) penalty = models.CharField(max_length=50) lastModified = models.DateTimeField(auto_now=True) I have json file where i store some json data from which i want to create objects of this model fixtures_date = open(os.path.abspath("/data/data/com.termux/files/home/storage/forecast/endpoints/leagues_date.txt"), "r") leagues_json = json.load(fixtures_date) leagues_json = leagues_json["api"]["fixtures"] for item in leagues_json: fixture_id = item["fixture_id"] league_id = item["league_id"] event_date = item["event_date"] event_timestamp = item["event_timestamp"] firstHalfStart = item["firstHalfStart"] secondHalfStart = item["secondHalfStart"] round_count = item["round"] status = item["status"] statusShort = item["statusShort"] elapsed = item["elapsed"] venue = item["venue"] referee = item["referee"] home_team_id = item["homeTeam"]["team_id"] away_team_id = item["awayTeam"]["team_id"] goal_of_home_team = item["goalsHomeTeam"] goal_of_away_team = item["goalsAwayTeam"] half_time_score = item["score"]["halftime"] full_time_score = item["score"]["fulltime"] extratime = item["score"]["extratime"] penalty = item["score"]["penalty"] Now i am trying to create objects … -
Making a new migration for a Django app, ignoring all other app models
I have made model changes to a Django model Bicycle in app bicycles in a project where another unrelated app cars has a model Car which has changes that has model changes without the accompanying makemigrations. The developer of cars.Car is unavailable and I cannot change their source code, but I still need to make a new migration for bicycles.Bicycle. Is this possible at all in Django 2.2? When I run makemigrations bicycles, I get this: You are trying to add a non-nullable field 'year' to car without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py Select an option: As I said, the bicycles app is completely unrelated to cars, so I feel like I should be able to make the migration for the bicycles app only? -
How to serialize a list of objects?
The Django-Rest-Framework documentation (https://www.django-rest-framework.org/api-guide/serializers/) gives the following example for serializing a list of objects: queryset = Book.objects.all() serializer = BookSerializer(queryset, many=True) serializer.data I try to do something similar with the following code: @api_view(['GET']) def postComments(request, pk): """ Retrieve all comments with originalPostId = pk. """ if request.method == 'GET': comments = Comment.objects.all() comments = comments.filter(originalPostId = pk) serializer = CommentSerializer(comments, many=True) if serializer.is_valid(): return Response(serializer.data) logger.error(serializer.errors) However, right off the bat I get the following error: AssertionError: Cannot call `.is_valid()` as no `data=` keyword argument was passed when instantiating the serializer instance. This other post (django-rest-framework: Cannot call `.is_valid()` as no `data=` keyword argument was passed when instantiating the serializer instance) seems to address this, but the answer suggests that putting in data= when calling my CommentSerializer would serve to deserialize instead of serialize, which is not what I want. However, when I do run with the line serializer = CommentSerializer(data=comments, many=True) I get the error{'non_field_errors': [ErrorDetail(string='Expected a list of items but got type "QuerySet".', code='not_a_list')]} Here is my serializer, in case that matters: poster = UserSerializer() community = CommunitySerializer() originalPost = PostSerializer() class Meta: model = Comment fields = ['post', 'community', 'poster', 'originalPost', 'originalPostId'] def create(self, validated_data): userData = … -
Make rows in Django table clickable
First off, I'm not a web developer. I'm just trying to write a simple web app for myself and I decided to do it in Django because I am very comfortable with Python. Anyway, my main page is essentially a django_tables2 table on the left side of the screen and a chart.js graph on the right. I've got the skeletons of both of these up. But now I cannot figure out to add click events to the rows in my table. What I'd like to do is have the graph updated whenever I click on a row in the table. If anyone has a simple example of this handy, that would be rad. I'm not sure what code you need from me, so just ask if there is something that would make it easier to see what I'm doing. -
Filter on Nested serializer - Django REST
I have the following models.py: class Question(models.Model): code = models.CharField(max_length=12) text = models.CharField(max_length=1000, null=True) catgeroy = models.ForeignKey( Category, on_delete=models.PROTECT, null=True, blank=True, db_index=True, related_name='category') class Answer(models.Model): question = models.ForeignKey( Question, on_delete=models.PROTECT, null=True, blank=True, db_index=True, related_name='question') exam = models.ForeignKey(Exam, on_delete=models.CASCADE) value = models.FloatField(null=True, blank=True) class Exam(models.Model): year = models.IntegerField() my nested serializer looks like this: class NestedQuestionAnswerSerializer(serializers.ModelSerializer): answer = AnswerSerializer(many=True, read_only=True) class Meta: model = Question fields = ( ('id','code', 'text', 'answer') ) class AnswerSerializer(serializers.ModelSerializer): related_name = 'answer' class Meta: model = Value fields = ('id', 'value', 'question', 'exam') my views.py looks like this: class QuestionAnswerViewSet(BaseCertViewSet): queryset = Question.objects.all() serializer_class = serializers.NestedQuestionAnswerSerializer filter_backends = [filters.DjangoFilterBackend] filterset_fields = ('category',) my urls.py looks like this: router.register('question-value', views.QuestionAnswerViewSet, 'question-answer') What I would like to be able to do is to filter by both Category AND Exam(which is a child attribute). So something like this: https://example.com/api/question-value?category=4&exam=21 This potentially should return all the Questions that are part of category=4 AND appeared on exam=21. I have no problem filtering by category alone, but can't seem to filter on exam which is a child foreign key. I've tried many solutions on SO but none seem to do the above. -
Allowing user to only create certain amount of objects with non-paid account, using Dajngo Stripe
I currently have a Personal CRM app that allow user to create Contacts and then create Logs for those contacts. Here is how the code looks like. views.py class CreateContact(LoginRequiredMixin, CreateView): model = Contact template_name = 'network/contacts_list.html' form_class = ContactForm def get_success_url(self): return reverse('home') def form_valid(self, form): form.instance.contact_owner = self.request.user return super(CreateContact, self).form_valid(form) def get_context_data(self, **kwargs): context = super(CreateContact, self).get_context_data(**kwargs) context['contacts'] = Contact.objects.filter(contact_owner=self.request.user) return context class CreateContactLog(LoginRequiredMixin, CreateView): model = ContactLog template_name = 'network/contact_detail.html' fields = ('log_type','body',) def get_success_url(self): return reverse('contact-detail', kwargs={'id':self.kwargs['id']}) def form_valid(self, form): current_contact = Contact.objects.get(contact_owner=self.request.user, contact_id=self.kwargs['id']) form.instance.contact_owner = self.request.user form.instance.contact_id = current_contact return super(CreateContactLog, self).form_valid(form) def get_context_data(self, **kwargs): current_contact = Contact.objects.get(contact_owner=self.request.user, contact_id=self.kwargs['id']) context = super(CreateContactLog, self).get_context_data(**kwargs) context["contact_info"] = current_contact context["first_name"] = current_contact.first_name context["id"] = current_contact.contact_id context['log_entries'] = ContactLog.objects.filter(contact_owner=self.request.user, contact_id=current_contact) return context Everything is working perfectly. Now I want to start accepting payments I want to integrate my app with Stripe. The best way to do this is with the third party package dj-stripe. I want to have 2 plans, free and paid. I want to allow free plan users to create up to 10 contacts. Reading the documentations for django-stripe I see that I can use class based views, but I dont't understand how I would approach … -
Django: conditionally override get_queryset
Django 1.11 I have two models. I would like to conditionally override the default behavior of their manager. class Project(models.Model): title = models.CharField(max_length=50) class Task(models.Model): title = models.CharField(max_length=50) project = models.ForeignKey(Project, null=True, blank=True, related_name='tasks') protected = models.BooleanField(default=False) objects = TaskManager() class TaskManager(models.Manager): def get_queryset(self): return super(TaskManager, self).get_queryset().exclude(protected=True) Tasks where protected = True should be filtered from any query not explicitly asking for them (I am aware the Django docs advise against filtering on overrides of get_queryset()) With the above code, any query on project.tasks returns all related tasks where protected = False, as expected. How can I conditionally override get_queryset() to return only related tasks where protected = True? Something like: project.protected_tasks or project.tasks.protected? -
App stuck on printing information from very first input
views.py from django.shortcuts import render, redirect from django.contrib import messages from .forms import AddmemberForm, Lookupmember from .models import Addmember def add_member(request): if request.method == 'POST': form = AddmemberForm(request.POST) if form.is_valid(): form.save() messages.success(request, f'The member has been added.') return redirect('front-page') else: form = AddmemberForm() return render(request, 'members/add.html', {'form': form}) def list_member(request): context = Addmember.objects.all() return render(request, 'members/list_members.html', {'context': context}) def look_up_member(request): if request.method == 'POST': form = Lookupmember(request.POST) if form.is_valid(): member_id = form.cleaned_data['member_id'] if Addmember.objects.filter(id = member_id): for x in Addmember.objects.all(): if Addmember.objects.filter(id = member_id): context = { 'name': x.name, 'email': x.email, 'address': x.address, 'city': x.city, 'state': x.state, 'zip_code': x.zip_code, 'phone_number': x.phone_number, } return render(request, 'members/about_members.html', context) else: messages.error(request, f'Error: This member does not exist.') return redirect('look_up_member') else: form = Lookupmember() return render(request, 'members/look_up_member.html', {'form': form}) The idea is to use a form that just takes one input, the member id. This is supposed to be a lookup feature. If no member exists with that ID, then an error appears. If the member ID does exist, then it's supposed to redirect to a page with the member's information. When I tested this for the very first time, I typed "1" for the member ID. This member does indeed exist, so I … -
I need a foolproof checklist for hosting an already built e-commerce site on Amazon Web Services
I have built an e-commerce website on my local computer that uses Django version 2.2 and python 3.7. The website consists of: fancyfetish is the main project directory. The apps, (cart, users, baseapp, products, blog) are all stored in their own directory 'apps. Within the settings folder I have three settings files: - production.py - base.py - development.py The static file in the main directory is where I put collectstatic files. Media is where I store externally uploaded images (product images for example) Docs is just random bits like a hand drawn site layout. Static files like JS and CSS are stored within baseapp, within apps. I want to host this website on Amazon Web Services, and I assume I need to use Elastic Beanstalk. I went through the process of trying to host with free version of EB, installed the EB CLI, and after using eb create and eb deploy on the CLI my website appeared. However, the static files didn't load properly in the first instance because I had not properly configured DJANGO_SETTINGS_MODULE. I have now done this. But before deploying I added eb migrate functionality so that I could also migrate my database. This seems to have … -
How to get or create credentials from authenticated user in django-allauth
I think I might be missing something obvious, but I cannot figure out the answer to my question. I have setup django-allauth on my project, added Google auth, enabled the API, ran the server, and successfully used the app for authentication. Here's where I'm getting stuck: Once the user is authenticated, I'm wanting the user to be able to view their calendar but I cannot figure out how to build the credentials using the credentials of the already authenticated user. I know that in order to get the calendar, I have to run: service = build('calendar', 'v3', credentials=creds) calendar = service.calendars().get(calendarId='primary').execute() print(calendar['summary']) but I cannot figure out how to build the value for credentials Any help would be so greatly appreciated. -
django cookiecutter compile sass in docker
I am running cookiecutter-django locally with docker. How do I compile the sass? I run the app by doing $ docker-compose --file local.yml up. When I edit the source code template files the web app reflects those changes at http://localhost:8000 When I edit static/sass/project.scss the site does not get the new css rules. I tried running $ docker-compose --file local.yml run --rm npm install but I get the message ERROR: No such service: npm. Resources that might help: https://cookiecutter-django.readthedocs.io/en/latest/live-reloading-and-sass-compilation.html https://cookiecutter-django.readthedocs.io/en/latest/deployment-with-docker.html#building-running-production-stack -
Can I make queries for tables which generated in pgAdmin without using SQL-scripts?
I have five tables in PostgreSQL database of my Django-project. I made two of these five tables as follows: made two classes/models in the models.py -> python manage.py makemigrations -> python manage.py migrate. I made other three tables as follows: I wrote scripts CREATE TABLE and INSERT some data into it using Query Editor of pgAdmin. I can retrieve objects from two first tables like here (first method) using Manager. But can I retrieve objects from three other tables (which I made in Query Editor of pgAdmin) using Manager (first method)? Now I don't understand how to do it because I don't have classes/models of three tables in models.py. Yes, I know about second method (using SQL script). But I would like to know there possibility to use only first method for tables created in Query Editor of pgAdmin is! -
Upload and overwrite CSV in specific location - django app
I currently have a django web app which reads in data from a csv and creates graphs using that data, the file hierarchy looks like this: csvparser csvparser init.py settings.py urls.py wsgi.py dataset admin.py apps.py models.py stored.csv ****** tests.py views.py The csv file that my graphs are made from (stored.csv) is included right in the application's folder, but now I want to have it so that I can upload any csv file (with the same headers) to that location with that name so that my app will do the same thing with an uploaded csv as it does with the current stored.csv. Essentially I just want to have functionality to upload a csv which overwrites the current stored.csv file at that location, is there an easy way to do this? -
Does git update or does git overwrite when pushing a sqlite database
FYI: Retired programmer new to git. Development platform is linux workstation. Current production is on Heroku. Framework is django using sqlite. Database is a flat file called db.sqlite3. When I push to Heroku using git, is the entire file of db.sqlite3 pushed from my workstation to the server? or Is some automagic worked so that the remote db.sqlite3 is only updated? (Obviously the latter is more efficient as the db grows in size.) thanks -
Discarding a Javascript file and using another one in an HTML template page in Django 2.2
I have an X.html web page which extends base.html. X.html is a django 2.2 template and extends base.html as below : {% extends 'base.html' %} {% load i18n %} {% load crispy_forms_tags %} {% block title %}{% trans "x-box" %}{% endblock title %} {% block content %} In the base.html page I have the below jQuery included: <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> This jQuery is included in X.html also. I want to discard the above jQuery for x.html and add the below jQuery in x.html : <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> Because the slim version causes problem for x.html. But I cannot delete slim version from base.html as it is extended by several other pages. -
Django 2.2. Instead of my template django uses the standard
I created an authapp application in django. And I registered it in settings and added to the main urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('authapp/', include('authapp.urls', namespace='authapp')), ] In authapp/urls.py I added: from django.contrib.auth import views as auth_views from django.urls import path, reverse_lazy import authapp.views as authapp app_name = 'authapp' urlpatterns = [ path('password_change/', auth_views.PasswordChangeView.as_view(success_url=reverse_lazy('authapp:password_change_done')), name='password_change'), path('password_change/done/', auth_views.PasswordChangeDoneView.as_view(), name='password_change_done'), ] I added my templates to authapp/templates/registration: - password_change_form.html - password_change_done.html But when you click on the link http://127.0.0.1:8000/authapp/password_change/ I get to standart form in the django admin, not my form... What am I doing wrong? -
How can I increase the field of my profile model from an updateview that changes a field of a diferent model?
Well, I am trying to gamify my school, and thus I have created three models aside of the User provided by Django. Model Profile, that extends the User through O2O Field, that includes the integer field called experienced that I want to increase. class Profile(models.Model): # EXTENDINNG USER MODEL user = models.OneToOneField(User, on_delete=models.CASCADE,related_name='profile') # PERSONAL DATA pic = models.ImageField(upload_to='accounts/media/profile_pics', blank=True) telefono = models.CharField(max_length=12, blank=True) location = models.CharField(max_length=30, blank=True) born_date = models.DateField(null=True, blank=True) #CADA PUNTUACIÓN SE SUMARA A LA EXPERIENCIA DEL JUGADOR experience = models.PositiveIntegerField(null=True, blank=False, default=0) skills = models.ManyToManyField('Skill', verbose_name = 'skill',blank = True, through='Gamification') Model Skills, that reflects the technics that a pupil must learn. Model Gamification, it is connected to the other two models by a M2M Field inserted in Profile, with the attribute "through" pointing to it and a Foreign Key linking it to Skills, inserted in this model. plus the two FK fields corresponding tu Profile and Skill class Gamification(models.Model): class Meta: ordering = ['trainned'] profile = models.ForeignKey(Profile, on_delete=models.CASCADE,null=True) skill = models.ForeignKey(Skill, on_delete=models.CASCADE,null=True) trainned = models.DateTimeField(auto_now=True) # MARKS poor = '1' slow = '2' enough = '3' fast = '4' pro = '5' # LISTA DE TUPLAS Per_opt = [(poor,'1'),(slow,'2'),(enough,'3'),(fast,'4'),(pro,'5')] #CADA SKILL TENDRA UNA PUNTUACION performance … -
Build web site with Django
I wouldlike to build a new website when you write your name for example in a searchbar (cf pictures) and after submit you have another page with some informations about yourself : Main Page After submit your name What is the best way to start something like this ? Thank you for your help ! -
ModuleNotFoundError: No module named 'onelogin.saml2?
I am trying to run an existing django project on a local server. When I run: python manage.py migrate I get an error of missing a module for example: pil, boto3, request-logging, raven etc. I already installed it with pip install ... But then this error pops up: ModuleNotFoundError: No module named 'onelogin.saml2' I dont know which module to install, I already looked it up online and solutions like 'pip install python3-saml' didnt work? What am I doing wrong -
Django session: disconnect when user is inactive
is there a simple way to disconnect a user that is inactive for 3 minutes for example? I have develop an authentification app following a tutorial (https://simpleisbetterthancomplex.com/) https://www.youtube.com/watch?v=60GTvKCuam8&list=PLLxk3TkuAYnryu1lEcFaBr358IynT7l7H I use 'from django.contrib.auth import views' so I did not have write the login/logout/... views and have the default authentification behavior here I need to customize the behavior so I suppose I need to override the logout view? How can I do that? -
Why won't the image be displayed in Django?
I have a model with an ImageField, and I want to display it on my HTML, but it does not work, it displays only the alt attribute. My model: class HomePage(models.Model): # Fields image = models.ImageField(upload_to='main_image', blank=False) class Meta: pass def __str__(self): return str(self.pk) def get_absolute_url(self): return reverse("PizzaDeliverySystem_HomePage_detail", args=(self.pk,)) def get_update_url(self): return reverse("PizzaDeliverySystem_HomePage_update", args=(self.pk,)) My HTML file: <div class="text-center rounded mb-12"> <img class="img-fluid rounded" src="{{ homepage.image.url }}" alt="Főoldal kép"/> </div> -
Use pandas in a django view function to load data from a csv
I want to display time series data in a django application. The data is currently available in a csv-format. The simplest solution that came to my mind was to load the data using pandas in the view function, then perform my desired processing with it and supply the processed data to the HTML template in the context dictionary: def view_function(request): df = pd.read_csv('data/test.csv') # Any further processing of the loaded Dataframe # that returns df_processed context = { 'data': df_processed} return render(request, 'template.html', context) However, since I am new to web development, I wondered if this would be the way how to do it or if there are actually severe problems attached to this solution? If yes, what would be a better way how to do it? -
Unable to generate id for dynamically added table rows - Django dynamic formset
I am trying to implement Django inline formset (with a parent and child scenario) with an option to add rows for the child fields housed in a table. For the purpose I am using Django dynamic formset which is working in so far as the default form layout is concerned as well as adding new rows at runtime. I am able to save and edit data as well, even with the new rows added. However I find, to my dismay, that the id's of the newly added row elements are not generated (when viewed in "view source") - actually there are no reference to the newly added elements at all. Am I missing something or is this the wrong way to go for what I am trying to do, considering that the plugin is pretty "old" and by the looks of it, there has not been much activity on the source page. (I found one user asking whether the plugin may be used with Django 2.0!) The reason I want the id's of individual field elements is, that I need to carry out calculations involving values contained, using jQuery before I submit the form. Without the id's I can not …