Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF not updating model in put/patch request in test
I'm trying to test an update of a model in the Django Rest Framework My test looks like this: class MyModelTest(APITestCase): def setUp(self): self.client = APIClient() self.url = reverse('MyModels-list') # Setup a dummy model for testing self.assignment = f.MyModelFactory( allocation__end_year=2020, transfer_status=None, user__id=45 ) self.true_form_data = { 'signature': 'TT', 'returning': True, 'confirmed_at': datetime.now() } def test_patch_request_updates_object(self): """ Ensure a patch request will work as expected. """ my_model = MyModel.objects.filter( id=self.assignment.id ).first() # print returning (blank) as expected print(my_model.returning) response = self.client.put( self.url+str(self.assignment.id), self.true_form_data, follow=True ) my_model = MyModel.objects.filter( id=self.assignment.id ).first() # !!This should now be True - but is still blank!! print(my_model.returning) self.assertEqual(my_model.signature, 'TT') Currently - it works when I run the local server. I make an ajax call like this (from my views.py): if form.is_valid(): user_id = request.user.id api_app = settings.PROJECT_API api_model = 'my_model/' api_fte_id = request.POST['MyModelId']+'/' # Build the data to pass the api data = {} data['signature'] = request.POST['signature'] data['returning'] = request.POST['returning'] data['confirmed_at'] = datetime.now() requests.patch(api_app+api_model+api_fte_id, data=data) return redirect('app:confirmation') That works fine and is what I am trying to replicate with my tests. What could be the rub? I'm sure I'm missing something really obvious... but I can't figure out how/why it works in the local server, but … -
Geo Django GDAL "The specified procedure could not be found" error
I've been trying to get geodjango working, and I'm getting a strange error. I've followed the installation steps, set all the environment variables, and followed the issues and solutions presented here. I now have an issue that I can't understand, and I'm hoping the community can help. The error returned is "The specified procedure could not be found" when running python manage.py check or trying to debug the django application. I've tried both of the approaches below: import os if os.name == 'nt': import platform OSGEO4W = r"C:\OSGeo4W64" os.environ['OSGEO4W_ROOT'] = OSGEO4W os.environ['GDAL_DATA'] = OSGEO4W + r"\share\gdal" os.environ['PROJ_LIB'] = OSGEO4W + r"\share\proj" os.environ['PATH'] = OSGEO4W + r"\bin;" + os.environ['PATH'] and GDAL_LIBRARY_PATH = 'C:\\OSGeo4W64\\bin\\gdal204.dll' and receive the error no matter what. I'm running django 2.2 and python3.7.2. What do I do to get this working? Thanks! -
Change Django-Rest-Framework serializer from flat to nested?
As per this example of nested and flat: https://docs.python-guide.org/scenarios/serialization/ I want the foreign key to represented from the following JSON output { "cart": { "cartid": "C0001", "username": "myuser1" }, "subtotal": 150.0, "start_day": "2019-03-20T00:00:00" }, to be represented like: { "C0001": { "username": "myuser1" }, "subtotal": 150.0, "start_day": "2019-03-20T00:00:00" }, Is there a simple way to have this output in django-rest-framework? -
Django doesn't understand if a field in the database is empty
So I am working on an API. A GET request which has a condition so as to generate render one field or the other. But to my surprise, is None does not work for a field that is empty. How do I solve this problem? Here is my table for example: -------------------------------------------------------------------------- | ms | offer_id | priprity_one | priority_two | priority_three -------------------------------------------------------------------------- | 89899 | | priority_one | priority_two | priority_three | 32323 | 3021 | priority_one | priority_two | priority_three | 12321 | 3022 | priority_one | priority_two | priority_three | 43421 | 3023 | priority_one | priority_two | priority_three views.py from mamo.models import Mamo from rest_framework import generics from mamo.serializers import MamoSerializer from django.http import Http404 from IPython import embed class OfferView(generics.ListAPIView): serializer_class = MamoSerializer lookup_field = 'ms' def get_queryset(self): msisdn = self.kwargs['ms'] try: return Mamo.objects.filter(ms=ms) except Mamo.DoesNotExist: raise Http404 def get(self, request, *args, **kwargs): queryset = self.get_queryset() serializer = self.serializer_class(queryset, many=True) if serializer.data[0]['offer_id'] is not None: result = serializer.data[0]['priority_one'] elif serializer.data[0]['offer_id'] is None: # This line dont work result = serializer.data[0]['priority_two'] else: result = serializer.data[0]['priority_three'] return Response(result) To make it work, this is what I have done below, but I believe it doesn't make sense. I … -
How to form data for select?
There is a model Provider. It has the field role, which has two options: Individual and Organization. There are summary field and organization field. It is necessary that in the form (in the template), in the select, the data is displayed in the following way: if the record is associated with Individual, then summqry + user, and if with the Organization, then the Organization title. models.py ROLE_INDIVIDUAL = 'individual' ROLE_ORGANIZATION = 'organization' ROLE_CHOICES = ( (ROLE_INDIVIDUAL, _('Individual')), (ROLE_ORGANIZATION, _('Organization')) ) class Provider(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) role = models.CharField(max_length=255, choices=ROLE_CHOICES, default=ROLE_INDIVIDUAL) summary = models.CharField(max_length=255, default='') organization = models.ForeignKey(Organization, on_delete=models.CASCADE) forms.py class ProductCreateForm(forms.ModelForm): class Meta: model = Product fields = (..., 'on_behalf', ...) def __init__(self, *args, **kwargs): self.request = kwargs.pop('initial').get('request') super(ProductCreateForm, self).__init__(*args, **kwargs) self.fields['on_behalf'] = ModelChoiceField(queryset=Provider.objects.filter(user=user.id)) -
How to integrate "prefetch_related" data into queryset and serializer?
Hello stackoverflow community, i have two models with random data about Phones. The Queryset sends the Min Price Value of each phone to my API... models.py class Phone(models.Model): name = models.CharField(max_length=200) description = models.CharField(max_length=400) image = models.ImageField(upload_to='phone_img/', max_length=255, null=True, blank=True ) slug_phone = models.SlugField(blank=True) <...> class Price(models.Model): price = models.DecimalField(max_digits=6, decimal_places=2) date = models.DateField(null=True, blank=True) phone = models.ForeignKey(Phone, on_delete=models.CASCADE) market = models.ForeignKey(Market, on_delete=models.CASCADE) views.py class PhoneAPI(generics.ListAPIView): queryset = Phone.objects.annotate(min_price=Min('price__price')) serializer_class = PhoneSerializer serializers.py class PhoneSerializer(serializers.ModelSerializer): min_price = serializers.IntegerField() class Meta: model = Phone fields = '__all__' Till here everything works fine, i get the min_price of each phone in my database represented in my API. API Output {"count":7,"next":null,"previous":null,"results":[{"id":10,"min_price":718,"name":"SAMSUNG Galaxy S10","description":"SAMSUNG Galaxy S10, Smartphone, 128 GB, Prism Black, Dual SIM","image":"http://127.0.0.1:8000/media/phone_img/galaxy_s10.jpg","slug_phone":"samsung-galaxy-s10"}, <...and so on...> The Question i have is, how to access the object wich is related to the min_price of each phone? For instance the Price.date and or Price.market of the Phone.models. So i read about "prefetch_related" and tried in my view / queryset. views.py class PhoneAPI(generics.ListAPIView): queryset = Phone.objects.prefetch_related('price_set').annotate(min_price=Min('price__price')) serializer_class = PhoneSerializer So far my API did not broke but i also shows no related data. Do i need a specific field in my serializers.py do represent the data? -
Need help to render img in pdf from template
I'm building a project were i need to get my data into pdf from a template (html), my problem is that the image is not apearing on pdf view. This is my code: class GeneratePdf_month(TemplateView): template_name = "polls/info_month.html" def get(self, request, *args, **kwargs): ## do some.... data = { 'cliente': cliente, } pdf = render_to_pdf(self.template_name, data) return HttpResponse(pdf, content_type='application/pdf') ## and this is my html template <head> {% load staticfiles %} <title>Detail</title> <style> table, th, td { border: 1px solid black; border-collapse: collapse; padding: 10px; } </style> </head> <body> <header>BlaBla<img src="{% static 'polls/images/image.png'%}"></header> </body Can someone help me? -
Unable to send Email using Django
Internal Server Error: /index/ Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/pradeep/Desktop/avinkey-pradeepavula (11)/tecum1/pr1/views.py", line 12, in index send_mail('subject', 'message', settings.EMAIL_HOST_USER, ['avulapradeep333@gmail.com'] , fail_silently=False) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/mail/__init__.py", line 60, in send_mail return mail.send() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/mail/message.py", line 291, in send return self.get_connection(fail_silently).send_messages([self]) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/mail/backends/smtp.py", line 103, in send_messages new_conn_created = self.open() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/mail/backends/smtp.py", line 63, in open self.connection = self.connection_class(self.host, self.port, **connection_params) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/smtplib.py", line 251, in __init__ (code, msg) = self.connect(host, port) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/smtplib.py", line 338, in connect (code, msg) = self.getreply() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/smtplib.py", line 394, in getreply raise SMTPServerDisconnected("Connection unexpectedly closed") smtplib.SMTPServerDisconnected: Connection unexpectedly closed Will be able to send Email from Django form -
Django admin select m2m items based on another m2m field of the items
Consider following models: class Library(models.Model): name = models.CharField(max_length=64) books = models.ManyToManyField(Book) class Book(models.Model): name = models.CharField(max_length=64) tags = models.ManyToManyField(Tag) class Tag(models.Model): name = models.CharField(max_length=64) In the Library admin I want to add books based on their tags, while retaining the option to add/remove single books. Existing options: Filter_horizontal - filters by __str__, is there a way to filter by tags__name? Raw_id_fields - works with any filters specified for Book, but you can only select 1 item. Is there a way to allow selection of more items? (checkboxes in the table) -
Use query parameter like "?name=" from url in a template
Django debug toolbar shows me in GET parameters that I have a variable 'name' in my get parameters, which is normal. I'd like to get this 'name' value to fill the form placeholder. I've tried {{ view.get.name }} or {{ request.name }} or... {{ name }} with no success. -
Login in and Logout with multiple users with Django test
I am trying to: 1) Login with testUser_1 2) Perform some action 3) Logout from testUser_1 4) login in with testUser_2 My goal is to view the page from testUser_2 perspective to see what did testUser_1 do Here is my code: def someTest(self): self.assertTrue(self.client.login(username='testUser_1',password='testPassword_1')) #user-1 performs some action self.client.post(reverse('page:logout'), follow=True) self.assertTrue(self.client.login(username='testUser_2', password='testPassword_2')) request = self.client.get(reverse('page:view2')) print(request.content) The print(request.content) does not return the action testUser_1 performed. How can I ensure that I am viewing the page from testUser_2 perspective? -
IntegrityError at /contacts/import
in django when i am going to import csv file and parse it i am getting following erro django.db.utils.IntegrityError: NOT NULL constraint failed: inven_app_clientcontact.author_id [29/Apr/2019 17:56:32] "POST /contacts/import HTTP/1.1" 500 188071 here is my code @login_required def contact_upload(request): template = 'site/contact_upload.html' prompt = { 'order': 'Order of the CSV should be client_name, client_company_name, email, work_phone' } if request.method == 'GET': return render(request, template, prompt) csv_file = request.FILES['file'] if not csv_file.name.endswith('.csv'): messages.error(request, 'This is not a csv file') data_set = csv_file.read().decode('utf-8') io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter=',', quotechar='|'): _, created = ClientContact.objects.filter(author=request.user).update_or_create( client_name=column[0], client_company_name=column[1], email=column[2], work_phone=column[3] ) context = {} return render(request, template, context) any help would be appriciated. Thank you. If any code is needed please let me know -
sending checkbox array from js to django views
I'm confused about how to do it via Ajax or Json, but how can I send the selection array (curCheck) on-click to Django views and receive it as a python array javascript document.getElementById('results').addEventListener('click', function(){ html_table = '<thead><tr><th>Currency</th><th>Amount</th><th>Symbol</th>><tr/><thead/>' var checkElements = document.getElementsByClassName('ch'); for(var i =0; i< curname.length; i++){ if (checkElements[i].checked) { var curChecked = curname[i]; var JsonArr = JSON.stringify(curChecked); postcurChecked(JsonArr) html_table += '<tr><td>' + curname[i] + '</td>'; } } document.getElementById('result_table').innerHTML = html_table; },false; ajax function postsubChecked(curChecked) { $.ajax({ "url": "http://127.0.0.1:8000/results/", "type": "POST", "data": {"checkbox": curChecked}, "headers": { 'X-CSRFToken': getCookie('csrftoken')} }) } in django def currencyChecked(request): body_unicode = request.body.decode('utf-8') body_unicode = body_unicode.replace('%22','') print(body_unicode) json_data = json.loads(body_unicode.read()) I would like to see the python array print to see it is passed to the back but I keep getting this error: json_data = json.loads(body_unicode.read()) AttributeError: 'str' object has no attribute 'read' -
Is there a way to aggregate a field in Django Rest Framework that will have the summation of one field
Currently I've figured it out on how to aggregate a single column in my serializers.py but the sum of my salary field will go to the total_salary field in my serializer and total_salary isn't in my models. Now my problem is that how can I do something like this in my API below: "total_salary": 1422.05, { "id": "8c1810d9-b799-46a9-8506-3c18ef0067f8", "date": "2019-04-27", "virtual_assistant": "Joevie", "time_in": "2019-04-27T22:20:13+08:00", "time_out": "2019-04-28T05:20:13+08:00", "hours": "7.00", "client_name": "landmaster", "rate": "90.00", "salary": "630.00", "status": "APPROVED-BY-THE-MANAGER", "notes": "" }, The existing one is like this. { "id": "8c1810d9-b799-46a9-8506-3c18ef0067f8", "total_salary": 1422.05, "date": "2019-04-27", "virtual_assistant": "Joevie", "time_in": "2019-04-27T22:20:13+08:00", "time_out": "2019-04-28T05:20:13+08:00", "hours": "7.00", "client_name": "landmaster", "rate": "90.00", "salary": "630.00", "status": "APPROVED-BY-THE-MANAGER", "notes": "" }, Currently a workaround I did is I get the sum of the salary in the ListView as of now, and each time the user will search for a specific month. The computation will change based on the month that the user searched for. Code below. def get(self, request, *args, **kwargs): search = request.GET.get('search') user = request.user.staffs.full_name current_month = datetime.date.today().month current_year = datetime.date.today().year payroll_list = VaPayroll.objects.all() payroll_data = payroll_list.filter(Q(virtual_assistant=user), Q(date__month=current_month), Q(status='APPROVED-BY-THE-MANAGER')) total_salary = VaPayroll.objects.filter(Q(virtual_assistant=user), Q(date__month=current_month), Q(status='APPROVED-BY-THE-MANAGER'), Q(date__year=current_year)).aggregate(Sum('salary')) if search: payroll_data = payroll_list.filter(Q(virtual_assistant=user), Q(status='APPROVED-BY-THE-MANAGER'), Q(date__icontains=search)) total_salary = VaPayroll.objects.filter(Q(virtual_assistant=user), Q(status='APPROVED-BY-THE-MANAGER'), Q(date__month=search), Q(date__year=current_year)).aggregate(Sum('salary')) … -
Render object in Django that have Status = Accept or Reject separately in a specific template
I am new to Django. I am working on a project where if client click on a "accept or reject" button then that object will also appears in their respective templates. For example if a client click on accept button then that object will be appear in accept .html file and the same will be work with reject button.I have no idea how can I do this. this is my accept .html file: <div class="body table-responsive"> <table class="table table-hover"> <thead> <tr> <th>S No.</th> <th>COMPANY NAME</th> <th>TEAM MEMBER</th> <th>EMAIL</th> </tr> </thead> <tbody> {%for team in object%} <tr> <th scope="row"> {{ forloop.counter }}</th> <td>{{team.company_name}}</td> <td>{{team.team_member}}</td> <td>{{team.email}}</td> </tr> {% endfor %} </tbody> </table> here it is rendering all the objects that are in database but i want that only those object are displayed here which have Status = "accept" and the same should be work with reject status. here is my model.py first_name = models.CharField(max_length= 50) last_name = models.CharField(max_length= 50) company_name = models.CharField(max_length= 100) address = models.CharField(max_length= 1000) state = models.CharField(max_length= 100) city = models.CharField(max_length= 100) pin_code = models.CharField(max_length= 100) status = models.CharField(max_length= 30) here is my views.py '''def accept(request): obj= Create_Team.objects.all() return render(request, "admin/accept.html", {"object": obj}) ''' and the same is my … -
How to run Facebook authentication on localhost in Django?
I have red all discussion about this matter on stackoverflow but all of them seem outdated. Does anyone know how to run facebook authentication on localhost in django by social-auth-app-django ? I have spent probably a day or so trying to solve it but nothing works. enter image description here AUTHENTICATION_BACKENDS = ( 'social_core.backends.facebook.FacebookOAuth2', "social_core.backends.vk.VKOAuth2", "django.contrib.auth.backends.ModelBackend" ) SOCIAL_AUTH_URL_NAMESPACE = 'social' SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.social_auth.associate_by_email', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) SOCIAL_AUTH_STRATEGY = 'social_django.strategy.DjangoStrategy' # new SOCIAL_AUTH_STORAGE = 'social_django.models.DjangoStorage' # new # facebook #FACEBOOK_APP_ID = ' xxx' #FACEBOOK_API_SECRET = ' xxx' SOCIAL_AUTH_FACEBOOK_KEY = ' xxx' # new SOCIAL_AUTH_FACEBOOK_SECRET = 'xxx ' # new SOCIAL_AUTH_FACEBOOK_SCOPE = ['email'] SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = { 'fields': 'id,name,email', } SOCIAL_AUTH_ADMIN_USER_SEARCH_FIELDS = ['username', 'first_name', 'email'] MIDDLEWARE = [ 'debug_toolbar.middleware.DebugToolbarMiddleware', # new 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware', # new 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', -
Django 2.2 TemplateDoesNotExist
I've just started with django. I'm finding so many question about this problem, but I see most of all are outdated. I guess something has changed between 2.1 and 2.2. This is my tree . |____posts | |____migrations | | |______init__.py | |____models.py | |______init__.py | |____apps.py | |____admin.py | |____templates | | |____posts | | | |____index.html | |____tests.py | |____urls.py | |____views.py |____django_project | |______init__.py | |____settings.py | |____urls.py | |____wsgi.py |____manage.py This is the content of posts/views.py def index(req): return render(req, 'posts/index.html') When I try to access http://127.0.0.1:8000/posts/ I get the error TemplateDoesNotExist at /posts/ To me it looks like I've done exactly what https://docs.djangoproject.com/en/2.2/topics/templates/ says. What am I missing? -
i have problems with django
i am trying to run my app with command: python manage.py runserver and its give me the error: raise ImproperlyConfigured('mysqlclient 1.3.13 or newer is required; you have %s.' % Database.__version__) django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3. -
Getting 'QuerySet' object has no attribute '_meta' error while serializing list of models
I understand this particular error message 'QuerySet' object has no attribute '_meta' has been discussed a lot on StackOverflow and I have gone through lots of the answers provided but each is unique and didn't solve my problem. So, I have a list of filtered model objects I'm getting from a database: questions_by_category = Question.objects.filter(category=category_id) I want to save this list in the session like this: request.session["questions"] = json.dumps(model_to_dict(questions_by_category)) but I'm getting the error message specifically from this line: model_to_dict(questions_by_category) This is the model class: class Question(models.Model): question_text = models.CharField(max_length=200) correct_answer = models.CharField(max_length=20) publication_date = models.DateTimeField('date_published', default=django .utils.timezone.now) question_hint = models.CharField(max_length=200, default='hint') question_thumbnail = models.ImageField(upload_to='gallery', height_field=None, width_field=None, max_length=100, default='images/pyramid.jpg') category = models.ForeignKey(QuestionCategory, on_delete=models.SET_NULL, null=True) difficulty_level = models.IntegerField(default=10) def was_published_recently(self): return self.publication_date >= timezone.now() - datetime.timedelta(days=1) class Meta: db_table = 'question' def __str__(self): return self.question_text def serialize(self): return self.__dict__ And the view: def question(request, category_name, category_id): questions_by_category = Question.objects.filter(category=category_id) current_question = questions_by_category.iterator().__next__() choice = current_question.choice_set.get() form = ChoiceForm(request.POST) request.session["questions"] = json.dumps(model_to_dict(questions_by_category)) context = { 'question': current_question, 'choice': choice, 'form': form } return render(request, 'quiz/question.html', context) I'd really appreciate an explanation on what I'm doing wrong and the right way to go about this. -
What is the most db efficient way to get specific fields of a foreign key in a queryset using Wagtail page models
So I have this model: class FieldPosition(Orderable): page = ParentalKey('PlayerDetailPage', on_delete=models.CASCADE, related_name='field_position_relationship') field_position = models.CharField(verbose_name=_('Field position'), max_length=3, choices=FIELD_POSITION_CHOICES, null=True) And this Wagtail page model: class PlayerDetailPage(Page): content_panels = [ InlinePanel('field_position_relationship', label=_('Field position'), max_num=3), ] I made a property in the page model: @property def position(self): position = [ n.field_position for n in self.field_position_relationship.all() ] return position So I can access the field_position in my template with: {% for p in page.position %} {{ p }} {% endfor %} But is there any better way to do this? I feel like I am hitting the database too much and I have a lot of queries. I would prefer something like: PlayerDetailPage.objects.values('field_position_relationship__field_position') But then I get the values of all PlayerDetailPage entries , I just want the value of the particular page that is displaying. How can I achieve something like that? -
multiple file upload in django rest framework
I want to create an API using DRF where I want to upload two files in two different name and a text field with a string of json. The figure below shows my postman attempt to the API. Please help me to write my API properly. I looked for several posts in stack overflow but did not get any proper solution. I dont have any models according to the input but I want to create a standalone API and want to manipulate these files and json at runtime. -
DRF Serialier - How to return field of a foreign key?
Good morning, I am really struggling with an issue returning a value from my Django Rest Framework API. I have two models, SirTarget & Status. The SirTarget is like a ticket & the Status is a textual status label of the ticket that corresponds to the phase of handling the ticket. The models are as follows: class Status(models.Model): status_text = models.CharField(max_length=20) status_open = models.BooleanField(default=1) def __str__(self): return self.status_text class SirTarget(models.Model): name = models.CharField(max_length=70) entry_date = models.DateTimeField(auto_now_add=True) last_name = models.CharField(max_length=40) first_name = models.CharField(max_length=40) sir_status = models.ForeignKey(Status, on_delete=models.CASCADE, default=1, related_name='targets') def __str__(self): return '%d - %s %s' % (self.id, self.first_name, self.last_name) My serializer looks like this: class SirTargetStatusSerializer(serializers.ModelSerializer): status_text = serializers.ReadOnlyField(source='Status.status_text') class Meta: model = SirTarget fields = '__all__' The field status_text is not coming back as part of the API call. When I return the data, I receive the PK of the Status table (1,2,3, etc.) but I do not receive the status_text field. I have been messing around with this for a while and struggling. I have referenced similar set ups such as in this post: Retrieving a Foreign Key value with django-rest-framework serializers However, nothing seems to be working for me. DRF 3.9.0 Python 3.7.1 Thank you for your … -
check if user has a new release note and notify him
I want to find a simple way to notify users about a new release note without using django-notifications or adding a relation between user and release notes table in the database, using something like a flag that returns true once a new release note is added but i don't know if its possible to use session to check if user has already seen the release note or not. -
Create django project without generating comments
I want to create a django project without all the auto generated comments in different files (such as reference links on settings.py and descriptions in urls.py) I try to remove all those stuff after the project creation with some tools like pyminifier and that works fine, but I find myself doing these tedious comment removing stuff every time I start a new project. Is there any way that I can get prevent django from generating these data? Something similar to this: django-admin startproject <name> --no-comment -
Django FormSet show two formset
I try to do a table, and when I click in a Store show me the data, and let me edit. But when I try to do this show me two form sets, one with the corect data and other empty. I have try to follow https://docs.djangoproject.com/en/2.2/topics/forms/modelforms/ tutorial but I dont understand very well. HTML: {% extends 'layout.html'%} [{# Load the tag library #} {% load bootstrap4 %} {# Load CSS and JavaScript #} {% bootstrap_css %} {% bootstrap_javascript jquery='full' %} {# Display django.contrib.messages as Bootstrap alerts #} {% bootstrap_messages %} {% block content%} <form action="/favorita/store/0/" method="POST" class="form"> {% csrf_token %} {% bootstrap_formset formset %} {% buttons %} <button type="submit" class="btn btn-primary"> Submit </button> {% endbuttons %} </form> {%endblock%}][1] View: def store(request, id): StoreFormSet = modelformset_factory(Store, exclude=()) if request.method == 'POST': formset = StoreFormSet(request.POST, request.FILES) if formset.is_valid(): formset.save() return render(request, 'stores/index.html', {'title': 'Favorita Stores'}) else: if id == 0: formset = formset_factory(StoreForm) else: stores_search = Store.objects.filter(id = id) formset = StoreFormSet(queryset=stores_search) return render(request, 'store/details.html', {'formset': formset}) Model: class Store(models.Model): city = models.ForeignKey(City, on_delete=models.CASCADE) store_type = models.ForeignKey(StoreType, on_delete=models.CASCADE) cluster = models.IntegerField(default=0) location = models.CharField(max_length=200) ModelForm: class StoreForm(ModelForm): class Meta: model = Store fields = ['city', 'store_type', 'cluster', 'location'] I only need …