Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Correctly Use JsonResponse to Handle Ajax Request
I am trying to use JsonResponse to return data for a successful Ajax request but am unsure how to format the data. data = request.POST[data_from_javascript] # do something with data return JsonResponse(?) I want to send back the data to the Javascript code and say that it was successful so it can run the success function but am unsure how to correctly do so. -
collectstatic --clear skipping instead of deleting
I am trying to update admin static files after upgrading to Django 2.2, but when I run python3 ./manage.py collectstatic --clear --verbosity 3, I see the following output: Skipping 'admin/css/base.css' (not modified) Skipping 'admin/css/changelists.css' (not modified) Skipping 'admin/css/dashboard.css' (not modified) Skipping 'admin/css/forms.css' (not modified) Skipping 'admin/css/ie.css' (not modified) Skipping 'admin/css/login.css' (not modified) ... I would think that using the --clear option would prevent skipping any files. How can I force delete? These static files are served on AWS S3. I am able to update modified static files just fine, and the --clear option worked prior to the upgrade. I am using the following relevant packages: Django==2.2.3 django_storages==1.7.1 boto==2.49.0 settings.py from boto.s3.connection import OrdinaryCallingFormat ########## AWS CONFIGURATION AWS_STORAGE_BUCKET_NAME = 'xxxxx' AWS_S3_REGION_NAME = 'xxxxx' AWS_S3_CALLING_FORMAT = OrdinaryCallingFormat() AWS_S3_CUSTOM_DOMAIN = '%s' % AWS_STORAGE_BUCKET_NAME AWS_S3_HOST = 's3-%s.amazonaws.com' % AWS_S3_REGION_NAME STATIC_ROOT = normpath(join(SITE_ROOT, 'assets')) STATICFILES_DIRS = ( normpath(join(SITE_ROOT, 'static')), ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', #'django.contrib.staticfiles.finders.AppDirectoriesFinder', #causes verbose duplicate notifications in django 1.9 ) STATICFILES_LOCATION = 'static' STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION) STATICFILES_STORAGE = 'custom_storages.StaticStorage' -
How to define a foreign key dynamicaly with abstract=True or Mixin?
I want to define a foreign key with a dynamic related_name. All the childs have the same parent. class AbstractChild(models.Model): class Meta: abstract=True related_name = None def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.parent = models.ForeignKey( Parent,on_delete=models.CASCADE, related_name=self.related_name ) self.created_at = models.DateTimeField(auto_now_add=True) class Child2(AbstractChild): #this should create the foreign key with the dynamic related_name related_name="child2" What should be the way for this? Mixin or abstract model? -
How to refresh an item in a flatList when like action happened?
So I have a flatList that gets data from an API. It does not refresh itself automatically not even with extraData. So I just want that the picture on that post changes to the LIKED picture. I already tried that in the likeAction function inside the StandardPostView that it gets refreshed by the response data, but then all the new / or next posts got the same LIKED picture. constructor(props) { super(props); this.state = { gestureName: 'none', hasLiked: this.props.has_liked, count:this.props.likes, current_user:"", modalVisible: false, dropdown:"", }; } likeAction = () => { axios.get(URL+'/api/posts/like/'+this.props.post_id, {headers: {'Authorization':'Token '+this.props.jwt}}) .then((response) => { }).catch((error) => { this.setState({ error: 'Error retrieving data', }); }); } return ( <Text style={styles.date}>{format(new Date(this.props.date), 'MMMM Do, YYYY')}</Text> <View style={styles.likeSection}> <TouchableOpacity onPress={this.likeAction}> <Image style={styles.likeImage} source={image_url}/> </TouchableOpacity> <TouchableOpacity onPress={this.props.goToUser}> <Image source={require("../icons/share.png")} style={styles.share}/> </TouchableOpacity> </View> </View> ); } } <StandardPostView current={this.state.user} author_id={item.author.id} username={item.username} title={item.title} content={item.content} image={{uri:item.author.profile_image}} date={item.date_posted} handleRefresh={this.handleRefresh} likes={item.likes} post_id={item.id} jwt = {this.props.screenProps.jwt} refresh = {this.handleRefresh} has_liked = {item.has_liked} editPost={() => this.props.navigation.navigate('EditPost',{ title:item.title, content:item.content, post_id:item.id })} goToProfile={() => this.props.navigation.navigate('UserProfile', { user_id:item.author.user })} goToPost={() => this.props.navigation.navigate('SinglePost', { post_id:item.id })} goToPostLike={() => this.props.navigation.navigate('PostLikes', { post_id:item.id, title:"Likes" })} goToUser={()=> this.props.navigation.navigate('ChooseUser',{ post_id:item.id })} /> )} /> -
Django doesn't change html when changing route
I created several html's for each project functionality, but when I change route, html doesn't change. The only html that appears is the homepage, index.html. urls.py: from website.views import IndexTemplateView, FuncionarioListView, FuncionarioUpdateView, FuncionarioCreateView, FuncionarioDeleteView from django.conf.urls import patterns, include, url app_name = 'website' urlpatterns = [ # GET / url('', IndexTemplateView.as_view(), name="index"), # GET /funcionario/cadastrar url('funcionario/cadastrar', FuncionarioCreateView.as_view(), name="cadastra_funcionario"), # GET /funcionarios url('funcionarios/', FuncionarioListView.as_view(), name="lista_funcionarios"), # GET/POST /funcionario/{pk} url('funcionario/<pk>', FuncionarioUpdateView.as_view(), name="atualiza_funcionario"), # GET/POST /funcionarios/excluir/{pk} url('funcionario/excluir/<pk>', FuncionarioDeleteView.as_view(), name="deleta_funcionario"), ] views.py: # -*- coding: utf-8 -*- from django.core.urlresolvers import reverse_lazy from django.views.generic import TemplateView, ListView, UpdateView, CreateView, DeleteView from helloworld.models import Funcionario from website.forms import InsereFuncionarioForm # PÁGINA PRINCIPAL # ---------------------------------------------- class IndexTemplateView(TemplateView): template_name = "website/index.html" # LISTA DE FUNCIONÁRIOS # ---------------------------------------------- class FuncionarioListView(ListView): template_name = "website/lista.html" model = Funcionario context_object_name = "funcionarios" # CADASTRAMENTO DE FUNCIONÁRIOS # ---------------------------------------------- class FuncionarioCreateView(CreateView): template_name = "website/cria.html" model = Funcionario form_class = InsereFuncionarioForm success_url = reverse_lazy("website:lista_funcionarios") # ATUALIZAÇÃO DE FUNCIONÁRIOS # ---------------------------------------------- class FuncionarioUpdateView(UpdateView): template_name = "website/atualiza.html" model = Funcionario fields = '__all__' context_object_name = 'funcionario' success_url = reverse_lazy("website:lista_funcionarios") # EXCLUSÃO DE FUNCIONÁRIOS # ---------------------------------------------- class FuncionarioDeleteView(DeleteView): template_name = "website/exclui.html" model = Funcionario context_object_name = 'funcionario' success_url = reverse_lazy("website:lista_funcionarios") and an example of one of the … -
Django Database Router not working properly
I have the following DB router, located in proj/inventory/inventory_router.py: class Inventory_Router: def db_for_read(self, model, **hints): if model._meta.app_label == 'webhooks' or model._meta.app_label == 'auth': return 'default' elif model._meta.app_label == 'inventory': return 'user_0001' else: return None def db_for_write(self, model, **hints): if model._meta.app_label == 'webhooks' or model._meta.app_label == 'auth': return 'default' elif model._meta.app_label == 'inventory': return 'user_0001' else: return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == 'auth' or obj2._meta.app_label == 'auth': return True else: return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == 'webhooks' or app_label == 'auth': return db == 'default' elif app_label == 'inventory': return True else: return None and the Product model for the inventory app, proj/inventory/models.py: from django.db import models class Product(models.Model): ... class Meta: app_label = 'inventory' My settings.py: DATABASE_ROUTERS = [ 'inventory.inventory_router.Inventory_Router', ] DATABASE_APPS_MAPPING = { # not sure if I need this? 'auth':'default', } DATABASES = { 'default': { 'ENGINE':'django.db.backends.mysql', 'NAME':'account', 'USER':'root', 'PASSWORD':'password', 'HOST':'localhost', 'PORT':'3306' }, 'user_0001': { 'ENGINE':'django.db.backends.mysql', 'NAME':'user_0001', 'USER':'user_0001', 'PASSWORD':'password', 'HOST':'localhost', 'PORT':'3306' }, ... } I am trying to have all models from the inventory app only create tables in the user_0001 schema, and not in the default account schema. When I run python3 manage.py migrate, the default schema, account, … -
One week imposible to Deploy django in windows with apache
500 Internal Server Error is what I have all the time. Hello guys I’m trying to deploy django with apache server in Windows Without any success, Any help is welcome. pro1.local is already setup in host and Works fine. WSGI is perfectly installed. mod_wsgi-express module-config LoadFile "c:/program files (x86)/python37-32/python37.dll" LoadModule wsgi_module "c:/program files (x86)/python37-32/lib/site-packages/mod_wsgi/server/mod_wsgi.cp37-win32.pyd" WSGIPythonHome "c:/program files (x86)/python37-32" Httpd.conf LoadFile "c:/program files (x86)/python37-32/python37.dll" LoadModule wsgi_module "c:/program files (x86)/python37-32/lib/site-packages/mod_wsgi/server/mod_wsgi.cp37-win32.pyd" WSGIPythonHome "c:/program files (x86)/python37-32" Httpd-vhost.conf # Virtual Hosts # # Required modules: mod_log_config # If you want to maintain multiple domains/hostnames on your # machine you can setup VirtualHost containers for them. Most configurations # use only name-based virtual hosts so the server doesn't need to worry about # IP addresses. This is indicated by the asterisks in the directives below. # # Please see the documentation at # <URL:http://httpd.apache.org/docs/2.4/vhosts/> # for further details before you try to setup virtual hosts. # # You may use the command line option '-S' to verify your virtual host # configuration. # # VirtualHost example: # Almost any Apache directive may go into a VirtualHost container. # The first VirtualHost section is used for all requests that do not # match a ServerName or ServerAlias … -
Celery worker getting crashed on Heroku
I am working on a Django project which I have pushed on Heroku, for background tasking I have used Celery. Although Celery works fine locally, but on the Heroku server I have observed that celery worker is getting crashed. I have set CLOUDAMQP_URL properly in settings.py and configured worker configuration in Procfile, but still worker is getting crashed. Procfile web: gunicorn my_django_app.wsgi --log-file - worker: python manage.py celery worker --loglevel=info Settings.py ... # Celery BROKER_URL = os.environ.get("CLOUDAMQP_URL", "django://") #CELERY_BROKER_URL = 'amqp://localhost' BROKER_POOL_LIMIT = 1 BROKER_CONNECTION_MAX_RETRIES = 100 CELERY_TASK_SERIALIZER="json" CELERY_RESULT_SERIALIZER="json" CELERY_RESULT_BACKEND = "amqp://" Logs 2019-08-05T15:03:51.296563+00:00 heroku[worker.1]: State changed from crashed to starting 2019-08-05T15:04:05.370900+00:00 heroku[worker.1]: Starting process with command `python manage.py celery worker --loglevel=info` 2019-08-05T15:04:06.173210+00:00 heroku[worker.1]: State changed from starting to up 2019-08-05T15:04:09.067794+00:00 heroku[worker.1]: State changed from up to crashed 2019-08-05T15:04:08.778426+00:00 app[worker.1]: Unknown command: 'celery' 2019-08-05T15:04:08.778447+00:00 app[worker.1]: Type 'manage.py help' for usage. 2019-08-05T15:04:09.048404+00:00 heroku[worker.1]: Process exited with status 1 -
Using django-user-accounts with costom PasswordChangeView - Rediect Error
I'm setting up a django project and I need a user-management-system that follow our user policy. It needs to force the user to change the password after 180 days. So I decided to use pinax/django-user-accounts. I have a own django app named 'accounts' that customize the standard django auth behaviour - essantially defining custom templates. When the password expires, django redirects to /accounts/change-password/?next=account_password and so it loops and a browser redirect error shows up in my Firefox. I setup django-user-accounts: ACCOUNT_PASSWORD_EXPIRY = 60*60*2 # seconds until pw expires ACCOUNT_PASSWORD_USE_HISTORY = True ACCOUNT_LOGIN_URL = 'accounts:login' ACCOUNT_LOGOUT_REDIRECT_URL = 'accounts:logout' ACCOUNT_PASSWORD_CHANGE_REDIRECT_URL = 'accounts:account_password' SITE_ID = 1 I also tried to hardcode the ACCOUNT_PASSWORD_CHANGE_REDIRECT_URL to '/accounts/change-password'. The result was the same. The login_required-decorator was changed from django.contrib.auth.decorators to account.decorators. The urls.py of my accounts app is: app_name = 'accounts' urlpatterns = [ ... path( 'change-password/', MyPasswordChangeView.as_view(), name='account_password' ), ] I'm created my own password change view inherits from django.contrib.auth.views.PasswordChangeView: class MyPasswordChangeView(PasswordChangeView): template_name = 'accounts/password_change.html' def get_success_url(self): return '/' The goal is to show up the change-password/ page on every request if the password is expired. It allready tries to get there, but ends up in this redirect loop. -
How to set a postgres table default ID to uuid_generate_v4() with Django
I have been told to set all the table default IDs in my Django project to the value of the postgresql method uuid_generate_v4(). An example of the current models I'm using is: import uuid from django.db import models class MyModel(models.Model): class Meta: ordering = ("my_var",) id = models.UUIDField(primary_key=True, default=uuid.uuid4, blank=True, editable=False) my_var = models.CharField(max_length=64, unique=True) I have come to understand that it would not be advised to mix SQLAlchemy with Django, so how can I best implement what is asked of me? (Note: yes, default=uuid.uuid4 isn't enough for what my project requires) -
Django creates new cart-product instead of updating already existing object
In my django shop I have a adding to cart function. But if I add the same product 2 times to the cart with a different quantity, 2 different objects are created. What's wrong with my code? here is my view def add_to_cart_view(request): cart = getting_or_creating_cart(request) product_slug = request.POST.get('product_slug') product = Product.objects.get(slug=product_slug) if request.method == "POST": form = CartAddProductForm(request.POST or None) if form.is_valid(): quantity = form.cleaned_data['quantity'] new_item, created = CartItem.objects.get_or_create( product=product, item_cost=product.price, quantity=quantity, all_items_cost=product.price*quantity, ) if new_item.product.title == product.title: cart.items.add(new_item) cart.save() if not created: new_item.quantity += quantity new_item.save(force_update=True) cart.save() new_cart_total = 0.00 for item in cart.items.all(): new_cart_total += float(item.all_items_cost) cart.cart_total_cost = new_cart_total cart.save() return JsonResponse({ 'cart_total': cart.items.count() }) And here is my models class CartItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) quantity = models.PositiveIntegerField(null=True, default=1) item_cost = models.DecimalField(max_digits=9, decimal_places=2, default=0.00) all_items_cost = models.DecimalField(max_digits=9, decimal_places=2, default=0.00) def __str__(self): return str(self.product.title) class Cart(models.Model): items = models.ManyToManyField(CartItem, blank=True) cart_total_cost = models.DecimalField(max_digits=9, decimal_places=2, default=0.00) def __str__(self): return str(self.id) Thanks for any help! -
Why can't I see user-added information with Django?
I'm using Django 2.2 and PostgreSQL. I want to display the product information that the user has added to the detail page. I see the information in the 'StoreOtherInfo' model, but I don't see the information in the 'Product' model. How can I do that? store/models.py class StoreOtherInfo(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,blank=True, null=True) phone = models.CharField(max_length=11) fax = models.CharField(max_length=11) province = models.CharField(max_length=11) district = models.CharField(max_length=11) neighborhood = models.CharField(max_length=11) def __str__(self): return self.user.username products/models.py class Product(models.Model): seller = models.ForeignKey(User, on_delete = models.CASCADE) product_name = models.CharField(max_length = 50) description = RichTextField() added_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.seller store/views.py from store.models import StoreOtherInfo from products.models import Product def neighbor_detail(request,username): neighbor_detail = get_object_or_404(User,username = username) neighbor_list = StoreOtherInfo.objects.all() product_list = Product.objects.all() return render(request, 'store/neighbor_detail.html', {'neighbor_detail':neighbor_detail, 'neighbor_list':neighbor_list, 'product_list':product_list}) templates/neighbor_detail.html <strong><p>{{neighbor_detail.first_name}} {{neighbor_detail.last_name}}</p></strong> <p>{{neighbor_detail.username}}</p> <p>{{neighbor_detail.email}}</p> <p>{{neighbor_detail.storeotherinfo.phone}}</p> <p>{{neighbor_detail.storeotherinfo.fax}}</p> <p>{{neighbor_detail.storeotherinfo.province}}</p> <p>{{neighbor_detail.storeotherinfo.district}}</p> <p>{{neighbor_detail.storeotherinfo.neighborhood}}</p> <p>{{neighbor_detail.product.product_name}}</p> <p>{{neighbor_detail.product.description}}</p> <p>{{neighbor_detail.product.added_date}}</p> -
Asynchronous asyncio Django command runs sequentially
I have written a simple command to loop through all of Result objects and check its www field (representing URL of the published scientific result eg. https://doi.org/10.1109/5.771073) There is 1M results in our db and I want to check the www field, if link is corrupted, I will guess it by appending actual doi to https://doi.org/ and save it (in the www field) This is my first time working with asyncio but I think barebones of my code are right and I can't find out, why code gets ran synchronously. Main command: # -*- coding: utf-8 -*- from __future__ import unicode_literals import asyncio import time from django.core.management.base import BaseCommand from isvav.models import Result def run_statistics(array_of_results, num_of_results): num_of_correct_urls = 0 sum_check_time = 0 max_check_time = 0 for res in array_of_results: if res[0]: num_of_correct_urls += 1 if res[1] > max_check_time: max_check_time = res[1] sum_check_time += res[1] return f"""ran statistics on {num_of_results} isvav.results \n ---------------------------------------------------------------------------- correct/corrupted link ratio: {num_of_correct_urls} / {num_of_results - num_of_correct_urls}\n Mean time to check URL: {sum_check_time / num_of_results}\n """ class Command(BaseCommand): help = 'checks url in www field of isvav.result, if the link is unresponsive, tries to generate new hyperlink ' \ '(using DOI) and saves it in www_processed field' … -
uWSGI runs Django project from command line but not from Emperor uwsgi.service file
I am running a virtualenv with Python3.6 on Ubuntu 16.04 for my Django project using uwsgi and NGINX. I have uWSGI installed globally and also in the virtualenv. I can run my project from the command line using uWSGI within the env with /home/user/Env/myproject/bin/uwsgi --http :8080 --home /home/user/Env/myproject --chdir /home/user/myproject/src/myproject -w myproject.wsgi and go to my domain and it loads fine. However I am obviously running uWSGI in "Emperor mode" and when I set the service file up (along with NGINX) the domain displays internal server error. The uWSGI logs trace to --- no python application found --- I was having this problem when running uwsgi --http :8080 --home /home/user/Env/myproject --chdir /home/user/myproject/src/myproject -w myproject.wsgi because it was using the global install uwsgi instead of the virtualenv one. I changed my StartExec to the virtualenv uwsgi path but no luck. I can't figure out what I'm doing wrong, path error? Syntax error? my /etc/systemd/system/uwsgi.service file [Unit] Description=uWSGI Emperor service [Service] ExecStartPre=/bin/bash -c 'mkdir -p /run/uwsgi; chown user:www-data /run/uwsgi' ExecStart=/home/user/Env/myproject/bin/uwsgi --emperor /etc/uwsgi/sites Restart=always KillSignal=SIGQUIT Type=notify NotifyAccess=all [Install] WantedBy=multi-user.target -
Showing JSON data from DB to django template using Bootstrap tabs
Sorry I'm a programming newb.... But I am trying to use Bootstrap's tabs navigation to view JSON data from a DB. I'm transforming the JSON data to a 2d array and storing my data as the following dictionary: tables = {u'table1': [[u'CS6140', u'Machine Learning', u'Sara Arunagiri'], [u'CS5100', u'Foundations of Artificial Intelligence ', u'Chris Amato'], [u'CS6220', u'Data Mining', u'Pablo Esteves']], u'table2': [[u'Paris, France', u'06/01/2019 - 06/15/2019', u'James Fraser'], [u'Edinborough, Scotland', u'10/14/2019 - 10/20/2019', u'Claire Beauchamp'], [u'Rome, Italy', u'12/14/2019-12/24/2019', u'Timothy Dalton']], u'table3': [[32423, u'iced coffee', 3.67], [34241, u'bagel', 2.99], [3109247, u'sanwich', 5.99]]} Thus each table dict entry corresponds to one table.So I'm trying to loop through the dictionary and 2d array to create different tables. I'm currently trying to loop through the dictionary as follows but I am getting the 2d arrays replicated 3 times for each of the tables when instead I want each table in my dictionary to only be shown once for each tab. {% for table in tables %} <div class="tab-content"> <div id="{{ table }}" class="tab-pane active"> {% for table in tables.values %} <table class="table"> <tbody> {% for row in table %} <tr> {% for item in row %} <td>{{ item }}</td> {% endfor %} </tr> {% endfor … -
isinstance() arg 2 must be a type or tuple of types error in Django
I keep getting this error when using Django Rest Framework: isinstance() arg 2 must be a type or tuple of types Here is my model: class mymodel(models.Model): firstfield = models.ArrayModelField(models.FloatField()) secondfield = models.ArrayModelField(models.FloatField()) def save(self, *args, using=None, **kwargs): super(mymodel, self).save(*args, using='mydb', **kwargs) Here is what my data looks like: id: 'some id here' firstfield: ['somefloat', 'somefloat'], ['another float', 'another float'] ... secondfield: ['somefloat', 'somefloat'], ['another float', 'another float'] ... I think the problem is with my MongoDB data. Basically, firstfield and 'secondfield' are both lists, containing other lists, each one with two float numbers. Every advice to fix this is appreciated -
ModuleNotFoundError: No module named 'config'
I am new to python and django. Every time I try any django command, I am getting this error. Following are the steps that I tried: [namespace] user@tux:~/Workspace/udemy$ python3 -m venv restapi-basics [namespace] user@tux:~/Workspace/udemy$ cd restapi-basics/ [namespace] user@tux:~/Workspace/udemy/restapi-basics$ source bin/activate (restapi-basics) [namespace] user@tux:~/Workspace/udemy/restapi-basics$ which python /home/user/Workspace/udemy/restapi-basics/bin/python (restapi-basics) [namespace] user@tux:~/Workspace/udemy/restapi-basics$ python --version Python 3.6.8 (restapi-basics) [namespace] user@tux:~/Workspace/udemy/restapi-basics$ which pip /home/user/Workspace/udemy/restapi-basics/bin/pip (restapi-basics) [namespace] user@tux:~/Workspace/udemy/restapi-basics$ pip --version pip 9.0.1 from /home/user/Workspace/udemy/restapi-basics/lib/python3.6/site-packages (python 3.6) (restapi-basics) [namespace] user@tux:~/Workspace/udemy/restapi-basics$ pip install django djangorestframework djangorestframework-jwt Collecting django Downloading https://files.pythonhosted.org/packages/d6/57/66997ca6ef17d2d0f0ebcd860bc6778095ffee04077ca8985928175da358/Django-2.2.4-py3-none-any.whl (7.5MB) 100% |████████████████████████████████| 7.5MB 193kB/s Collecting djangorestframework Downloading https://files.pythonhosted.org/packages/af/2a/055e65e1aa25cc2726d68d78b859a7b5955c673bc5e4646b205c21e05b25/djangorestframework-3.10.2-py3-none-any.whl (908kB) 100% |████████████████████████████████| 911kB 748kB/s Collecting djangorestframework-jwt Downloading https://files.pythonhosted.org/packages/2b/cf/b3932ad3261d6332284152a00c3e3a275a653692d318acc6b2e9cf6a1ce3/djangorestframework_jwt-1.11.0-py2.py3-none-any.whl Collecting pytz (from django) Downloading https://files.pythonhosted.org/packages/87/76/46d697698a143e05f77bec5a526bf4e56a0be61d63425b68f4ba553b51f2/pytz-2019.2-py2.py3-none-any.whl (508kB) 100% |████████████████████████████████| 512kB 928kB/s Collecting sqlparse (from django) Downloading https://files.pythonhosted.org/packages/ef/53/900f7d2a54557c6a37886585a91336520e5539e3ae2423ff1102daf4f3a7/sqlparse-0.3.0-py2.py3-none-any.whl Collecting PyJWT=1.5.2 (from djangorestframework-jwt) Downloading https://files.pythonhosted.org/packages/87/8b/6a9f14b5f781697e51259d81657e6048fd31a113229cf346880bb7545565/PyJWT-1.7.1-py2.py3-none-any.whl Installing collected packages: pytz, sqlparse, django, djangorestframework, PyJWT, djangorestframework-jwt Successfully installed PyJWT-1.7.1 django-2.2.4 djangorestframework-3.10.2 djangorestframework-jwt-1.11.0 pytz-2019.2 sqlparse-0.3.0 (restapi-basics) [namespace] user@tux:~/Workspace/udemy/restapi-basics$ which django-admin /home/user/Workspace/udemy/restapi-basics/bin/django-admin (restapi-basics) [namespace] user@tux:~/Workspace/udemy/restapi-basics$ django-admin startproject cfehome (restapi-basics) [namespace] user@tux:~/Workspace/udemy/restapi-basics$ cd cfehome/ (restapi-basics) [namespace] user@tux:~/Workspace/udemy/restapi-basics/cfehome$ ls cfehome manage.py (restapi-basics) [namespace] user@tux:~/Workspace/udemy/restapi-basics/cfehome$ python manage.py runserverTraceback (most recent call last): File "/home/user/Workspace/udemy/restapi-basics/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/user/Workspace/udemy/restapi-basics/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 60, in execute super().execute(*args, **options) File "/home/user/Workspace/udemy/restapi-basics/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File … -
Pip install error exit status 1 while installing a pip package
I'm having a issue while installing a python package, it came out a issue that something regarding of spacy issue . How could i solve it and install successfully ? I am a rookie on python Collecting pyresparser Using cached https://files.pythonhosted.org/packages/ad/8f/5a55cfb269621d3374a6ba4aed390267f65bdf6c4fed8b1c0cbf5a118f0e/pyresparser-1.0.2-py3-none-any.whl Collecting idna>=2.8 (from pyresparser) Downloading https://files.pythonhosted.org/packages/14/2c/cd551d81dbe15200be1cf41cd03869a46fe7226e7450af7a6545bfc474c9/idna-2.8-py2.py3-none-any.whl (58kB) |████████████████████████████████| 61kB 261kB/s Collecting pyrsistent>=0.15.2 (from pyresparser) Using cached https://files.pythonhosted.org/packages/b9/66/b2638d96a2d128b168d0dba60fdc77b7800a9b4a5340cefcc5fc4eae6295/pyrsistent-0.15.4.tar.gz Collecting thinc>=7.0.4 (from pyresparser) Using cached https://files.pythonhosted.org/packages/92/39/ea2a3d5b87fd52fc865fd1ceb7b91dca1f85e227d53e7a086d260f6bcb93/thinc-7.0.8.tar.gz Collecting blis>=0.2.4 (from pyresparser) Using cached https://files.pythonhosted.org/packages/59/9e/84a83616cbe5daa94909da38b780e93bf566dc2113c3dc35d7b4cad52f63/blis-0.2.4.tar.gz Collecting tqdm>=4.32.2 (from pyresparser) Using cached https://files.pythonhosted.org/packages/9f/3d/7a6b68b631d2ab54975f3a4863f3c4e9b26445353264ef01f465dc9b0208/tqdm-4.32.2-py2.py3-none-any.whl Collecting certifi>=2019.6.16 (from pyresparser) Using cached https://files.pythonhosted.org/packages/69/1b/b853c7a9d4f6a6d00749e94eb6f3a041e342a885b87340b79c1ef73e3a78/certifi-2019.6.16-py2.py3-none-any.whl Collecting spacy>=2.1.4 (from pyresparser) Using cached https://files.pythonhosted.org/packages/f1/04/f25cdc3cb6d143ef397c23718026aff606c3e558cbd4939e9e4cb0a4b515/spacy-2.1.7.tar.gz Installing build dependencies ... error ERROR: Command errored out with exit status 1: command: 'c:\users\user\appdata\local\programs\python\python37-32\python.exe' 'c:\users\user\appdata\local\programs\python\python37-32\lib\site-packages\pip' install --ignore-installed --no-user --prefix 'C:\Users\User\AppData\Local\Temp\pip-build-env-kc70rx4b\overlay' --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- setuptools 'wheel>0.32.0.<0.33.0' Cython 'cymem>=2.0.2,<2.1.0' 'preshed>=2.0.1,<2.1.0' 'murmurhash>=0.28.0,<1.1.0' 'thinc>=7.0.8,<7.1.0' cwd: None Complete output (70 lines): Collecting setuptools Using cached https://files.pythonhosted.org/packages/ec/51/f45cea425fd5cb0b0380f5b0f048ebc1da5b417e48d304838c02d6288a1e/setuptools-41.0.1-py2.py3-none-any.whl Collecting wheel>0.32.0.<0.33.0 Using cached https://files.pythonhosted.org/packages/bb/10/44230dd6bf3563b8f227dbf344c908d412ad2ff48066476672f3a72e174e/wheel-0.33.4-py2.py3-none-any.whl Collecting Cython Using cached https://files.pythonhosted.org/packages/ba/08/4f0d09d63b713955f9c6937923f1b1432331f468912b65824b19b9d82d19/Cython-0.29.13-cp37-cp37m-win32.whl Collecting cymem<2.1.0,>=2.0.2 Using cached https://files.pythonhosted.org/packages/eb/cb/4ff546a491f764f67284572d25c57927e3f17103adf979bc99d90128f3eb/cymem-2.0.2-cp37-cp37m-win32.whl Collecting preshed<2.1.0,>=2.0.1 Using cached https://files.pythonhosted.org/packages/00/52/ef641ebb40e287b95e9742e7f3120dca0350d92b3d0ef050e5133acf8931/preshed-2.0.1-cp37-cp37m-win32.whl Collecting murmurhash<1.1.0,>=0.28.0 Using cached https://files.pythonhosted.org/packages/22/e9/411be1845f1ac07ae3bc40a4b19ba401819baed4fa63b4f5ef28b2300eb4/murmurhash-1.0.2.tar.gz Collecting thinc<7.1.0,>=7.0.8 Using cached https://files.pythonhosted.org/packages/92/39/ea2a3d5b87fd52fc865fd1ceb7b91dca1f85e227d53e7a086d260f6bcb93/thinc-7.0.8.tar.gz Collecting blis<0.3.0,>=0.2.1 (from thinc<7.1.0,>=7.0.8) Using cached https://files.pythonhosted.org/packages/59/9e/84a83616cbe5daa94909da38b780e93bf566dc2113c3dc35d7b4cad52f63/blis-0.2.4.tar.gz Collecting wasabi<1.1.0,>=0.0.9 (from thinc<7.1.0,>=7.0.8) Using cached https://files.pythonhosted.org/packages/f4/c1/d76ccdd12c716be79162d934fe7de4ac8a318b9302864716dde940641a79/wasabi-0.2.2-py3-none-any.whl Collecting srsly<1.1.0,>=0.0.6 (from thinc<7.1.0,>=7.0.8) Using cached https://files.pythonhosted.org/packages/84/59/6f276ab6d74888eed0e999d617101ed7357fc1ee073e9aac92d53260bd23/srsly-0.0.7.tar.gz Collecting numpy>=1.7.0 (from thinc<7.1.0,>=7.0.8) Using cached https://files.pythonhosted.org/packages/f9/3f/d75fc983cc420b2acb5fae446b950e2dc9e5395a79fa76859d2528352d2c/numpy-1.17.0-cp37-cp37m-win32.whl Collecting plac<1.0.0,>=0.9.6 … -
Mixing Django models and SQLAlchemy in model fields: can it be done?
I have several models, with ids defined like this: id = models.UUIDField(primary_key=True, default=uuid.uuid4, blank=True, editable=False) I want to be able to use the SQLAlchemy server_default option, I tried this way: id = Column( UUID(as_uuid=True), primary_key=True, server_default=sqlalchemy.text("uuid_generate_v4()"), blank=True, editable=False, ) but this returned the error NameError: name 'sqlalchemy' is not defined (despite sqlalchemy being imported and installed with Pip). Is there a clean/correct way of making use of this function in a Django model? -
Is there a way to set two variables as unique together?
I'm creating an application that i have username and nickname for the same person: username = models.CharField( max_length=40, unique=True, db_index=True) nickname = models.CharField(max_length=100, unique=True) But i need to define this two variables as unique like: If an user A has: username: bird nickname: dog and an user B try to make registration like: username: dog nickname: butterfly I will not accept because dog is already taken. Or if an user try to put nickname as same as username. I'm thinking to create a registration view to make this validation manually. But is there a way to make this in the declaration? -
Adding security questions to signup page created using django
I am creating a signup page using Django, I need to add some security questions so the user can choose which one they wanna use and save the answer of that question. What am I supposed to do? -
Django values() function. What are *fields?
As documentation says: values(*fields, **expressions) The values() method takes optional positional arguments, *fields, which specify field names to which the SELECT should be limited. If you specify the fields, each dictionary will contain only the field keys/values for the fields you specify. If you don’t specify the fields, each dictionary will contain a key and value for every field in the database table. But what is *fields is not clear to me. Supposing a model named MyModel with just three fields: id, name and phone. This works: values = MyModel.objects.all().values('id', 'name', 'phone') This doesn't work: def get_values(fields): return MyModel.objects.all().values(fields) fields = ['id', 'name', 'phone'] values = get_values(fields) Because it raises: AttributeError: 'list' object has no attribute 'split' But I don't understand why. I mean, it is clear that a list, tuple or set don't have a split method but, is not a list (a tuple, actually) what I am passing in the first example? The second code snippet fails even with a tuple or a set, and this is obvious, because they don't have a split method too. So what type am I passing in first example? There's something about python/django behavior that I'm not missing. Thank you. -
Circular imports django
I have wrote this code in my models.py file. As you see the code, I have a class called File and also I have imported in models.py the same class. Now it gives me this error while migration: Cannot import name "File" from 'uploadapp.models' I understand it's the error for circular (recursive) import. But how can I solve this? from django.db import models from .models import File class File(models.Model): file = models.FileField(blank=False, null=False) def __str__(self): return self.file.name -
Updating source of video tag with ajax
I have an html page where there is a calendar, a video tag and a button. When a user clicks on a button, based on the timestamp the path of the video file from Django is sent and is received by an ajax call. When the page is opened for the first time or is refreshed and the date and time is selected and then the button is pressed the video corresponding to that date and time gets displayed on the page and can be played. However when I change the date and time, the same video file which was opened previously gets displayed on the page, however the path of the video file which is being returned from the django is according to the new date and time. Kindly help me here. HTML code <div style="margin-left: 10%"> <button type="submit" class="btn btn-secondary btn-lg" id="recorded" name="btn_submit" value="Play Recorded Videos" onclick="record()" >Play Recorded Videos</button> </div> <div id="videoDiv" class="container" style="margin-left: 10%; margin-top: 1%; align-items: center; display: none "> <video id='storedVideoId' width='100%' controls > </video> <br><br> </div> Javascript code <script type="text/javascript"> var dateNow = new Date(); dateNow.setDate(dateNow.getDate()); var timer $(function () { $('#datetimepicker1').datetimepicker({ defaultDate:dateNow }); }); function getDataFromServer() { getVideoFile() } function getSelectedDate() { … -
How to manage static files in Python, which are in separate app in Django 2+?
Here is my project directory: So I want to create home.html file where to load style.css file. How I load style.css file in home.html file: {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'style.css' %}"> Which returns me: <link rel="stylesheet" type="text/css" href="/static/style.css"> Which is not the right path. Based on documentation I tried with: {% load static %} <img src="{% static "my_app/example.jpg" %}" alt="My image"> in my case: {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'core/style.css' %}"> But it returns me wrong path again: <link rel="stylesheet" type="text/css" href="/static/core/style.css"> Where am I wrong ?