Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
While using python manage.py migrate command in powershell , I got the following error message
enter image description here Can you please help me fix this? -
gcloud app deploy - TypeError: __init__() missing 1 required positional argument: 'on_delete'
This is the first time for me to deploy my app in google cloud. When I enter 'gcloud app deploy' command, it failed due to TypeError: __init__() missing 1 required positional argument: 'on_delete'. But it doesn't seem like a problem of my coding but django itself. Please give me any comment which helps me to understand this error message. > Updating service [default] (this may take several minutes)...failed. > ERROR: (gcloud.app.deploy) Error Response: [9] Application startup > error: [2018-08-06 23:53:20 +0000] [1] [INFO] Starting gunicorn 19.9.0 > [2018-08-06 23:53:20 +0000] [1] [INFO] Listening at: > http://0.0.0.0:8080 (1) [2018-08-06 23:53:20 +0000] [1] [INFO] Using > worker: sync [2018-08-06 23:53:20 +0000] [7] [INFO] Booting worker > with pid: 7 [2018-08-06 23:53:20 +0000] [7] [ERROR] Exception in > worker process Traceback (most recent call last): File > "/env/lib/python3.6/site-packages/gunicorn/arbiter.py", line 583, in > spawn_worker > worker.init_process() File "/env/lib/python3.6/site-packages/gunicorn/workers/base.py", line 129, > in init_process > self.load_wsgi() File "/env/lib/python3.6/site-packages/gunicorn/workers/base.py", line 138, > in load_wsgi > self.wsgi = self.app.wsgi() File "/env/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in > wsgi > self.callable = self.load() File "/env/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 52, > in load > return self.load_wsgiapp() File "/env/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 41, > in load_wsgiapp > return util.import_app(self.app_uri) File "/env/lib/python3.6/site-packages/gunicorn/util.py", line 350, in > import_app … -
PUT on ModelViewSet with nested object Django Rest Framework
I'm building an API with the django rest framework. I have these models: class Organism(models.Model): name = models.CharField(max_length=255) address = models.ForeignKey(Address, on_delete=models.CASCADE) type = models.ForeignKey(Type, on_delete=models.CASCADE) class Address(models.Model): street = models.CharField(max_length=255, blank=True) class Type(models.Model): name = models.CharField(max_length=255, blank=True) This is the view for my mode Organism : class OrganismViewSet(viewsets.ModelViewSet): queryset = Organism.objects.all() serializer_class = OrganismSerializer pagination_class = StandardResultsSetPagination filter_backends = (filters.SearchFilter, DjangoFilterBackend) filter_class = OrganismFilter search_fields = ('name') And my serializer: class OrganismSerializer(serializers.ModelSerializer): addresse = AddressSerializer() type = TypeSerializer() class Meta: model = Organism fields = '__all__' def update(self, instance, validated_data): // What I should write to do something "elegant" Let's imagine when I get my Organism, I have: { "address": { "id": 1 "street": "test" }, type: { "id": 1, "name": "type Organism" }, "name":"TestTest", } So I'm trying to update an Organism (I want to change the name of the street but not create a new object AND change the Type which exists in my database) by sending this: { "address": { "id": 1 "street": "new name" }, type: { "id": 2, "name": "new type" } "name":"TestTest", } And the fact is I don't have the ID of my object in the parameter "validated_data" of the method update. … -
Python List values selection
Hi I have this list which is working for what initially intended for gp_list_t = [int(i) for i in gp_list] gp_lits3 = gp_list_t[0] agencys_sp = GPSpecial.objects.filter(agencys=user_agency,is_active=True,id = gp_lits3).values_list('agencys') Now Let say they are more than i values on the list how do i make sure that it not only use the first value on the list . -
django : three forms but only one input allowed
How would you handle having three forms in one page but only allowing the user to use one for input and therefore making the others inactive/disabled, in the most user friendly way. Say for example having the user choose of one of the following forms: URL file text -
Most efficient way to add "show results within X miles of zip code" filter to website
I am trying to add a "show results within X miles of zip code" filter to my django site. I am using a file with all US zip codes in the format "ZIP,LATITUDE,LONGITUDE\n" (https://gist.github.com/erichurst/7882666), I plan on having a function get the user entered zip code, get the lat and long of that zip code from this file and then run some calculations to find all zip codes within a certain distance. My question is about the most efficient way to do this. Is saving this long file as a .txt, storing it on a server and having my website access this file and run these commands on the fly when a user uses the filter the best way of doing this? Will this cause a long load time? -
Django how to get model field and send an email?
I am newbie and just see the django documentation of sending mail . i want to send an email to the drivers after seeing their details if they are eligible i want them to send an email using thier email address that they submit while registering to my app . please tell me how do i send a email. i had already set the settings.py email host user all the needs of send an email its working on my other app . but not working on this app . how do i get the driver email and send an email from our company employee. Views def rentacar_carapp_sendmail(request): if request.POST: try: args['driver'] = driver = Driver.objects.get(id=request.POST.get('driver_id')) subject = "Please Register Your Car" from_email = settings.EMAIL_HOST_USER to_email = carapp.get('car_app_driver_id.driver_email') join_message = """thankyou we will contact you later """ send_mail(subject=subject, from_email=from_email, recipient_list=[to_email], message=join_message, fail_silently=False) driver.save() except: pass return HttpResponseRedirect('/mega-admin/rentacar/driver-manager/') Models class Driver(models.Model): class Meta(): db_table = "driver" verbose_name = "Driver" verbose_name_plural = "Drivers" ordering = ['driver_firstname', 'driver_lastname'] driver_firstname = models.CharField( max_length=64, blank=False, null=False ) driver_lastname = models.CharField( max_length=64, blank=False, null=False ) driver_email = models.EmailField( blank=False ) -
UpdateView will correctly show model data but wont actually save the update
I am trying to get my UpdateView to load the current data into the form -> allow the user to make changes-> update the object and persist the changes to the database. So far I have this code: class SurveyInitUpdate(UpdateView): model = SurveyInit template_name = 'Model/surveyInit.html' form_class = SurveyInitForm success_url = reverse_lazy('Model:myModel-home') def get(self, request, **kwargs): self.object = SurveyInit.objects.get(user=self.request.user) form_class = self.get_form_class() form = self.get_form(form_class) context = self.get_context_data(object=self.object, form=form) return self.render_to_response(context) def get_object(self, queryset=None): return self.request.user So far it will correctly load the user's data and allow them to enter changes in the form but when the user submits it will not change the object or the database information! Thank you for any help! -
Django ModelChoiceField dynamic queryset from instance
I have a dataset where users may need to edit old records but also choices need to be limited to a set of "active" values. This means the legacy choices need to be added to the queryset of the ModelChoiceField when an instance containing a non-active value is selected. In my mind the ideal way to do this would be to subclass ModelChoiceField however I cannot seem to find the insertion point of instance data into ModelChoiceField. I am able to make it work by setting the queryset in forms.py but I have a large number of fields this is needed for and was really hoping for a more pythonic/DRY solution. For example: models.py class ActiveChoiceModel(models.Model): name = models.CharField(max_length=10) active = models.NullBooleanField(default=False) class MyModel(models.Model): fk_activechoicemodel = models.ForeignKey(to='mydb.ActiveChoiceModel') The queryset for the ModelChoiceField should be: ActiveChoiceModel.objects.filter(active=True) | ActiveChoiceModel.objects.filter(pk=instance.fk_activechoicemodel.id) This can be achieved in forms.py as: Class MyForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) if self.instance.fk_activechoicemodel: self.fields['fk_activechoicemodel'].queryset = ActiveChoiceModel.objects.filter(active=True) | ActiveChoiceModel.objects.filter(pk=instance.fk_activechoicemodel.id) Any thoughts on how to do this clean and DRY for 10's or 100's of 'ActiveChoiceModels'? -
pip install mysqlclient error django
I am currently trying to use MySQL 8.0 as the backend database for my Django project rather than the SQLite that it defaults to. For a little background, I am using Python 3.6 and I have installed pip as needed to be able to install this plugin. I have installed other plugins using pip with no issue but whenever I run pip install mysqlclient I end up getting the following message and it aborts the installation: Command "c:\users\anirudh\appdata\local\programs\python\python36-32\python.exe -u -c "import setuptools, tokenize;file='C:\Users\Anirudh\AppData\Local\Temp\pip-install-xer9o7aw\mysqlclient\setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record C:\Users\Anirudh\AppData\Local\Temp\pip-record-t3br6ckm\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\Anirudh\AppData\Local\Temp\pip-install-xer9o7aw\mysqlclient\ I have visual studio 2017 installed and I used the following link to try to fix it, but that did not work: https://dimitri.janczak.net/2017/05/20/python-3-6-visual-studio-2017/ Any help would be gladly appreciated. Thanks -
Getting an "Received incompatible instance "<TreeQuerySet [<...." from Graphene, and using MPTT
I have a model defined as: class PartyType(MPTTModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) description = models.CharField(blank=False, null=False, unique=True, max_length=255) parent = TreeForeignKey('self', on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.description And in my schema.py file: class PartyTypeType(DjangoObjectType): class Meta: model = PartyType interfaces = (relay.Node,) @classmethod def get_node(cls, id): node = PartyType.objects.get(pk=id) return node When I use the admin, the list of PartyTypes works as expected, however When I use this graphql: { partyTypes { id description } } I get this error: Exception: Received incompatible instance ", , ]>". How do I get graphene and mptt to play nice? -
compare password between form and database is invalid always
Im trying to create a login system with Python/Django/MongoDB. This is my code from django.shortcuts import render from pymongo import MongoClient import bcrypt def login( req ): response = { 'error': 'Error' } if req.POST['username'] and req.POST['password']: u = req.POST['username'] p = req.POST['password'].encode('utf8') client = MongoClient() result = client['db']['users'].find_one({'name': u}) if result: hashed = bcrypt.hashpw( result['password'].encode('utf8'), bcrypt.gensalt() ) if bcrypt.checkpw( p, hashed ): response = { 'error': 'Welcome!' } else: response = { 'error': 'Invalid password' } else: response = { 'error': 'Invalid username' } else: response = { 'error': 'Password/Username empty' } return render( req, 'crawler/login.html', response ) How must I use bcrypt.checkpw() I Stored the password like this $2b$12$tapbosJdMHGCnO6zb.n7Wu3acXyBh4Cj2jdJGv.1TmMBWYtd.nnWW and the test real password is 'password' How must I store the passwords? How must I compare the passwords? (From DB against Form incoming values) Thank you for your guidance -
Django - Change login redirect based on current App
So, I'm adding on another app to a webapp that I'm building for my company, this one involving bill creation for invoices. Unless one has a specific account with my website, they should not be allowed to access this specific app. I am using Django's built-in authentication system. My LOGIN_REDIRECT_URI is set to redirect to one of my apps. However, I would like for the login redirect to send the user to the app that they were previously in after login. How might I accomplish this? Thank you in advance! -
Django error on admin site entry when deployed on Heroku
I have had success in the past hosting a website using the django-heroku package outlined here, but now when I try to run just a basic shell of a Django project as the start of a new project I am hit with the following error message: ProgrammingError at /admin/login/ relation "auth_user" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user... ^ Request Method: POST Request URL: https://hockamer2018.herokuapp.com/admin/login/?next=/admin/ Django Version: 2.1 Exception Type: ProgrammingError Exception Value: relation "auth_user" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user... ^ Exception Location: /app/.heroku/python/lib/python3.6/site- packages/django/db/backends/utils.py in _execute, line 85 Python Executable: /app/.heroku/python/bin/python Python Version: 3.6.6 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python36.zip', '/app/.heroku/python/lib/python3.6', '/app/.heroku/python/lib/python3.6/lib-dynload', '/app/.heroku/python/lib/python3.6/site-packages'] It runs fine when I run this locally so I must have forgotten to set up something on the database on Heroku. I have thoroughly researched this question and all of the fixes seem to be to run python manage.py makemigrations python manage.py migrate but I have done that through the heroku remote ssh and "heroku run" command both to no avail. I am running a completely fresh Django installation where all I have done is added the two django-heroku lines to settings.py. I have tried this on both django-2.0.8 and … -
Python Django Shell AttributeError: 'Article' object has no attribute 'title'
I am new in django please help to find out this problem. I am trying to get hello world from DB but it's not working. Have a look in my windows power shell as administration windows. I have a app articles in my django project and there I have changed the models models file and made a basic class Article with title, date and body field . Also has a function str ============== Windows PowerShell Copyright (C) Microsoft Corporation. All rights reserved. PS C:\WINDOWS\system32> cd C:\Users\Shayon\Desktop\djangonautic PS C:\Users\Shayon\Desktop\djangonautic> python manage.py shell Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from articles.models import Article >>> Article <class 'articles.models.Article'> >>> Article.ojects.all() Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: type object 'Article' has no attribute 'ojects' >>> Article.objects.all() <QuerySet [<Article: Article object (1)>, <Article: Article object (2)>]> >>> article = Article() >>> strivlr Traceback (most recent call last): File "<console>", line 1, in <module> NameError: name 'strivlr' is not defined >>> article <Article: Article object (None)> >>> artile.title = "hello world" Traceback (most recent call last): File "<console>", line 1, in … -
Calling a method defined in a .py from a JS script
first time posting here, sorry if the formatting won't be so good. I'm trying to develop a small project and for this I need to receive MQTT messages and display them in a web page. What I'm currently doing right now is: I created an mqtt.py that gets called by init.py, here I define my MQTT broker and I also define a function that I called "msq_request", this function basically checks a queue of messages and return the oldest one as a JSON. What i want to do is to call "msg_request" every 10 seconds, to do this I'm using a Javascript script that i call periodically in my page. My problem is, how do i call the python function defined inside my mqtt.py from JS? I tried linking the url direclty to the function, but my Django server tells me that it need to be a view and not a function. This is my method: def msg_request(self): global queue if not queue.empty(): return json.loads(queue.get()) else: return json.loads('null') This is my url: path('panel/_new_msg', mqtt.msg_request, name='_new_msg'), #this calls the view, how do i call the function instead? And this is the script: setInterval(function(){ $.getJSON('http://127.0.0.1:8000/demo/panel/_new_msg', { //the url is correct but won't … -
Can´t reassign declared variables with Python/Django
I´m creating a login system with Python, Django and Mongo. This is my function from django.shortcuts import render from pymongo import MongoClient import bcrypt def login( req ): #hashed = bcrypt.hashpw( p.encode('utf8'), bcrypt.gensalt() ) response = { 'error': 'WTF Error' } if req.POST['username'] and req.POST['password']: u = req.POST['username'] p = req.POST['password'] client = MongoClient() result = client['db']['users'].find({'name': u}) if result: for res in result: if bcrypt.checkpw( p, res['password'] ): response = { 'error': 'welcome!' } else: response = { 'error': 'Invalid password' } break else: response = { 'error': 'Nobody with that name' } else: response = { 'error': 'Empty user or password' } return render( req, 'crawler/login.html', response ) Everytime 'WTF Error' is returned to the template, it´s looks like if statement are ignored What´s wrong with my code? I´m newbie with Python -
Assign foreign key when submitting Django Form
I need to assign a foreign key field to an object without neither showing this field in the template nor listing it as a form field. Lets say I have a sample model: class SampleRecord(models.Model): foreign_key = models.ForeignKey(OtherModel) some_field = models.CharField(...) URL pattern I'm calling has a unique parameter which determines to which OtherModel object I'll be assigning new SampleRecord instance. In this case I want to use a Form to create new SampleRecord and I don't want to determine foreign_key as field of this form: class MyForm(forms.ModelForm): class Meta: model = SampleRecord fields = ['some_field'] I understand that I need to override save method inside my form, but I don't understand how to pass OtherModel object to a form from a view and then assign it to new object after/during form validation. -
With transaction.atomic() and transaction.commit()
I've following block of code success = True with transaction.atomic(): try: ''' Some data base inserts ''' except: success = False if success: transaction.commit() celery_task.delay() return I want to understand couple of things regarding transactions and celery task Will the transaction be committed twice? How can I test, whether the transaction is committed twice or not? Is there better way to make sure celery task will be able to read data that was written in transaction? Note - Django version is 1.8. Also neither it is possible to upgrade to 1.9 or use other packages -
Using Python 3.7 on Pycharm gives me: "Error: Django is not importable in this environment"
This problem just started when I updated to python 3.7 (on macOS). Is there any fix or is it an issue with JetBrains? I want to use Django 2.1 with Python 3.7 Also when I select "Run Server" despite the error, everything seems to work perfectly fine. -
How change JSON response result in POST request | DRF?
I am little bit confused and need some advise how correctly organize view. In my Django REST Framework project I have pretty simple model and serializer. models.py: class Article(models.Model): body = models.TextField() serializers.py: class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article fields = ('id', 'body') Lets say I have next data in database: ID | BODY ------------------------------------------------------------- 1 | Aki doing his homework about japanese robot in library. 2 | All chapters are accompanied by necessary links. 3 | Japanese robot Aki doing a lot of tasks. Right now I try to send JSON by POST request to ArticleFilterView controller: curl -X POST -H "Content-Type: application/json" -d '[ { "first": ["Aki", "robot"], "second": ["doing", "library"] }]' http://localhost:8000/api/article/filter/ If any article has words "Aki" and "robot" in body field, I want to add that article to JSON response. In the same time I need to remove "doing" and "library" words from the text. Input: [{ "fisrt": ["Aki", "robot"], "second": ["doing", "library"] }] Output: [ {"id": 1, "body": "Aki his homework about japanese robot in ."}, {"id": 3, "body": "Japanese robot Aki a lot of tasks."}, ] views.py: class ArticleFilterView(APIView): parser_classes = (JSONParser,) def post(self, request, format=None): # some code return Response({'received data': … -
Django unable to display reg_form.html
i've got 2 apps within my project. the main app (blog app) and a accounts app (user model app). now i want that the user gets refferd from the blog app to the registration form within my accounts app but i simply see no content of that registration form. accounts/reg_form.html: {% extends 'quickblog/base.html' %} {% block body %} <div class="container"> <h1>Register</h1> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> </div> {% endblock %} accounts/views.py from django.shortcuts import render, redirect from django.urls import reverse from accounts.forms import ( RegistrationForm, EditProfileForm ) from django.contrib.auth.models import User from django.contrib.auth.forms import PasswordChangeForm from django.contrib.auth import update_session_auth_hash def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() return redirect(reverse('accounts:home')) else: form = RegistrationForm() args = {'form': form} return render(request, 'reg_form.html', args) def view_profile(request, pk=None): if pk: user = User.objects.get(pk=pk) else: user = request.user args = {'user': user} return render(request, 'profile.html', args) def edit_profile(request): if request.method == 'POST': form = EditProfileForm(request.POST, instance=request.user) if form.is_valid(): form.save() return redirect(reverse('accounts:view_profile')) else: form = EditProfileForm(instance=request.user) args = {'form': form} return render(request, 'edit_profile.html', args) def change_password(request): if request.method == 'POST': form = PasswordChangeForm(data=request.POST, user=request.user) if form.is_valid(): form.save() update_session_auth_hash(request, form.user) return redirect(reverse('accounts:view_profile')) else: return redirect(reverse('accounts:change_password')) else: form … -
Django - C stack error in Django
Error: C stack usage 2011331632 is too close to the limit This is what i am getting while running django project, I have no clue what to do here, the numbers are increasing on every attempt. Any quick fix to this? This started happening after adding rpy2 code in app. I have been looking to other solutions but cant exactly decide what could be the problem in mine -
Reverse for 'fobi.dashboard' not found. 'fobi.dashboard' is not a valid view function or pattern name
Everything was working fine when i have added fobi in my project but somehow while i have added namespace in my url it start giving me the error like below. python url(_(r'^$'), view=dashboard, name='fobi.dashboard'), Template {% url 'fobi.dashboard' as fobi_dashboard_url %} Reverse for 'fobi.dashboard' not found. 'fobi.dashboard' is not a valid view function or pattern name. I have visited many site but did not received any quick fix. Could you please help me out to fix this issue? -
Kubernetes not returning endpoints Django Rest-Framework
Hey guys i have a django rest application and every time that i expose the deployment with service, my minikube doesn't expose the IP, anyone knows how to solved it? I wait 3 hours and my minikube doesn't show any IP. Pod/container log: &lt;django.db.models.fields.related.ForeignKey&gt; &lt;django.db.models.fields.TextField&gt; &lt;django.db.models.fields.related.ForeignKey&gt; Operations to perform: Apply all migrations: admin, auth, authtoken, chat, contenttypes, notifications, sessions Running migrations: No migrations to apply. &lt;django.db.models.fields.related.ForeignKey&gt; &lt;django.db.models.fields.TextField&gt; &lt;django.db.models.fields.related.ForeignKey&gt; &lt;django.db.models.fields.related.ForeignKey&gt; &lt;django.db.models.fields.TextField&gt; &lt;django.db.models.fields.related.ForeignKey&gt; Performing system checks... System check identified no issues (0 silenced). August 06, 2018 - 19:14:37 Django version 2.0.1, using settings 'chatire.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C backend-service: apiVersion: v1 kind: Service metadata: name: backend-service spec: type: NodePort ports: - port: 8000 nodePort: 30001 selector: service: backend-pod backend-deployment: apiVersion: extensions/v1beta1 kind: Deployment metadata: name: backend-deployment spec: template: metadata: labels: name: backend-pod spec: containers: - name: container-backend image: modalgr.azurecr.io/chatbot/backend:v1.1 ports: - containerPort: 8000 command: ["/bin/sh"] args: ["app.sh"] restartPolicy: Always imagePullSecrets: - name: azure-auth Error log: C:\Users\Youssef\Documents\kubernetes>minikube service backend-service | findstr IP Waiting, endpoint for service is not ready yet... Waiting, endpoint for service is not ready yet... Waiting, endpoint for service is not ready yet... Waiting, endpoint for service is not ready yet...