Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Argument \"input\" has invalid value id when updating the company
I am learning graphql so i am using graphene-django. I am developing and api for CRUD apps. However, I am getting an error while updating the company. I get following error 'Argument \"input\" has invalid value'. Here is what I have done class CompanyInput(graphene.InputObjectType): name = graphene.String(description='Name of your company') email = graphene.String(description='Email of your company') phone_number = graphene.String(description='Phone number of your company') director = graphene.String(description='Director of your company') franchise_head = graphene.String(description='Franchise Head of your company') class UpdateCompany(graphene.Mutation): class Arguments: input = CompanyInput(description="These fields are required", required=True) id = graphene.String(required=True) class Meta: description = "Update an existing company" # model = models.Company errors = graphene.String() company = graphene.Field(CompanyNode) @staticmethod def mutate(root, info, input=None): print('######################') print('root', root) print('######################') print('info', info, info.context, info.context.user, info.context.user.is_authenticated) if not info.context.user.is_authenticated: return UpdateCompany(errors=json.dumps('Please Login to continue')) try: company_instance = models.Company.objects.get(id=id) if company_instance: company = models.Company(owner=info.context.user, name=input.name, email=input.email, phone_number=input.phone_number, director=input.director, franchise_head=input.franchise_head ) return UpdateCompany(company=company, instance=company_instance) except models.Company.DoesNotExist: return UpdateCompany(errors=json.dumps('No Company Exist to Update')) class Mutation(graphene.ObjectType): create_company = CreateCompany.Field() update_company = UpdateCompany.Field() The query for updating the company is mutation { updateCompany(input: {id: "Q29tcGFueU5vZGU6MQ==", name: "Demo Company", email: "abc@gmail.com", phoneNumber: "984217846", director: "Mr Director", franchiseHead: "Mr Franchise"}) { errors company { id name } } } I tried … -
Django Unit test for models
Below is a class in models.py. class Unit(models.Model): name = models.CharField(max_length=200) start = models.DateTimeField() end = models.DateTimeField() description = models.TextField() deleted = models.BooleanField(default=False) def clean(self): if self.end and self.start and self.end <= self.start: raise ValidationError({ 'end': _('End date should be after start date') }) def __str__(self): return self.name def get_absolute_url(self): return reverse('decentmark:unit_view', kwargs={'unit_id': self.pk}) I have written tests for validating date, length of the string etc. Following are tests for the above class. from django.test import TestCase from decentmark.models import * class UnitModelTest(TestCase): @classmethod def setUpTestData(cls): Unit.objects.create(name='Python', start='2018-10-25 14:30:59', end='2017-10-25 14:30:59', description='111', deleted='False') def test_name_label(self): unit = Unit.objects.get(id=1) # type: Unit field_label = unit._meta.get_field('name').verbose_name self.assertEquals(field_label, 'name') def test_name_max_length(self): unit = Unit.objects.get(id=1) max_length = unit._meta.get_field('name').max_length self.assertEquals(max_length, 200) def test_str(self): unit = Unit.objects.get(id=1) expected_object_name = unit.name self.assertEquals(expected_object_name, str(unit)) def test_date(self): unit = Unit.objects.get(id=1) with self.assertRaises(ValidationError): unit.full_clean() Are there any other tests that I need to write for above class in models.py. Please suggest. Thanks in advance. -
Broken images in bootstrap carousel- Django production(nginx, gunicorn)
I'm setting up a website for production and everything seems alright except that I'm getting broken images in bootstrap carousel(the only place where I have images). I've ran collectstatic and a new folder is created in the project directory where manage.py exists. I've other js, css all working well. Below are my changes in settings.py and nginx sites-available files. STATIC_URL = '/static/' STATIC_ROOT = '/home/xyz/myprojectenv/myproject/static/' location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/xyz/myprojectenv/myproject/static/; } Kindly suggest! broken-image example -
django compare time fields
I am trying to compare two date fields for the time. Here is what I am doing. My output when I print. I can see it is the same, but comparison result is false! Any pointers to what I am doing wrong? Thanks. for appt in appointment_detail: print(appt['start_time']) print(slot_time) print(slot_time == appt['start_time']) 2018-09-22 11:00:00+00:00 2018-09-22 11:00:00 False -
How do I automatically link foreign key id in html
I created my models in django below: Models class TermPolicyPeriod(models.Model): term = models.IntegerField() start_term = models.DateField(auto_now_add=False, blank=True, null=True) end_term = models.DateField(auto_now_add=False, blank=True, null=True) term_end = models.BooleanField(default=False) class TermPolicyDetails(models.Model): branch = models.CharField(max_length=150) branch_code = models.CharField(max_length=3) class_type = models.CharField(max_length=255) week_type = models.CharField(max_length=10) students_per_coach = models.IntegerField() start_class_time = models.TimeField(auto_now_add=False, blank=True) end_class_time = models.TimeField(auto_now_add=False, blank=True) duration_class_time = models.TimeField(auto_now_add=False, blank=True) notes = models.TextField(max_length=350, null=True) foreign_key_term_end = models.ForeignKey(TermPolicyPeriod, on_delete=models.CASCADE) views ... args = { # Term Policies - Period 'new_term_policy_period_form': new_term_policy_period_form, 'term_period_policy_page_data': term_period_policy_page_data, 'edited_tpp': edited_tpp, # Term Policies - Details 'new_term_policy_details_form': new_term_policy_details_form, 'term_policy_details_page_data': term_policy_details_page_data, 'edited_tpd': edited_tpd, } return render(request, 'static/html/home.html', args) Within the forms that I want to create in html, I would like for the foreign key to be linked automatically to the TermPolicyPeriod pk. I've been searching around, but i'm unsure how the syntax should be written. I've thought of something along the lines of <form> {% csrf_token %} {% for pp in new_term_policy_period_form %} {% for pd in new_term_policy_details_form %} {% set pd.foreign_key_term_end_id = pp.pk %} {% endfor %} {% endfor %} ... <button type="submit">submit</button> </form> Is something like this possible in html? -
Updating a field to the primary keys value after a model is created in Django 2.1
I have a django model named Project that has recursive foreign keys to itself. class Project(models.Model): project_root_parent = models.ForeignKey('self',on_delete=models.CASCADE, related_name='root_parent',null=True) project_parent = models.ForeignKey('self', on_delete=models.CASCADE, related_name = 'parent',null=True) This is the desired functionality I want: If the project does not have a parent project the field is set to the created objects primary key. If the project doesnt have a root parent project the field is set to the created objects primary key. Ideally i want the default value of the field to be set to the primary key. If this is not possible then I need to be able to update the value after the primary key is generated and the model is instantiated in django. I have looked at overriding the save method or using the post_save signal but I am unsure that either of these methods are correct. -
Django views not render data after user submit form
It sound simple but I want my page to display the database of my model. I use ModelForm for user to input and it would save into my model. Now I want to render the whole table, not just each separately. forms.py class My_Folio(forms.ModelForm): class Meta: model = my_data fields = ['symbol','buy_price','quantity'] views.py def blockfolio(request): if request.method == 'POST': my_folio = My_Folio(request.POST) if my_folio.is_valid(): symbol = my_folio.cleaned_data['symbol'] buy_price = my_folio.cleaned_data['buy_price'] quantity = my_folio.cleaned_data['quantity'] instance = my_folio.save(commit=False) instance.save() return render(request, 'blockfolio/blockfolio.html', {'symbol':symbol, 'buy_price':buy_price, 'quantity':quantity, 'instance':instance}) template: {{instance}} This give me the user input after submit, but I want to show all of the inputs saved in database. -
Migration to PostgreSQL in Django - error value too long for type character varying(2)
I got following error on the way to migration sqLite to PostgreSQL for Django. psycopg2.DataError: value too long for type character varying(2) I referred to other articles (1, 2). And investigate models.py file to find whether I am setting max_length=2. However, I could not any of them. Can anyone come up what could be the reason to get this error? -
How to use Django's template tag with Vuetify's input value?
I would like to use Django's template tag with Vuetify's input value. In Vuetify 's official document, it is written in the setting method of value as follows. https://vuetifyjs.com/ja/components/text-fields#example-disabled-and-readonly <template> <v-form> <v-container> <v-layout row wrap> <v-flex xs12 sm6> <v-text-field value="John Doe" label="Regular" disabled ></v-text-field> </v-flex> </v-layout> </v-container> </v-form> </template> And I tried using django as follows <v-form method="post" novalidate> {% csrf_token %} <template> <v-form> <v-container> <v-layout row wrap> <v-flex xs12 sm6> {% for field in form %} <v-text-field value="{{ form }}" disabled ></v-text-field> {% endfor %} </v-flex> </v-layout> </v-container> </v-form> </template> </v-form> And the result is like this image What is wrong? -
What is the proper Django Project/App Structure
New to Django, new to Python. Moving from Symfony/PHP and MVC/C# just because it's something different. So I'm starting an App, this app will not be used as a piece of any other app. Following along in the tutorial it almost seems like Django wants me to put each url as it's on App. For example: /directors /ledgers The reason I say it seems like Django wants me to use an App per url family is because in the tutorial the views/models/templates are in the App, and use use index.html/details.html, etc, like so polls --> templates --> index.html details.html Whereas in Symfony for example, in the templates I'd be able to branch to other folders like so. views --> directors --> index.html details.html ledgers --> index.html details.html For Django how would I handle the same scenerio? Just name each template different? For example: polls --> templates --> directors_index.html directors_details.html ledgers_index.html ledgers_details.html Or would I move each to their own App? Very confused. -
Pass a foreign key to form radio button in Django
I have a form (code below) which takes answers into a response model. Answers are always on a scale of 1-3, but may be referencing a variety of different questions. form.py from Django import forms RESPONSE_CHOICES = ( ('1', '1. Happy'), ('2', '2. Neutral'), ('3', '3. Sad'), ) class ResponseForm(forms.Form): quid = forms.IntegerField() response = forms.ChoiceField(choices=RESPONSE_CHOICES, widget=forms.RadioSelect()) quid is the foreign key to ID in the question model. in template.html I have: <form action="" method="post"> {% csrf_token %} {{ form }} <input type="submit" /> </form> Is there a way I can set the value of quid in the radio buttons of my form template, rendering something like this: <label>1</label> <input type="radio" value="1" name="{{ question.id }}"> <label>2</label> <input type="radio" value="2" name="{{ question.id }}"> <label>3</label> <input type="radio" value="3" name="{{ question.id }}"> -
Why does time still show with UTC time zone instead of settings.TIME_ZONE?
I have a model that shows a short string in __str__() method of the model def __str__(self): return "Scheduled at %s" % (self.date_time.strftime("%B %d %Y %I:%M %p")) #Output: <Task: Scheduled at September 30 2018 12:30 AM> # it should have been: <Task: Scheduled at September 29 2018 08:30 PM> When I go to the Django admin, I see in the title Task: Scheduled at September 30 2018 12:30 AM and in the input it is filled with the correct TIME_ZONE: 20:30:00 settings.py TIME_ZONE = 'Etc/GMT+4' USE_I18N = False USE_L10N = False USE_TZ = True He keeps showing time with UTC time zone, however I set TIME_ZONE='Etc/GMT+4 in my settings. I want time data to be saved in database as UTC and show them with TIME_ZONE, in my case Etc/GTM+4 -
Tracking users' posts
How is it better to implement the following task: There are users, users can create posts. It is necessary to make it possible to subscribe to users, to see the messages of those you subscribed to (as in the livejournal). How is it better to implement it? What are the best relationships in the model? -
Type error: int() argument must be a string, a bytes-like object or a number, not 'DeferredAttribute'
I have a table with a list of artists and a link to look at the artist's details. I am getting this error when I click on the link: Type error: int() argument must be a string, a bytes-like object or a number, not 'DeferredAttribute' Can someone explain what is meant by a DeferredAttribute? It looks like artistID is being recognized (because it goes to page http://127.0.0.1:8000/artist/1 when I click on the first artist), but not as an int. Here's what I have: models.py: class Artist(models.Model): artistID = models.IntegerField(primary_key=True, null=False, unique=True) artistName = models.CharField(max_length=50) artistNotes = models.TextField(blank=True) artists.html: {% block content %} <table> <tr> <th>Artist ID</th> <th>Artist Name</th> </tr> {% for artist in artists %} <tr> <td> {{artist.artistID}} </td> <td> {{artist.artistName}} </td> <td><a href="{% url 'artist_detail' artistID=artist.artistID %}" title = "Get more information about this artist"> <img src = "static/images/info.png"></a></td> </tr> {% endfor %} </table> {% endblock %} urls.py: urlpatterns = [ path('artist/<int:artistID>', views.artist_detail, name='artist_detail'), ] views.py: def artist_detail(request, artistID): artist = get_object_or_404(Artist, artistID=Artist.artistID) return render(request, 'dtccArt/artist_detail.html', {'artist': artist}) Thanks in advance for your help! -
Where to write a function/method in a django project
I am writing a function that normalizes gmail email address, transforming them from: david.New+1234@gmail.com ==> davidnew@gmail.com Otherwise, someone could sign up multiple times from a gmail account, for example. My current function is in models.py and looks like this: def normalize_email(email): """ Make sure people cannot register variations of the same email address """ email = email.lower() name, domain = email.split('@') name = name.replace('.', '').split('+')[0] email = name + '@' + domain return email This function is only called by the User model, so my question is where should this function/method best "live"? For example: 1) Within the User model as a regular method: class User(models.Model): [fields here...] def normalize_email(self, email): ... 2) Within the User model as a classmethod class User(models.Model): [fields here...] @classmethod def normalize_email(cls, email): ... 3) Within the User model as a static method class User(models.Model): [fields here...] @staticmethod def normalize_email(email): ... 4) Within a User ModelManager: class User(models.Model): [fields here...] objects = UserManager() 5) Outside of everything but in the models.py file as a regular function. def normalize_email(email): ... class User(models.Model): [fields here...] Which of the above make sense to do and which do not? (for example, why would we not want to use choice … -
How to create Django form with variable number of fields
I'm new to Django and trying to construct form. This is a survey app where there are many questions. Models: I have 2 models Questions and Responses. Responses has 2 fields. - a questionid which is a foreign key on the Question Model's ID - a response field which is an integer between 1-5. Desired Form The desired form lists every question in the question model, and then radio-buttons for the numbers 1-3 beneath. There might be 20 questions on a template page, each with 3 radio buttons. This data would be submitted to the response model. There might be more radio buttons in the end, shown 3 for simplicity. Every question will answer on the same 1-3 scale. What's confusing me is that I need to get the questions.id from the questions model, but somehow pass that into a response modelForm or form. The user shouldn't be able to specify the question.id. I'm unsure the best way to create a form to accomplish this. Attempt 1 template.py <form action="/submit" method="post"> {% csrf_token %} {% for question in questions %} <h2>id: {{ question.id }} - {{ question.question_title }}</h2> <fieldset id="{{ question.id }}"> <label>1</label> <input type="radio" value="1" name="{{ question.id }}"> <label>2</label> … -
In django-storages library why safe_join function is not imported in s3boto3.py file from storages.utils.py file
Currently i am using Django(version=1.8.4), django-storages(version=1.6.5) and boto3(version=1.5.35). while running the command heroku run python manage.py collectstatic i am getting this error: from storages.utils import safe_join, setting ImportError: cannot import name 'safe_join' -
Im working with django and my manage.py file is displaying something strange?
I'm new to web development and have no idea what to do, the problem is stated very clearly but the only problem is I do not know how to do what they are telling me? -
Django view HttpResponseRedirect
I have two functions in views.py: First function def upload_blob(request, iterator, interview_id, candidate_id, question_id): try: interview_obj = Interview.objects.get(id=interview_id) except ObjectDoesNotExist: interview_obj = None current_interview = interview_obj if request.method == 'POST': //do some operation iterator = str(int(iterator) + 1) return HttpResponseRedirect(reverse('candidate:show_question', kwargs={'iterator': iterator,'interview_id':current_interview.id,'question_id':question_id})) else: return render(request, 'candidate/record_answer.html') Second function def show_question(request, iterator, interview_id, question_id): try: interview_obj = Interview.objects.get(id=interview_id) except ObjectDoesNotExist: interview_obj = None current_interview = interview_obj current_question_id = InterviewQuestion.objects.filter(interview_id=interview_obj)[int(iterator)].question_id.id current_question = Question.objects.get(id=current_question_id) **//Here if redirected from first function, I should display show_question page with incremented iterator value, but currently it's going in loop** return HttpResponseRedirect(reverse('candidate:show_question', kwargs={'iterator': iterator,'interview_id':current_interview.id,'question_id':question_id})) context = {'iterator':iterator, 'current_interview':current_interview,'current_question':current_question,} return render(request, 'candidate/show_question.html', context) **Flow of operation is like this: show_question function is called with iterator = 0 and it renders show_question.html. User does some operation on this page that calls the function upload_blob through POST request. upload_blob does some operation after checking request.method is POST, increases iterator value by 1 and redirects to show_question method. This time show_question receives iterator =1 and is supposed to show show_question page with iterator=1 (without putting redirects in loop). Again user should do some operation on show_question.html and upload_blob should be called through POST request. I am currently facing the problem of loop … -
django url testing case
I am new to Django, I am following one tutorial for learning, everything went fine after writing the testing cases it's showing some error, I am following as per tutorial don't know why it's not working. Run python manage.py test Output: Creating test database for alias 'default'... System check identified no issues (0 silenced). E. ====================================================================== ERROR: test_home_url_resolves_home_view (boards.tests.HomeTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\sradha\Development\myproject\myproject\boards\tests.py", line 13, in test_home_url_resolves_home_view view = resolve('/') File "C:\Users\sradha\Development\myproject\venv\lib\site-packages\django\urls\base.py", line 24, in resolve return get_resolver(urlconf).resolve(path) File "C:\Users\sradha\Development\myproject\venv\lib\site-packages\django\urls\resolvers.py", line 520, in resolve raise Resolver404({'tried': tried, 'path': new_path}) django.urls.exceptions.Resolver404: {'tried': [[<URLResolver <URLPattern list> (admin:admin) 'admin/'>], [<URLPattern 'homepage/' [name='home']>]], 'path': ''} ---------------------------------------------------------------------- Ran 2 tests in 0.036s FAILED (errors=1) Destroying test database for alias 'default'... tests.py file from django.urls import reverse from django.urls import resolve from django.test import TestCase from .views import home class HomeTests(TestCase): def test_home_view_status_code(self): url = reverse('home') response = self.client.get(url) self.assertEquals(response.status_code, 200) def test_home_url_resolves_home_view(self): view = resolve('/') self.assertEquals(view.func, home) python version 3.6.2 django version 2.1.1 thank you in advance. -
Django: how to work around "Keyword can't be an expression" error
In the code below, capitals_listings_from_latest_Celery_scrape is a QuerySet of Listing model objects: capitals_listings_from_latest_Celery_scrape = capitals_listings_all.filter(date_added.date()=latest_Celery_scrape_date) However, I currently get "Keyword can't be an expression" error on this line, because of date_added.date() part. The reason I am using .date() is that in order to properly evaluate date_added against latest_Celery_scrape_date I need to strip date_added from time data and leave only the year, month and day. How do I fix the error? -
django dateTimeField deltat
I would like know the delta between the creation of a model row and now. For the moment I have: from datetime import date, time, datetime from django.utils import timezone before= self.begin_current_player#models.DateTimeField(auto_now_add=True) before= datetime(before.year, before.month, before.day, before.hour, before.minute,before.second) now_date= datetime.now() delta_seconde = int((before-now_date).seconds) But the result is very strange(sometime >0 , sometime <0,sometime error type error). Do you have a idea ? thx -
How to use Icontains to search in ListField as the source is an array?
I am using django to query data in my MongoDB. I have this document in my DB: { "source": "www.google.com", "hierarchies": [], "mainTags": [ "Sobre a página", "Teste Tag", "Cartão de Crédito" ], "email": "a@a.com", "_id": { "$oid": "5ba7ffee2ef3f4139de74f3d" }, "updated_at": { "$date": 1537725886501 }, "created_at": { "$date": 1537725886501 }, "title": "Relação de seguros entre 2017 e 2016", "tableId": "relacao_de_seguros_entre_2017_e_2016_7836c6e2", "relevance": 1.0, "description": "este dataset tem como função mostrar a Relação de seguros entre 2017 e 2016", "tags": [] } And my entry should be something like: ["Sobre", "Teste"] I'm trying to find all documents where my Maintag contains any of my entry values. This is what I did: for word in keywordsArray: q |= Q(mainTags__icontains = word) objects = Metadata.objects.all().filter(q).order_by('relevance') -
Trying to get Average rating for user in the Post List Django Template
Intro: Supposing I am making a app where users are rated based on the types of posts they write I have a users profile page. If you come on the users profile page you see all the posts they have written and you see their overall rating. My below code is achieving this with no errors Example: Profile Page Samir T's Profile Rating: 8.0 See Samir T's posts below Problem: When users come on the home page. Which doubles as a PostList page. A site visitor will see all posts from different users I want the visitor to see the post author's rating instead they see N/A on 10 Example: Home Page (Post List View) Post 1 Author Samir T Rating: 8.0 /10 #intead they see N/A on 10 Post 2 Author John Doe Rating: 7.5 /10 #intead they see N/A on 10 My working code for Review Models.py (shows users profile page) class Review (models.Model): review_from = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='review_from') review_for = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='review_for') def average_rating(self): counter = 0 total_ratings = 0 for item in Review.objects.filter(review_for=self.review_for): counter += 1 total_ratings += int(item.ratings) user_rating = total_ratings / counter return user_rating Profile views.py def get_context_data(self, **kwargs): context['review_list'] = … -
How do I integrate .toggle with form errors?
I want to show a div containing other fields(only required if true) if boolean field is true, and hide the div if bool is false. Currently this code works to show and hide the div: $('.hidden-div').hide(); $('#id_bool').change(function() { $('.hidden-div').toggle(this.checked); }); The default value for the bool is false, so when the form is first rendered, the div is hidden. However, the js does not recognize that the bool is true or false and toggle based on those values. This becomes a problem when you check the boolean true, and try to submit the form without filling out the other fields. The form then rehides the div and only shows errors for the normally shown fields even though the hidden fields are required. Then, if you check the bool false, the hidden-div reappears. Any tips on how to fix this?