Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django convert list to query set
i have a list [<Upload: 33-bb6f5d9a98604450>, <Upload: 35-bb6f5d9a98604450>, <Upload: 30-bb6f5d9a98604450>, <Upload: 31-bb6f5d9a98604450>, <Upload: 34-bb6f5d9a98604450>] which has been generated by ques = list(sorted(Upload.objects.filter(unique_id=tdetail), key=lambda x: random.random())) <Upload: 33-bb6f5d9a98604450> here Upload is the model and 33-bb6f5d9a98604450 is the slug of model upload how can we extract Upload model values from this list -
Not able to load images from static folder of Django even after proper configuration
HTML Page: <body> {% load static %} <section class="hero is-success is-fullheight"> <div class="hero-body"> <div class="container has-text-centered"> <div class="column is-4 is-offset-4"> <h3 class="title has-text-grey">Login</h3> <div class="box"> <figure class="avatar"> <img src="{% static 'images/abc.png' %}"> </figure> Settings.py configuration # Static files (CSS, JavaScript, Images)STATIC_URL = '/static/' STATIC_URL = '/static/' #STATIC_URL = os.path.join(BASE_DIR, "static/") STATIC_ROOT = '/staticfiles/' #STATIC_ROOT = os.path.join(BASE_DIR, "static/") INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] When i try to load an image using the above configuration. I am unable to get the response. Error is throwing like "GET http://127.0.0.1:8000/static/images/abc.png 404 (Not Found)" Thanks! -
My Django Web gets empty values when I try to use UpdateView to edit data
I am trying to use an Edit button in my website to edit items using UpdateView. The problem is, that when I click edit the forms are staying blank without the previous data data. Under forms I have post.id that I supposed to give him so forms will know which form to get his data... but it doesn't work.. I have no idea why.. serverlist.html- <div class="container"> <br> <center><h1 class="display-4">DevOps Server List</h1></center> <br> <center><button type="button" class="save btn btn-outline-success btn-lg" data-toggle="modal" data-target=".AddServer">Add Server <i class="fa fa-server fa-lg" aria-hidden="true"></i></button></center> <table class="table table-hover table-bordered table-condensed" cellspacing="0" width="1300" id="ServerTable"> <thead> <tr> <th><center> #</center></th> <th><center> Server Name </center></th></center> <th><center> Owner </center></th></center> <th><center> Project </center></th></center> <th><center> Description </center></th></center> <th><center> IP Address </center></th></center> <th><center> ILO </center></th></center> <th><center> Rack </center></th></center> <th><center> Status </center></th></center> <th><center> &nbsp;&nbsp;&nbsp;&nbsp; Actions &nbsp;&nbsp;&nbsp;&nbsp; </center></th></center> </tr> </thead> <tbody> {% for server in posts %} <tr> <div class ="server"> <td></td> <td><center>{{ server.ServerName }}</center></td> <td><center>{{ server.Owner }}</center></td> <td><center>{{ server.Project }}</center></td> <td><center>{{ server.Description }}</center></td> <td><center>{{ server.IP }}</center></td> <td><center>{{ server.ILO }}</center></td> <td><center>{{ server.Rack }}</center></td> <td><h4><span class="badge badge-success">Online</span></h4></td></center> <td> &nbsp;&nbsp;&nbsp;&nbsp; <button type="button" class="btn btn-outline-danger" data-toggle="modal" href="#delete-server-{{server.id}}" data-target="#Del{{server.id}}">Delete <i class="fa fa-trash-o"></i></button>&nbsp; <button type="button" class="btn btn-outline-primary" data-toggle="modal" href="#edit-server-{{server.id}}" data-target="#Edit{{server.id}}"> &nbsp;&nbsp;Edit&nbsp; <i class="fa fa-pencil"></i></button> &nbsp; <div id ="Del{{server.id}}" class="modal fade" role="document"> <div class="modal-dialog" … -
Import external react component from CDN (React Bootstrap Slider)
I have a Django project and I want to use React on it. I have already created my own components and this works, but I dont know how to import third-party components from CDN. To do this, I did: Import React (develop or production version) in the base template: <!-- baseTemplate.html --> {# ReactJs#} <script src="https://unpkg.com/react@16/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script> Also import the file where I create my components <!-- baseTemplate.html --> <script src="/one_directory/my_react.jsx" type="text/babel"></script> and create the tag where it will be rendered. <!-- template.html --> <div id="container"></div> And finally render my React components: <!-- my_react.jsx --> ReactDOM.render( <App />, document.getElementById('container') ); This works correctly :) Now, I want to import a third-party component (specifically, it's React Bootstrap Slider) from CDN, but I dont know how. Maybe this is not possible, I dont know. How could I do it? Thank you very much :] -
the miss "meida" path in django-oscar image URL
I m trying django-oscar to build an e-commerce website. I have deployed django-oscar on Heroku (with Amazon S3 as static and media file bucket), the issue is When I try to add a photo for a product on dashboard, The system returns the correct working URL https://s3.amazonaws.com/mybucket/media/cache/XXX/YYY/ZZZ.jpg that works on first page view request. Reload the page. The system returns broken URL: https://s3.amazonaws.com/mybucket/cache/XXX/YYY/ZZZ.jpg (missing 'media' path) any idea about this miss "media"? -
python - mock, patch, start and return_value
When using mock patcher with start() (and stop() later on) - does it matter when I add the return_value? For example - is there a difference between - cls._dm_delete_attachment_patcher = mock.patch.object(DmService, 'delete_attachment') cls._dm_delete_attachment_patcher.return_value = 'some_deleted_attachment_urn' cls._dm_delete_attachment_start = cls._dm_delete_attachment_patcher.start() and - cls._dm_delete_attachment_patcher = mock.patch.object(DmService, 'delete_attachment') cls._dm_delete_attachment_start = cls._dm_delete_attachment_patcher.start() cls._dm_delete_attachment_start.return_value = 'some_deleted_attachment_urn' or maybe it should be - cls._dm_delete_attachment_patcher = mock.patch.object(DmService, 'delete_attachment') cls._dm_delete_attachment_patcher.return_value = 'some_deleted_attachment_urn' cls._dm_delete_attachment_start = cls._dm_delete_attachment_patcher.start() cls._dm_delete_attachment_start.return_value = 'some_deleted_attachment_urn' In my test, seems like the first option failed, and the third did the work. I'm not sure why. -
Installing Django on MAC error msg "Command "python setup.py egg_info" failed with error code 1 in /private/tmp/pip-build-2yOWor/django/"
I am trying to install Django 2.0 on my Macbook on Sierra 10.12.6, with Python 2.7.14 using virtualenv but I keep getting this error code at the bottom: (sorry in advance, I'm new here so not sure how to make it more user-friendly to read so also attached a screenshot below) Joeys-MBP:somename joeybaloney$ pip install django Collecting django Using cached Django-2.0.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "", line 1, in File "/private/var/folders/wj/jbbqxb5d6ld9q00gw73mjzp00000gn/T/pip-build-QicGdd/django/setup.py", line 32, in version = import('django').get_version() File "django/init.py", line 1, in from django.utils.version import get_version File "django/utils/version.py", line 61, in @functools.lru_cache() AttributeError: 'module' object has no attribute 'lru_cache' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/wj/jbbqxb5d6ld9q00gw73mjzp00000gn/T/pip-build-QicGdd/django/ I've tried almost every solution here on Stackoverflow such as updating tools, using sudo pip install but nothing seems to work. Thanks in advance terminal screen shot -
Why python manage.py collectstatic do not copy files to correct location?
The problem I am facing is that my Django project can't find static files. I was struggling with this issue for quite a while hence, now I figured where the problem is however, I have no idea how to fix it. Real static files location: ls /code/jk/static/jk/css/main.css ls /code/jk/static/jk/js/main.js When running: RUN (python /code/jk/manage.py collectstatic --noinput) I noticed that this provides me a wrong location: ... 61 static files copied to '/code/jk/jk/static', 2 unmodified. ... There is redundant '/code/jk/jk/static' in the path and I have no idea how to change it. settings.py ... STATIC_DIR = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = [STATIC_DIR] PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static') MEDIA_DIR = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' MEDIA_ROOT = MEDIA_DIR ... I am using Django application in docker as following: Dockerfile FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY . /code/ RUN (pip install -r reqirements.txt) RUN (python /code/jk/manage.py migrate) RUN (python /code/jk/manage.py collectstatic --noinput) RUN (python /code/jk/manage.py migrate) # clean packages RUN apt-get clean RUN rm -rf /var/cache/apt/archives/* /var/lib/apt/lists/* ENTRYPOINT ["/code/jk/start_gunicorn.sh"] start_gunicorn.sh #!/bin/bash cd /code/jk/ touch ./gunicorn.log touch ./gunicorn-access.log tail -n 0 -f ./gunicorn*.log & #export DJANGO_SETTINGS_MODULE=projectx.settings exec gunicorn jk.wsgi \ --bind 0.0.0.0:8000 \ --workers 3 … -
Web - Which languages I need to create a website
I am a boy and I are a beginner in programming. I can write code on python, but which more language I need to create a website. Thanks! PS. Sorry for my bad English. I are from Russia. -
including shipping in django e-commerce application
I have a django e-commerce application where people can place order on any product of their choice and as well checkout their cart. I am at the point of checkout where a user selects his shipping address. I have a shipping app to handle the shipping address and I have an order app to handle the order and checkout. After implementing my codes I could not checkout a user who was supposed to be redirected to his paypal account(for now) and after creating shipping address for different users in the admin I also noticed that on the checkout page, it loads every shipping address instead of the customer's address (with the user logged in offcourse). I also noticed that when a user selects 'create new address radio button', it does not bring an address page for the user to create another shipping address. my codes are written below shipping models.py class AbstractAddress(models.Model): MR, MISS, MRS, MS, DR = ('Mr', 'Miss', 'Mrs', 'Ms', 'Dr') TITLE_CHOICES = ( (MR, _("Mr")), (MISS, _("Miss")), (MRS, _("Mrs")), (MS, _("Ms")), (DR, _("Dr")), ) title = models.CharField( pgettext_lazy(u"Treatment Pronouns for the customer", u"Title"), max_length=64, choices=TITLE_CHOICES, blank=True) first_name = models.CharField(_("First name"), max_length=255, blank=True) last_name = models.CharField(_("Last name"), max_length=255, … -
Django runtime migrations
Could someone help me, give me an example or a link I didn't find yet, to create migrations at runtime, or in other words to use migrations to let users to add custom fields ? Thank you in advance -
Custom JS for specific models in admin inline form
So I have followed https://docs.djangoproject.com/en/1.11/ref/contrib/admin/javascript/#inline-form-events to add custom JS to the change_form for my inline forms and it works but now I want to add different JS for a different model. This is not specific to the add and delete as described in above link. In my main app I have two models Invoices and Quotes that contain inline items InvoiceItems and QuoteItems. They both refer to the same change_form and therefore same formset_handlers.js file. The invoiceitem has some JS which takes qty, price etc and figures out the total plus some other js. I now want to add some new js for the quotes inline where the form ids and behaviour will be different. What I am looking for is a way to specify the JS file listed here {{ block.super }} <script type="text/javascript" src="{% static 'app/formset_handlers.js' %}"> </script> {% endblock %} Or a way to check for: $(document).on('formset:added', function(event, $row, formsetName) { if (formsetName == 'maininvoiceitem_set') { ... } else if (formsetName == 'mainquoteitem_set') { ... } without needing to specify added or delete. Unfortunately it does not seem as simple as leaving the :added or :delete off. -
Creating a .gitignore file for a Django website
I'm ready to push my existing Django project (which i've been running in a local environment) to a Bitbucket repository so I can run it on a public server. At the moment I feel like there's a lot of files created in local development that needs to be added to .gitignore. I found this .gitignore file on github however I still feel it's missing some things, for example it doesn't seem to remove files from each migrations folders. There's also a lot of stuff there that I don't know what they do - I understand not all of it is needed. Any advice is appreciated. -
How to delete an instance of a ManyToMany field in Django
I am trying to delete an instance of a ManyToMany field in Django. I tried this but it's not working: act = Activity.objects.get(pk=pk) act.save() attendee, _ = Attendee.objects.get_or_create(student=request.user) **act.attendee.delete(attendee)** return... The idea is to delete an Attendee of a specific Activity given its primary key. These are my models: class Attendee(models.Model): student = models.ForeignKey(User, related_name="attendee") class Activity(models.Model): type = models.CharField(max_length=50, default="") title = models.CharField(max_length=200, default="") description = models.CharField(max_length=500) owner = models.ForeignKey(User, related_name="owner") college = models.CharField(max_length=200) location = models.CharField(max_length=200) room = models.CharField(max_length=200) startDate = models.DateTimeField(null=True, blank=True) endDate = models.DateTimeField(null=True, blank=True) attendee = models.ManyToManyField(Attendee, related_name="attendees",null=True, blank=True) -
Gunicorn/Django, ImportError: No module named application.wsgi
I'm trying to deploy a Django app using Heroku, but I'm running into the following error: "ImportError: No module named foodForThought.wsgi". My project is configured as such: my-project │ Procfile │ requirements.txt │ runtime.txt │ README.md │ ├───myproject │ │ db.sqlite3 │ │ django │ │ django._file_ │ │ import │ │ manage.py | | │ ├───myproject | | | wsgi.py | | | settings.py | | | urls.py | | | _init_.py | | | | | ├───_pycache_ | | │ ├───venv ... My wgsi.py file is configured as such: import os import signal import sys import traceback import time from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings") application = get_wsgi_application() application = DjangoWhiteNoise(application) My Procfile contains the following: web: gunicorn myproject.wsgi:application --log-file - Why is this producing an error? -
Unabl to create and start service to deploy Django in ubuntu 14.04
I following the nginx-django steps to deploy my project. I was trying to create Gunicorn service for Django to deploy on server. I use the following, [Unit] Description=Ourcase gunicorn daemon [Service] Type=simple User=nginx ExecStart=/var/www/test/gunicorn_start.sh [Install] WantedBy=multi-user.target After i store my service in /usr/lib/systemd/system/gunicorn_ourcase.service And i try to start this service by using service gunicorn_ourcase But i get error as gunicorn_ourcase: unrecognized service How can i create and start(on-start) my own service in ubuntu 14 for Django ? -
django fetch data using list
i have a list that takes values from the a database as ques=list(sorted(Upload.objects.filter(unique_id=tdetail), key=lambda x: random.random())) now i have saved ques in the database and in database it appears as [<Upload: 34-bb6f5d9a98604450>, <Upload: 31-bb6f5d9a98604450>, <Upload: 35-bb6f5d9a98604450>, <Upload: 30-bb6f5d9a98604450>, <Upload: 33-bb6f5d9a98604450>] here Upload is the name of the model and 34-bb6f5d9a98604450 is the slug value of that ques.... now i want to retrive the information using this list..... ques=list(Upload.objects.filter(slug=platform.list)) and it gives an empty list ......how can i retrive information using this list [<Upload: 34-bb6f5d9a98604450>, <Upload: 31-bb6f5d9a98604450>, <Upload: 35-bb6f5d9a98604450>, <Upload: 30-bb6f5d9a98604450>, <Upload: 33-bb6f5d9a98604450>] -
value too long for type character varying(1)
I am trying to deploy my app on heroku, everything went well, all the files were uploaded, but as soon as I ran heroku run python manage.py migrate it gave the following error for a particular field(choices field). django.db.utils.DataError: value too long for type character varying(1) The model in which the field is present is: models.py class Api(models.Model): User = get_user_model() notice_name = models.CharField(max_length=100, null=True) notice_desc = models.TextField() notice_file = models.FileField(upload_to="notice_files/", null=True, blank=True) notice_author = models.CharField(max_length=20, default='admin') notice_valid_till = models.DateTimeField(default=datetime.now, blank=True) notice_publish_date = models.DateTimeField(auto_now=True) year = models.CharField(max_length=5, null=True) branch = models.CharField(max_length=20, null=True) choices = models.CharField(max_length=20, null=True) user = models.ForeignKey('accounts.Account', on_delete=models.CASCADE, null=True) I tried varying the length of the choices field, but it didn't help. Can anyone help me out with this. -
Understanding Django user authentication system
I followed a couple of tutorials to create a custom authentication system and I'm trying to understand everything I'm doing because it doesn't work and I'm a bit lost. I have a class called CustomUserAuth that implements the "authenticate" method. In there, in the tutorial they simply do this to retrieve the user whose username is the same as we want: user = CustomUser.objects.get(username=username) since it didn't work even if I know I have that username in the database, I tried to print all the users: print(CustomUser.objects.all()) and I got that there were no users, and I don't really know why. My CustomUser inherits from AbstractBaseUser and in its code I have: objects = CustomUserManager() My CustomUserManager inherits from BaseUserManager. I tried to followed the source code in github but I don't know how and where Django access to the database. In my settings file I also added: AUTH_USER_MODEL = "custom_user.CustomUser" AUTHENTICATION_BACKENDS = ("custom_user.backends.CustomUserAuth",) My ultimate goal is to figure out why it doesn't work and it doesn't retrieve the users from the database, but I'm interested in knowing as well where does Django access the database. Thanks. -
django pwa authentication CSRF verification error
Please help! i have created a django PWA, with pre-fetch serviceworker to cache files, but while loggin in it causes CSRF Verification error. what should i do to fix it? -
Clear Google Cloud oAuth2 Token info when user's session ends
I'm working on a Python(3.6) & Django(1.10) project, in which I'm using some google cloud apis, I have used Google's OAuth2 for authentication, I have implemented it according to the google's documentation.It's saving the user's info in a file something called storage.json file first time and every time user is able to use this info when trying to authenticate with Google. What I want: I also have setup my app's login/signup with sessions as I'm using Django.I want to remove this token info of User's google account when the session for the user on my app ends. Mean when the session ends with my app, the user again will be redirected to a web browser tab to login and authenticate with google cloud. Here's what I have tried: def getauth(): logging.basicConfig(level=logging.INFO) parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, parents=[tools.argparser] ) # Parse the command line flages argv = [] flages = parser.parse_args(argv[1:]) flow = AuthClient.flow_from_clientsecrets(CLIENT_SECRET, SCOPES) store = file.Storage('/Users/abdul/PycharmProjects/Updated_IGUI/IGui/static/storage.json') credz = store.get() if credz is None or credz.invalid: credz = tools.run_flow(flow, store, flages) auth_http = credz.authorize(Http()) return auth_http -
Django, matching query does not exist
I am new to Django. When I run the command python manage.py runserver on pycharm, I get the error message like webapp.models.DoesNotExist: RecordSet matching query does not exist. The code of models.py is : from __future__ import unicode_literals import uuid import datetime from django.db import models class RecordSet(models.Model): name = models.CharField(max_length=512) value = models.TextField() def __unicode__(self): return "{0}: {1}".format(self.name, self.value) And the parent directory of models.py is the directory webapp. Any suggestions is appreciated, thanks! -
After delete database ,my Django does't work
I have some problem with my database, so I deleted db.sqlite3 and Migrations manually. than I recreate the database by using manage.py makemigrations <appname> manage. py migrate <appname> Everything looks normal,but when I get into localhost:8000, It is a blank page without anything (even if I never change the templates). To my confused, I can get into the admin page. Are there any mistakes in this process?what happened to my django app? -
Django Model Forms set possible values of foreign key dropdown
I have a form ReviewForm that extends ModelForm. ReviewForm's model is Review, which has the fields: class Review(models.Model): message = models.TextField(max_length = 4000) created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(null = True) rating = models.IntegerField( default = 5, validators = [MaxValueValidator(5), MinValueValidator(0)] ) prof = models.ForeignKey(Prof, related_name = 'reviews') course = models.ForeignKey(Course, related_name = 'reviews') user = models.ForeignKey(User, related_name = 'reviews') and for forms.py class ReviewForm(ModelForm): rating = CharField(widget=TextInput(attrs={'type': 'number','value': 5, 'min': 0, 'max': 5})) class Meta: model = Review fields = ['message', 'rating', 'prof', 'course', 'user'] I'm trying to pass initial values to the form before rendering it. Here's my code for views.py def review(request, prof_id=None): """ Review a prof """ # If there's an input prof, return review page for that prof if prof_id: user = User.objects.get(pk=request.user.id) prof = prof_views.prof(prof_id) course = prof.course_set.all() data = {'user': user, 'prof': prof, 'course': course} review_form = ReviewForm(initial=data) return render(request, 'reviews/review_form.html', {'review_form': review_form}) review_form = ReviewForm() return render(request, 'reviews/review_form.html', {'review_form': review_form}) The initial values of prof and user are set successfully. I'm trying to pass in the courses of a prof, and have the form display that queryset. However, Django doesn't seem to accept it. I'm not sure how to code … -
How to use docopt inside django view
I recently come across the python module docopt which is a command line parser which basically parsers the docstring you build to your program. I checked out the website and played around with it on http://try.docopt.org/ and found it useful that it works in the browser and thought it would be perfect for my django web app. After checking out the github repo at https://github.com/docopt/try.docopt.org i found the example was implemented in flask which i have never used and could not quite figure out how it worked. I have a script called votes.py that has a bunch of functions that i will be using but i just need the docopt to parse user command string from an ajax post request from a form element votes.py #A script with a bunch of example simple functions def get_vote_count(vote_candidate): vote_count = Votes.objects.filter(candidate = vote_candidate).count() return vote_count .... views.py #Will display candiate info def vote_info_list(request): template = 'app/vote.html' if(request.is_ajax() and request.method == 'POST'): command = request.POST.get("commmand","") #command string #e.g votes -c bob ''' I need to parse it here ''' If anyone can provide a simple docopt script solution that could work with this example to get me going will be greatly appreciated