Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Api - Get and Post Request in One Go - Post Request based on the Get Result
I have this below requirement to achive using Django Rest Framework. I need to handle POST request to Model 2 within the Get request of Model 3 I have two models, Kept only few columns models.py class Customers(models.Model): #original customers data are stored here customer_id = models.BigIntegerField(db_column='customer_id', primary_key=True) customer_name = models.CharField(db_column='Customer_name', blank=True, null=True, max_length=50) class Customers_In_Use(models.Model): #where we will track the locking of customers data once they get used customer_id = models.OneToOneField(Customers_Master, to_field='customer_id', on_delete=models.DO_NOTHING, related_name='rel_customer') comments = models.TextField(blank=True,null=True) one database view. Customers_View(models.Model): customer_id = models.BigIntegerField() customer_name = models.CharField() in_use = models.CharField(blank=True) class Meta: managed = False This view is built at backend as below Select C.customer_id, C.customer_name, CASE WHEN U.customer_id_id IS NULL THEN 'No' ELSE 'Yes' END AS In_Use, from Customers C left join Customers_In_Use U on C.customer_id=U.customer_id_id On my Django Rest Api I am exposing data based on Customers_View (GET request) I have a POST request to Customers_In_Use which will receive customer_id and comments in a json format. Example Data on Customers_View: customer_id,Customer_name,in_use 123,John,No 456,Smith,No 789,John,No 987,Tom,Yes #Yes means this customer data is already in use 567,Tom,No now on api if i run this get request 127.0.0.1:8000/api/customers_view/?in_use=No&customer_name=Tom I should get result as below { customer_id:567, customer_name=Tom, in_use:No } Since … -
Unable to run the docker image for the ethereum project
I have been trying to run the project https://github.com/Mattie432/Blockchain-Voting-System The following steps are given to run the image. 1.Ensure docker is running with sudo service docker start. 2.Build the docker image with docker build -t applicationserver . while in the 2_ApplicationServer directory. 3.Run the docker image with docker run -p 80:80 applicationserver and map the internal port 80 to the localhost port 80. But following error is shown while the third step docker run -p 80:80 applicationserver [docker_entrypoint] Running database migrations.. Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.5/site-packages/django/core/management/base.py", line 305, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.5/site-packages/django/core/management/base.py", line 353, in execute self.check() File "/usr/local/lib/python3.5/site-packages/django/core/management/base.py", line 385, in check include_deployment_checks=include_deployment_checks, File "/usr/local/lib/python3.5/site-packages/django/core/management/base.py", line 372, in _run_checks return checks.run_checks(**kwargs) File "/usr/local/lib/python3.5/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/usr/local/lib/python3.5/site-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/usr/local/lib/python3.5/site-packages/django/core/checks/urls.py", line 24, in check_resolver for pattern in resolver.url_patterns: File "/usr/local/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.5/site-packages/django/urls/resolvers.py", line 310, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/local/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.5/site-packages/django/urls/resolvers.py", line … -
Create manytomany to user with value
I am building an application where I need to add to the user model 'skills'. These skills are created and added by the user being this also a model. I want to add to this skills, related with a many to many relationship, a value. This value will be a number from 1 to 10 specifing the level of the user at a particular skill. So that I need to relate a level to each skill added to the user. models.py class Skill(models.Model): name = models.CharField(max_length=50) class Perfil(AbstractUser): skills = models.ManyToManyField(Skill, blank=True, null=True) Does anyone know how can I resolve this issue. Thanks in advance. -
Filter JSON results - Django 1.8
I've tried this: def profile(request): parsedData = [] if request.method == 'POST': username = request.POST.get('user') req = requests.get('https://api.github.com/users/' + username + '/repos') jsonList = [] jsonList=req.json() userData = {} for data in jsonList: userData['html_url'] = data['html_url'] userData['created_at'] = data['created_at'] userData['updated_at'] = data['updated_at'] userData['forks_count'] = data['forks_count'] repo_instance = Repo.objects.create(name=data['id']) repos = Repo.objects.filter(updated_at__lt = timezone.now()).order_by('updated_at') parsedData.append(userData) return render(request, 'app/profile.html', {'data': parsedData}) Here's my model: class Repo(models.Model): name = models.CharField('Name of repo', max_length=255) login = models.CharField('Login', max_length=255) blog = models.CharField('Blog', max_length=255) email = models.CharField('Email', max_length=255) public_gists = models.CharField('Public Gists', max_length=255) updated_at = models.DateTimeField('Updated at', blank=True, null=True) The profile method on views.py, makes a query to an address like this one What am I missing? The results aren't being filtered, or should I use some other parameter instead of lt? Or maybe it's the fact that updated_at is not being called into the method, just id field? -
Form verification with MySQL database using Django
Hi, I'm new to coding and I wanted to build a program using Django and MySQL that would be useful for me. Essentially I wanted to build a site where I can input a 9-digit ID code into a form, then have the site verify if that 9-digit number exists in a database. I wanted to have a database with +100,000 9-digit numbers to check against. If the number exists I wanted to send back a "Number is valid" message and if not a "Number is invalid" message. Could someone direct me to a book/example/tutorial that discusses how to check form data against large MySQL databases. -
Django-Allauth remove email field in signup form
I only use Linked-In as means to authenticate. When the user gives permission in Linked-In, he get's send to my own form so I can gather extra information. But it seems Allauth only lets me add fields to the default form using: ACCOUNT_SIGNUP_FORM_CLASS = 'myapp.forms.MySignUpForm' But the email field is always visible (and filled in with the email from Linked-In). Is it true that I have no way of dropping this field? I don't want the user to be able to change his email into something else than his Linked-In email. -
Django login page via /accounts/login/ instead of /
I have just begun using Django and after a long time struggling I finally made the login work. The only problem is that I have to go to ip_address/accounts/login/ to login. I want to have this as the first thing you see, so on the link: ip_address/ I was wondering if there is such a thing like LOGIN_URL for the homepage or another solution. Thanks -
How can users add to a database in Django
Within the admin app it's possible to add to a database. But is there a way where users who have accounts on the website can add to the database. For example a playlist where a user can add information about songs to -
Order a recipe queryset by replies number using django-disqus
I have a recipe model and i need create a view for most commented recipes, i'm using django-disqus for handling recipe's comments, but i don't know how can i order the queryset by the recipe's comment number. class PopRecipeListView(GlobalQueryMixin, ListView): model = Recipe context_object_name = "recipe_list" template_name = 'recipe/recipe_top_list.html' def get_queryset(self): qs = super(PopRecipeListView, self).get_queryset() if qs: qs = qs.extra( select={ 'comments': # get comment numbers } ).filter(shared=True).order_by('-rate')[:20] return qs What's the properly way? -
Passing list of dicts to form
I have a rather fundamental query regarding django and form handling. Suppose I have a form called "questions.html". I wish to give all the fields names, so I write a view to give names to all the fields. The data from the form is then supposed to be passed to a view for processing, and then response is generated and given to another page, called "answers.html". Do I need 2 views for handling this? Is my flow correct? -
import error: module properly installed, pycharm congfigured for virtualenv, was working
I have set up my pycharm to point to my virtualenv I have properly installed the module in this case its requests I have properly used the module. This is a case of " it just stopped working" here is the code that the module requests is being used in import requests from suitsandtables.settings import googlemapsgeocodeurl, googlemapsgeocodekey class VenueServices: def getvenueaddresscoordinates(self,address): url = googlemapsgeocodeurl + VenueServices.prepareaddress(self,address) + googlemapsgeocodekey r = requests.get(url).json() r = r['results'][0]['geometry']['location'] return r def prepareaddress(self, address): convertedaddress =[] addressstring = '' for add in address: add = add.replace(' ', '+') convertedaddress.append(add) addressstring = convertedaddress[0] + ',+' + convertedaddress[1] + ',+' + convertedaddress[2] return addressstring and the error: File "/home/rickus/Documents/softwareProjects/211hospitality/suitsandtables/backend/virtualsuits/suitsandtables/suitsandtables/urls.py", line 18, in <module> from venues.urls import * File "/home/rickus/Documents/softwareProjects/211hospitality/suitsandtables/backend/virtualsuits/suitsandtables/venues/urls.py", line 2, in <module> from views import UnapprovedVenueApplicationDetail, DeclineDestroyVenueApplication, VenueAddressLatLng, UnapprovedVenueApplicationList, CreateUnapprovedVenue, CreateApprovedVenue,RetreiveEditDeleteApprovedVenue File "/home/rickus/Documents/softwareProjects/211hospitality/suitsandtables/backend/virtualsuits/suitsandtables/venues/views.py", line 8, in <module> from services import VenueServices File "/home/rickus/Documents/softwareProjects/211hospitality/suitsandtables/backend/virtualsuits/suitsandtables/venues/services.py", line 1, in <module> import requests ImportError: No module named requests -
Django - File remove button for InlineFormSet not working
I have 2 models, OwnerListing and OwnerListingPhoto, the latter is a ForeignKey to the former. I'm using InlineFormset to allow the user to edit an existing OwnerListing with all of its respective OwnerListingPhoto's. On the site, the formset is shown like this. Everything else is working fine, except the delete function. When you check the 'Delete' checkbox and submit the form, the form is successfully submited, but the photo is not deleted. What's going on in my code that is causing this? def fsbo_edit_listing(request): listing = OwnerListing.objects.get(id=int(request.GET.get('id'))) PhotoFormSet = inlineformset_factory( OwnerListing, OwnerListingPhoto, fields=('photo',), widgets={ 'photo': ClearableFileInput(attrs={'class': 'btn btn-outline-secondary form-control'}) } ) if request.method == 'POST': form = OwnerListingForm(request.POST, instance=listing) photo_formset = PhotoFormSet(request.POST, request.FILES, instance=listing) if form.is_valid() and photo_formset.is_valid(): form.save() for i in photo_formset: if i.instance.pk and i.instance.photo == '': i.instance.delete() elif i.cleaned_data: temp = i.save(commit=False) temp.listing = form.instance temp.save() return redirect('dashboard') else: if listing.user == request.user: form = OwnerListingForm(instance=listing) photo_formset = PhotoFormSet(instance=listing) else: raise Http404('Not a valid request') return render(request, 'fsbo_create_listing.html', {'form': form, 'photo_formset': photo_formset}) HTML: {{ photo_formset.management_form }} {% for form in photo_formset %} <div class="col-sm-6 col-xl-4 mb-3 p-1" style=""> <div class="col-12 border border-dark rounded p-2"> {{ form }} </div> </div> {% endfor %} -
Expected view to be called with a URL keyword argument named "user_token"
I am using Django Rest Framework and here is my view: class DeleteUserView(generics.DestroyAPIView): permission_classes = (IsAuthenticated,) serializer_class = UserSerializer queryset = User.objects.all() lookup_field = 'user_token' and my urls.py: from django.urls import path from .views import CreateUserView, DeleteUserView urlpatterns = [ path('add_user/', CreateUserView.as_view()), path('delete_user/', DeleteUserView.as_view()), ] serializer.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('user_token',) I am trying to delete user by specific token but it doesn't work... -
Django ON UPDATE setting for Foreign Keys?
Why does Django not have an ON UPDATE setting for foreign keys? The ForeignKey model only has on_update. -
Parent page option keeps appearing
I'm working on a Python/Django/Wagtail project. At some point when creating an Article it could go under the Articles index model or the Partners index model. I deleted all of the Partners traces in the code, and the Article model only has this: parent_page_types = ['btcmag.ArticleIndexPage'] However when creating an Article, I still get the same screen showed above. Am I missing some step? -
Pyinstaller subprocess exception When running on windowed mode
I'm using pyinstaller to create my application.In my django app, I'm using subprocess. When i execute pyinstaller in noconsole mode its throwing errors. Error log: Traceback (most recent call last): File "site-packages\django\core\handlers\base.py", line 149, in get_response File "site-packages\django\core\handlers\base.py", line 147, in get_response File "crumbs_tableau\views.py", line 1603, in parser File "site-packages\django\shortcuts.py", line 67, in render File "site-packages\django\template\loader.py", line 96, in render_to_string File "site-packages\django\template\loader.py", line 43, in get_template django.template.exceptions.TemplateDoesNotExist: helpers/error.html Internal Server Error: / Traceback (most recent call last): File "crumbs_tableau\views.py", line 286, in parser File "crumbs_tableau\views.py", line 248, in mac_list File "subprocess.py", line 336, in check_output File "subprocess.py", line 403, in run File "subprocess.py", line 667, in __init__ File "subprocess.py", line 905, in _get_handles File "subprocess.py", line 955, in _make_inheritable OSError: [WinError 6] The handle is invalid During handling of the above exception, another exception occurred: Traceback (most recent call last): File "site-packages\django\core\handlers\base.py", line 149, in get_response File "site-packages\django\core\handlers\base.py", line 147, in get_response File "crumbs_tableau\views.py", line 1603, in parser File "site-packages\django\shortcuts.py", line 67, in render File "site-packages\django\template\loader.py", line 96, in render_to_string File "site-packages\django\template\loader.py", line 43, in get_template django.template.exceptions.TemplateDoesNotExist: helpers/error.html Not Found: /static/parser/bootstrap.css.map -
Incomplete json structure - no count/next/previous/results field
like many times before, im trying to send data from my Django backend to my Ionic mobile app. This time, however, for some reason, the .jsons im parsing are coming out incomplete. A complete .json: {"count":1,"next":null,"previous":null,"results":[{"codigo":"qwe","area":"ewq","especies":[],"id":1}]} My incomplete .json: [{"nome_ficheiro":"1520529086252.jpg","id":26,"especie":"Ameijoa Branca","zona":"L6","data":"09/06/2018"}] IONIC is struggling with identifying what I'm parsing as a .json, which makes sense since there is no "results" field. Here are the relevant snippets of my django code: Views.py (both Views are doing the same thing! This is just me trying out different approaches!) class resultUploadViewSet(viewsets.ViewSet): def list(self, request, nome_ficheiro): queryset = labelResult.objects.all() nome = nome_ficheiro answer = queryset.filter(nome_ficheiro=nome) serializer = resultSerializer(answer, many=True) return Response(serializer.data) class resultUploadView(APIView): serializer_class = resultSerializer def get(self, request, nome_ficheiro): queryset = labelResult.objects.all() nome = nome_ficheiro answer = queryset.filter(nome_ficheiro=nome) serializer = self.serializer_class(answer, many=True) return Response(serializer.data) Models.py class labelResult(models.Model): nome_ficheiro = models.CharField(max_length=120) especie = models.CharField(max_length=120) zona = models.CharField(max_length=120) data = models.CharField(max_length=120) Urls.py urlpatterns = [ url(r'results/(?P<nome_ficheiro>.+)/$', resultUploadViewSet.as_view({'get': 'list'})), url(r'results1/(?P<nome_ficheiro>.+)/$', resultUploadView.as_view())] Serializers.py class resultSerializer(serializers.ModelSerializer): class Meta: model = labelResult fields = ('nome_ficheiro','id','especie','zona', 'data') Any idea why my .jsons are coming out incomplete? -
Django - How can I open multiple stored files and render them as HTML?
I have a user account that can create a model called experiment. Within this model, it can store files: HTML, JS, and CSS. It stores them in the server. My issue right now is trying to figure out how to approach this problem of rendering the HTML file on a page. Do I try to create a view that has an HTTP response of the file? Is there a better way? -
import requests fail. pycharm, project interpreter set up to us virtual env
I am receiving a error that requests is not installed in python after I have installed it, and used it. I have successfully installed requests inside my virtual environment I have successfully pointed pycharms project interpreter to the virtual environment using this tutorial: http://exponential.io/blog/2015/02/10/configure-pycharm-to-use-virtualenv/ I have successfully used requests. This is literally a case where "it just stopped working" This is a django project. Things I have done recently that shouldn't effect this issue, but just in case Made changes to my models changed urls changed views the code that uses requests looks like this: import requests from suitsandtables.settings import googlemapsgeocodeurl, googlemapsgeocodekey class VenueServices: def getvenueaddresscoordinates(self,address): url = googlemapsgeocodeurl + VenueServices.prepareaddress(self,address) + googlemapsgeocodekey r = requests.get(url).json() r = r['results'][0]['geometry']['location'] return r def prepareaddress(self, address): convertedaddress =[] addressstring = '' for add in address: add = add.replace(' ', '+') convertedaddress.append(add) addressstring = convertedaddress[0] + ',+' + convertedaddress[1] + ',+' + convertedaddress[2] return addressstring the error I am getting: File "/home/rickus/Documents/softwareProjects/211hospitality/suitsandtables/backend/virtualsuits/suitsandtables/suitsandtables/urls.py", line 18, in <module> from venues.urls import * File "/home/rickus/Documents/softwareProjects/211hospitality/suitsandtables/backend/virtualsuits/suitsandtables/venues/urls.py", line 2, in <module> from views import UnapprovedVenueApplicationDetail, DeclineDestroyVenueApplication, VenueAddressLatLng, UnapprovedVenueApplicationList, CreateUnapprovedVenue, CreateApprovedVenue,RetreiveEditDeleteApprovedVenue File "/home/rickus/Documents/softwareProjects/211hospitality/suitsandtables/backend/virtualsuits/suitsandtables/venues/views.py", line 8, in <module> from services import VenueServices File "/home/rickus/Documents/softwareProjects/211hospitality/suitsandtables/backend/virtualsuits/suitsandtables/venues/services.py", line 1, in <module> import requests … -
Generating an API blueprint documentation from Django/DRF code
Is there any lib/parser which can generate API blueprint documentation (apiary) from Django + Django Rest Framework code? Eg: class UserView(...): """ ## Users list [GET /users] + Request (application/json) ... + Response (application/json) ... """ class UserSerializer(...): """ ## User (object) + id (string) + username (string) + ... """ -
Wagtail admin password reset doesn't work
According to the server logs email has been sent: [08/Mar/2018 17:07:50] "GET /admin/password_reset/ HTTP/1.0" 200 4304 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: Password reset From: correct.email@address.com To: narunas@example.com Date: Thu, 08 Mar 2018 17:08:01 -0000 Message-ID: <20180308170801.3122.49315@linux-host> Please follow the link below to reset your password: http://example.com/admin/password_reset/confirm/MQ/4ub-ba21a21a92b51d01e139/ Your username (in case you've forgotten): narunas ------------------------------------------------------------------------------- [08/Mar/2018 17:08:01] "POST /admin/password_reset/ HTTP/1.0" 302 0 [08/Mar/2018 17:08:01] "GET /admin/password_reset/done/ HTTP/1.0" 200 3662 However tcpdump show contradicting results, thus email hasn't been sent: # tcpdump -i any -fn port 587 tcpdump: verbose output suppressed, use -v or -vv for full protocol decode listening on any, link-type LINUX_SLL (Linux cooked), capture size 262144 bytes I'm using the following django settings: WAGTAILADMIN_NOTIFICATION_FROM_EMAIL = 'correct.email@address.com' DEFAULT_FROM_EMAIL = 'correct.email@address.com' EMAIL_HOST = 'email-smtp.us-east-1.amazonaws.com' EMAIL_HOST_USER = '******************' EMAIL_HOST_PASSWORD = '******************' EMAIL_USE_TLS = True EMAIL_PORT = '587' Any idea what's wrong? -
How to save images from RTF editor in Django project?
I have been able to use Alloy Editor (a fork of CKEditor) and save the formatted texts in Django model. I have used AJAX to capture the input and save the data with the following code. $(document).ready(function() { $('#create_form').on('submit', function(e) { e.preventDefault(); $.ajax({ url : '/create/', type : 'POST', data : { title : $('#id_title').val(), body : $('#id_body').html() }, success : function() { $(location).attr('href', '/'); } }) }); }); However, when I select an image in the editor and hit the save button I am shown a 400 bad request error in the console. I am guessing that for the image to be used within the article I am trying to save I have to upload the image in the media folder and put a link to that uploaded image in the place where I have placed the image in the RTF editor. How can I do this? -
EXE application created using pyinstaller running in memmory two times
I used py installer to make EXE application package from my django web-app. I could run my application perfectly, But when i run application inside process this application running more than one time. This will leads to memory leakage that i cant compromise with. Used Pyinstaller 3.3.1 python 3.6 Django 1.9 -
How to submit tags in bootstrap tagsinput with form
I am trying to submit a form with bootstrap tagsinput, But having some issues . At views.py when I try to get the tags that are entered in tagsinput, I get an empty list. Earlier I tried getting tags in jquery using this command $("#tagbar").tagsinput('items') and made a POST request with Ajax to transfer values to the views.py and it worked perfectly. But it doesn't works with form. How can we get the list of tags in views.py. index.html <form method="post" enctype="multipart/form-data" action="/get_data/"> <input type="text" id="tagbar" /> <button type="submit">Submit</button> </form> views.py @csrf_exempt def get_data(request): if request.method == 'POST': tags = request.POST.getlist('tagbar') print(tags) return render(request, "index.html") -
Setting DEFAULT_FILE_STORAGE in settings.py triggers "TypeError: Unicode-objects must be encoded before hashing"
I'm setting up my app to work with AWS. I can upload my static files by running python manage.py collectstatic however when I follow the instructions and set my DEFAULT_FILE_STORAGE for my my media files I get this error: "TypeError: Unicode-objects must be encoded before hashing". If I comment out DEFAULT_FILE_STORAGE = app.aws.utils.MediaRootS3BotoStorage the error message goes away. I've searched relentlessly but I haven't found anything to point me in the right direction. Could this be an issue with the packages I've installed? Packages: boto3==1.6.4 botocore==1.9.4 Django==2.0.2 django-photologue==3.8.1 django-sortedm2m==1.5.0 django-storages==1.6.5 docutils==0.14 ExifRead==2.1.2 jmespath==0.9.3 Pillow==5.0.0 psycopg2==2.7.4 python-dateutil==2.6.1 python-decouple==3.1 pytz==2018.3 s3transfer==0.1.13 six==1.11.0 Here are the logs: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x1103e3ea0> Traceback (most recent call last): File "/dev/app/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/dev/app/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "/dev/app/lib/python3.6/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/dev/app/lib/python3.6/site-packages/django/core/management/__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "/dev/app/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/dev/app/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/dev/app/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/dev/app/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", …