Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Iterating through directory in django without "IsADirectoryError: [Errno 21] Is a directory" error
I have a folder (static/classification) in a django project full of .txt files. In my views.py file I am trying to iterate over each file in the (static/classification) folder however, when I run my django server locally I get the an IsADirectoryError. I have it working in standard python, however; Django wont let me iterate through my directory. views.py dataSetPath = "static/classification" dirFileList = os.path.dirname(os.path.dirname(dataSetPath)) Ill use the dirFileList in a function to generate a list of words in each file, however; I cant get to that point due to the error. -
There is no unique constraint matching given keys for referenced table in django
There are a lot of questions related to this error on SO, but either I understand each of them incorrectly, or they do not apply to this case. I have the following code in photo/models.py. class Photo(EmptyModelBase): # there's a lot of fields in this model. And the following in points/models.py class Label(EmptyModelBase): photo = models.ForeignKey(Photo, related_name='labels') Considering this works, I understand it to mean that the Photo model holds an unique key, since Label can have a photo field with a foreignkey to the Photo model. So, next I wanted to add another model to points/models.py , that also holds a foreignkey to Photos class Material(EmptyModelBase): photo = models.ForeignKey(Photo, related_name='material') When trying to add these changes to the database, I get the following error: django.db.utils.ProgrammingError: there is no unique constraint matching given keys for referenced table "photos_photo" What I though this error meant is that the Photo model does not have an unique constraint, i.e. entries in the Photo model are not necessarily unique, therefor the foreignkey might not know which entry to use. However, I can add the foreignkey in Label to the model, so that explanation doesn't appear to make sense. -
Django Manytomany field with foreign key cannot get the data?
Im trying to to get the user data from the team models members field that's a many-to-many field with a though with its own model that has a foreign key that leads to the standard users that are registered and paste it into a template. But all I get is blank, it pastes the number of people that are created the only things it doesn't is the text. class Team(models.Model): name = models.CharField(max_length=16) logo = models.ImageField(upload_to='teams/avatars', default='static/img/userpreload.png') background = models.ImageField(upload_to='teams/backgrounds', default='static/img/userpreload.png') description = models.TextField(blank=True) people_needed = models.PositiveSmallIntegerField() members = models.ManyToManyField(User, through='TeamMembership') accepts_applications = models.BooleanField() class TeamMembership(models.Model): user = models.ForeignKey(User) team = models.ForeignKey(Team) leader = models.BooleanField() In the template, I have this. {% if teamhasmembers %} <div class="tab-pane fade" id="members" role="tabpanel" aria-labelledby="members-tab"> <div> </div> <div id="userslist"> {% for member in requested_team.members_queryset.all %} <div class="listmember {% if member.leader is true %} memberlsleader {% endif %}"> <div class="memberinfo"> <div id="memberimg"> <img src="{{ member.user.extendeduser.background.url }}"> </div> {{ member.user.username }} </div> </div> {% endfor %} </div> </div> {% endif %} I feeling im missing one thing to get it to work but I don't know what. thanks in advance -
Nginx not serving Django static files (Code Inside)
I will admit, I am a bit of a biased searcher... If I do not see a similar problem in the title of a post, I will likely not click it. That aside, I have done my research and cannot find a solid solution that works for me Problem I am using Apache 2.4 and mod_wsgi 4.5.22 as well as attempting to use nginx 1.12.2-1~jessie for serving my static files. My nginx setup does not seem to be serving my files. Setup Here is my apache2 .conf file: ... Alias /robots.txt /home/user/web/domain.com/public_html/robots.txt Alias /favicon.ico /home/user/web/domain.com/public_html/favicon.ico IncludeOptional /home/user/conf/web/apache2.domain.com.conf* <Directory /home/user/web/domain.com/user/project/> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /home/user/web/domain.com/project/app/> AllowOverride All Options +Includes </Directory> LoadModule wsgi_module "/root/.virtualenvs/user/local/lib/python2.7/site-packages/mod_wsgi/server/mod_wsgi-py27.so" WSGIDaemonProcess domain.com user=user group=user processes=2 threads=25 WSGIProcessGroup domain.com WSGIPythonHome "/root/.virtualenvs/user" Here is my nginx .conf file: server { listen X.X.X.X:80; server_name domain.com www.domain.com; error_log /var/log/apache2/domains/domain.com.error.log error; location / { proxy_pass http://X.X.X.X:8080; location ~* ^.+\.(jpeg|jpg|png|gif|bmp|ico|svg|tif|tiff|css|js|htm|html|ttf|otf|webp|woff|txt|csv|rtf|doc|docx|xls|xlsx|ppt|pptx|odf|odp|ods|odt|pdf|psd|ai|eot|eps|ps|zip|tar|tgz|gz|rar|bz2|7z|aac|m4a|mp3|mp4|ogg|wav|wma|3gp|avi|flv|m4v|mkv|mov|mpeg|mpg|wmv|exe|iso|dmg|swf)$ { root /home/user/web/domain.com/public_html; access_log /var/log/apache2/domains/domain.com.log combined; access_log /var/log/apache2/domains/domain.com.bytes bytes; expires max; try_files $request_uri @fallback; } } location /error/ { alias /home/user/web/domain.com/document_errors/; } location @fallback { proxy_pass http://X.X.X.X:8080; } location /static { autoindex on; alias /home/user/web/domain.com/project/app/static/; } location ~ /\.ht {return 404;} location ~ /\.svn/ {return 404;} location ~ /\.git/ {return … -
How to get data from manytomany field though with the foreign key?
Im trying to to get the user data from the team models members field that's a many-to-many field with a though with its own model that has a foreign key that leads to the standard users that are registered and paste it into a template. But all I get is blank, it pastes the number of people that are created the only things it doesn't is the text. class Team(models.Model): name = models.CharField(max_length=16) logo = models.ImageField(upload_to='teams/avatars', default='static/img/userpreload.png') background = models.ImageField(upload_to='teams/backgrounds', default='static/img/userpreload.png') description = models.TextField(blank=True) people_needed = models.PositiveSmallIntegerField() members = models.ManyToManyField(User, through='TeamMembership') accepts_applications = models.BooleanField() class TeamMembership(models.Model): user = models.ForeignKey(User) team = models.ForeignKey(Team) leader = models.BooleanField() In the template, I have this. {% if teamhasmembers %} <div class="tab-pane fade" id="members" role="tabpanel" aria-labelledby="members-tab"> <div> </div> <div id="userslist"> {% for member in requested_team.members_queryset.all %} <div class="listmember {% if member.leader is true %} memberlsleader {% endif %}"> <div class="memberinfo"> <div id="memberimg"> <img src="{{ member.user.extendeduser.background.url }}"> </div> {{ member.user.username }} </div> </div> {% endfor %} </div> </div> {% endif %} I feeling im missing one thing to get it to work but I don't know what. -
Best practice to deploy and reference files in gitignore
I'm trying to deploy a Django app on Heroku. As recommended for security, I don't want to commit and push my secret key from the settings.py file, so I put the key in a separate file and imported it into settings.py. I put my file containing the secret key into .gitignore so that it doesn't get committed. Now the problem is when I'm pushing to Heroku, I get a ModuleNotFoundError - which makes sense because this file was never committed. Is there a workaround or best practice to use secret keys without exposing them?