Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
jQuery get request with json body to a REST api
I'm building a website with django and django_rest_framework. I tested the rest api with httpie. But when I try to do the same call with jQuery I get an error. jquery.min.js:4 GET http://localhost:8000/api/recentposts/?{%22last_id%22:1650} 500 (Internal Server Error) The call with httpie is the following http get localhost:8000/api/recentposts/ last_id=1650 or http get localhost:8000/api/recentposts/ < recent.json ---------------------------- content of recent.json { "last_id": 1650 } and I get the right results. while with jquery I tried $.ajax({ type: 'GET', url: 'http://localhost:8000/api/recentposts/', contentType: 'application/json', dataType: 'json', processData: false, data: JSON.stringify({ last_id : 1650 }), success: function(resp){ console.log(resp); } }); Is there something wrong with the call? I've tried with .get instead of .ajax, and a lot of different ways to pass the json but I haven't solved anything yet. by the way this is the view that is called class RecentPostViewSet(viewsets.ReadOnlyModelViewSet): ''' ViewSet that displays recent posts after it post id It needs a JSON file like the following { "last_id" : int } ''' queryset = Post.objects.all() serializer_class = PostSerializer def list(self, request): recent_feed = Post.objects.filter(hidden=False).order_by('-pub_date').filter(pk__gt=request.data['last_id']) log.warning("incoming request") log.warning(dir(request)) log.warning(request.data) log.warning(request.query_params) serializer = self.get_serializer(recent_feed, many=True) return Response(serializer.data) Is this beacause jQuery get call is not capable to do a get request with a … -
User Profile not saving profiles and throwing exceptions
I'm still new to Django and I've been reading through all the previous posts on User Profile and have tried adopting the solutions found. In doing so, I have been unable to actually save profiles to the database through the shell. Instead I'm receiving 'IntegrityError'. My Profile Model: class Profile(User): user = models.OneToOneField(User, on_delete=models.CASCADE) chunks = models.ManyToManyField(Chunk) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() I have changed my settings to authorise the profile module by including the following in settings: AUTH_PROFILE_MODULE = 'pomodoro.Profile' My problems occur when trying to create profiles for users. In the shell I have tried this but get an auth error: from django.contrib.auth.models import User from pomodoro.models import Profile admin_profile = Profile() admin = User.objects.get(pk=1) admin_profile.user = admin admin_profile.save() Traceback (most recent call last): File "C:\Python35\lib\site-packages\django\db\backends\utils.py", line 64, in execute return self.cursor.execute(sql, params) File "C:\Python35\lib\site-packages\django\db\backends\sqlite3\base.py", line 337, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: UNIQUE constraint failed: auth_user.username The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Python35\lib\site-packages\django\contrib\auth\base_user.py", line 80, in save super(AbstractBaseUser, self).save(*args, **kwargs) File "C:\Python35\lib\site-packages\django\db\models\base.py", line 796, in save force_update=force_update, … -
Django Haystack - Autucomplete not working properly
I am using Django 1.8.4 along with Python 2.7.12. I use a Whoosh (2.7.4) backend for Haystack. I am trying to implement autocomplete on searches. Here is my model.py : class Event(models.Model): title = models.CharField(max_length=200, null=True, blank=False) description = models.TextField(blank=False) date_event = models.DateTimeField(null=True, blank=False) search_indexes.py : class EventIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.NgramField(document=True, use_template=True) title = indexes.NgramField(model_attr='title') def get_model(self): return Event def index_queryset(self, using=None): """Used when the entire index for model is updated.""" return self.get_model().objects.all() In my views.py : def search(request): all_results = False search = None if request.method == 'GET': search = request.GET.get('q').strip() all_results = SearchQuerySet().filter( content = search ).order_by('id')[:50] return render(request, 'search/search.html', {'results' : all_results, 'search' : search}) And finally in my search.html : {% block content %} {% for result in results %} {{ result.object.title }} {% endfor %} {% endblock %} At this point, I pretty much followed all the instructions from the documentation and what I have found on the Internet. Though the system doesn't work because I am getting no result whenever I search for something even if I put a complete title of one of the event in the database as a search query. -
using python @poperty in django models suddenly not found
I started my application to day, and was frustrated to see that a Django model, i had which have the following definition stopped recognizing one of the properties with @property attribute. it's from django-coupons @python_2_unicode_compatible class Coupon(models.Model): value = models.IntegerField(_("Value"), help_text=_("Arbitrary coupon value")) criteria = models.IntegerField( _("Criteria"), blank=True, null=True, help_text=_("Arbitrary coupon criteria amount that must be met for the coupon to be valid")) code = models.CharField( _("Code"), max_length=30, unique=True, blank=True, help_text=_("Leaving this field empty will generate a random code.")) type = models.CharField(_("Type"), max_length=20, choices=COUPON_TYPES) user_limit = models.PositiveIntegerField(_("User limit"), default=1) redeem_limit = models.PositiveIntegerField( _("Redeem limit"), default=None, blank=True, null=True, help_text=_("Leave empty for coupons that have no redeem limit")) redeem_count = models.IntegerField(_("Redeem Count"), default=0) created_at = models.DateTimeField(_("Created at"), auto_now_add=True) valid_until = models.DateTimeField( _("Valid until"), blank=True, null=True, help_text=_("Leave empty for coupons that never expire")) campaign = models.ForeignKey('Campaign', verbose_name=_("Campaign"), blank=True, null=True, related_name='coupons') objects = CouponManager() class Meta: ordering = ['created_at'] verbose_name = _("Coupon") verbose_name_plural = _("Coupons") def __str__(self): return self.code def save(self, *args, **kwargs): if not self.code: self.code = Coupon.generate_code() super(Coupon, self).save(*args, **kwargs) def expired(self): return self.valid_until is not None and self.valid_until < timezone.now() @property def is_redeemed(self): """ Returns true is a coupon is redeemed (completely for all users) otherwise returns false. """ return self.users.filter( … -
HTML form django fail on save model
I'm working as newbie in Django making a callcenter App and i'm having some problems when i'm trying to store form data passed by POST to the view. The data is passing ok from the form template to the view function, but when i try to store, it fails. Here is the code, and many thanks in advance: views.py: def addIncidence(request): incidenceNew = Incidencia messageNew = Mensaje try: incidenceNew.user_id = request.POST.get('id_user') incidenceNew.nom_user = request.POST.get('username') incidenceNew.fecha_incidencia = request.POST.get('fecha_inci') incidenceNew.rango_incidencia = request.POST.get('rango_inci') messageNew.incidence_id = request.POST.get('new_inci_id') messageNew.cadena_mensaje = request.POST.get('mensaje_inci') incidenceNew.save() return HttpResponse("All right") except: return HttpResponse("Failed) models.py: class Incidencia(models.Model): user = models.ForeignKey(User) nom_user = models.CharField(max_length=100) fecha_incidencia = models.DateTimeField('incidence date') detalles_admin = models.CharField(max_length=300) rango_incidencia = models.CharField(max_length=3) estado_incidencia = models.CharField(max_length=20) class Mensaje(models.Model): incidence = models.ForeignKey(Incidencia, on_delete=models.CASCADE) cadena_mensaje = models.CharField(max_length=300) newIncidence.html: <form name="NewIncidenceForm" action="new/" method="post"> {% csrf_token %} </br> id_user_fk_inci <input type="text" id="id_user" name="id_user" value="{{ user.id }}"> </br> nom_user <input type="text" id="username" name="username" value="{{ user.username }}"> </br> fk_message_inci_id <input type="text" id="new_inci_id" name="new_inci_id" value="{{ totalIncidences }}"> </br> fecha_inci <input type="text" id="fecha_inci" name="fecha_inci" value="{{ currentDate }}"> </br> rango <input type="text" id="rango_inci" name="rango_inci" placeholder="A, M o B"> </br> mensaje <input type="text" id="mensaje_inci" name="mensaje_inci" placeholder="Put your message here"> </br> </br> <button type="submit">Registrar incidencia</button> </form> -
angular2: origin 'http://localhost:3000' is therefore not allowed access
I have a django backend and I have enabled Cross origin requests as follows: INSTALLED_APPS = [ .. 'corsheaders', ] MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'corsheaders.middleware.CorsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True I haven't implemented any authentication. I simply am trying to hit an API endpoint and trying to fetch data on my Angular2 frontend. I have implemented a session based cart in Django backend which stores my products (https://github.com/lazybird/django-carton). When I hit http://127.0.0.1:8000/api/shopping-cart/show/ through my browsable api it gives me {"1":{"product_pk":1,"price":"23000.00000","quantity":3},"2":{"product_pk":2,"price":"34000.00000","quantity":7},"4":{"product_pk":4,"price":"450.00000","quantity":1}} However when I try to hit the same url from my Angular2 service: it throws me error: XMLHttpRequest cannot load http://127.0.0.1:8000/api/shopping-cart/show/. A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'http://localhost:3000' is therefore not allowed access. The credentials mode of an XMLHttpRequest is controlled by the withCredentials attribute. My service call is as follows: private myUrl: string = 'http://127.0.0.1:8000/api/shopping-cart/' showCart(){ return this.http.get(this.myUrl + 'show' + '/', {withCredentials:true}) .toPromise() .then(response => response.json()) } Note: If I remove {withCredentials:true} then it does not send sessionid or csrftoken and returns {} but the error vanishes. What am I doing wrong? -
Use external python libraries on Pyramid
Can I use any external libraries that are developed for python on Pyramid? I mean is it the 'normal python' to which I can import external libraries as I do with the standard python downloaded from python.org What is the situation for Django and Flask and Bottle? My intention is to create backend for a mobile app. I want to do it specifically in Python because I need to learn python. The app is a native android app. Therefore the there is no need to use response with nice html code. I just want Django/Flask/Pyramid to direct http request to relevant python functions. Everything else including user auth, database is handled by my code I write. Is there a better more simpler way to map http request/responses with the relevant functions without using these 3 platforms? In case I use one of these can I still use my own libraries? -
django JWT asking for username/password
I can successfully connect via CURL using the example posted in their documentation here: http://getblimp.github.io/django-rest-framework-jwt/#usage The problem comes from trying to use Postman. I set the authorization to Basic and put in my username/password and I get a 400 response with the following json: { "username": [ "This field is required." ], "password": [ "This field is required." ] } I'm not sure if I'm missing something obvious. -
ERR_TOO_MANY_REDIRECTS after adding SSL certificate to djnago app in Nginx
Getting error ERR_TOO_MANY_REDIRECTS Access my django website using https://example.com , django app is hosted in nginx server Nginx Config file: upstream example.com { server unix:/home/www/example/env/run/gunicorn.sock fail_timeout=0; } server { listen 443 ssl; rewrite ^/(.*) https://www.example.com/$1 permanent; server_name example.com www.example.com *.example.com; ssl_certificate /root/sslkeys/example.com.chained.crt; ssl_certificate_key /root/sslkeys/example.key; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_prefer_server_ciphers on; ssl_ciphers ''; client_max_body_size 4G; access_log /home/www/example/logs/nginx-access.log; error_log //home/www/example/logs/nginx-error.log; location /static/ { alias /home/www/example/xyz/static_content/; } location /uploads { alias /home/www/example/xyz/uploads; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; # <- proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://example.com; break; } } # Error pages error_page 500 502 503 504 /500.html; location = /500.html { root /home/www/example/xyz/templates/; } } Django Setting.py contains : SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True on removing rewrite ^/(.*) https://www.example.com/$1 permanent; It throws 404. -
PYTHON/DJANGO: "SUser.user" must be a "User" instance
I have a problem with adding new custom user to the database. I know thare's some threads about it on the internet but I couldn't find solution for my problem. After hitting "Submit" button in registration page which template is here: {% extends 'strona/Main.html' %} {% block body %} < form action="" method="post" enctype="multipart/form-data" > {% csrf_token %} {% for field in form %} {{ field.label_tag }} < /br > {{ field }} < /br > < /br > {% endfor %} < button type="submit" class="btn btn-success">Submit</button > < /form > {% endblock %} it keeps saying that: "Cannot assign "< SimpleLazyObject: < django.contrib.auth.models.AnonymousUser object at 0x038B5A70 >>": "SUser.user" must be a "User" instance." Source Codes: VIEWS.PY class RegPanelView(View): panel = RegPanel template_name = 'strona/RegistrationTemp.html' registration = None def get(self, request): form = self.panel(None) return render(request, self.template_name, {'form': form}) def post(self, request): # form = self.panel(data=request.POST) form = self.panel(request.POST) if form.is_valid(): # user = form.save(commit=False) # username = form.cleaned_data['username'] password1 = form.cleaned_data['password1'] password2 = form.cleaned_data['password2'] if password1 == password2: newuser = form.save(commit=False) newuser.user = request.user newuser.save() return redirect('strona:index') return render(request, self.template_name, {'form': form}) MODELS.PY class SUser(models.Model): # User = user_model() user = models.OneToOneField(User, on_delete=models.CASCADE) username = models.CharField(max_length=200) # last_login = … -
Reading cookie expiration date in django
When I run request.COOKIES.get(key) I get the cookie value. How do I get the cookie expiration date? (get_signed_cookie() throws me *** BadSignature: No ":" found in value error) -
Django & Cube OLAP Integration
I am working on an ERP solution. i would like to know, how can we integrate Python Cube (or any other OLAP Cube) with Django? As in what is the procedure? How would my models.py file change? If Cube has to be a separate structure, how and where does it lie? Thank You -
ValueError: path is on mount 'C:', start on mount 'F:' while django migrations in windows
I am trying to run the following command python manage.py makemigrations But, getting the error ValueError: path is on mount 'C:', start on mount 'F:' -
Setting up Django(Database) in Eclipse with PyMySQL insteand of MySQLdb ---Python 3.5.2
please how do is set up my Django database in Eclipse(oxygen) with PyMySQL instead of MySQLdb. I have installed Python 3.5.2. -
run a code every 5 minutes when django server is running
I have a django project and inside I have an app. Inside this app I created a management folder, inside this one I create a commands folder, and inside the last one I put my script with the init.py file too. My question is: how can I do to autorun that code every X minutes once the server is running to don't worry about execute the script myself. -
Why is django displaying white lite on top of the page when using bootstrap
when I render my html file, I want to display on top of the page my header, but django displays a white line on top. This is how it looks like: I want all, from top of the page to be orange, and not to have that white line on top of the page. How to do that? This is my html code: {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <title>{% block title %}{% endblock %}</title> <!-- jQuery library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <!-- Latest compiled JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <!-- Custom Fonts --> <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css" /> <link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'> <link href="{% static "css/blog.css" %}" rel="stylesheet" type="text/css" /> <!-- Theme CSS --> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> </head> <body><!-- Navigation --> <!-- Page Header --> <!-- Set your background image for this header on the line below. --> <div class="page-header"> <h1>My First Bootstrap Page</h1> <p>Resize this responsive page to see the effect!</p> … -
Cannot get models thats referencing another model aas foriegn key
What i want to do is get all userimages that use a particular foriegnkey I'm doing this by User.objects.get(pk=1).profile.friends.all().values_list('userimages') but then this is what i get. What I find strange is that uservideo model is very similar to userimages and yet userimages cannot be resolved. FieldError: Cannot resolve keyword 'userimages' into field. Choices are: about_me, display_image, friends, id, nick_name, owner, owner_id, user, user_id, uservideo models class UserImages(models.Model): owner = models.ForeignKey('auth.User', related_name='UserImages') user=models.ForeignKey(Profile,related_name="profile_owner") # highlighted = models.TextField(default=None,blank=True,null=True) image=models.ImageField() pub_date=models.DateTimeField(default=now) class UserVideo(models.Model): owner = models.ForeignKey('auth.User', related_name='UserVideo') # highlighted = models.TextField(default=None,blank=True,null=True) user=models.ForeignKey(Profile) image=models.FileField() pub_date=models.DateTimeField(default=now) -
search from database using ajax in django
I am working on a django project and making a dashboard in which I am trying to add a search bar in which on typing I will get a list of all the relevant searches. Views.py def get_user_name(request): if request.is_ajax(): results = [] context = RequestContext(request) if request.method == 'GET': q = request.GET.get('search_text') results = User.objects.filter(user_name__contains = q) context = { 'data': [] } for record in results: data = { 'id': record.id, 'code': record.code, 'name': record.name, 'manager': record.manager.email, 'type': record.type.upper(), 'status': record.current_state.display_name, } return render(request, 'listinguser.html', context) listinguser.html {% extends "base.html" %} {% block title %}Users Listing Page{% endblock %} {% block body %} <div class='page_header'> <div class="ui-widget"> <p align="right"> <input type="text" placeholder="Type user name" id="user_name" name="term"> </p> </div> <script> $("#user_name").keypress(function(){ $.ajax({ type: "GET", url: "{% url "user_name" %}", dataType: "json", success: function(response) { //success code }, error: function(rs, e) alert(rs.responseText); } }); }) </script> </div> <div class="col-md-6" style="width:100%"> <table id="data-table" class="table table-striped table-bordered"> <thead> <tr> <th style="width: 5%;">#</th> <th style="width: 8%;">Id</th> <th style="width: 15%;">Name</th> <th style="width: 15%;">Status</th> </tr> </thead> <tbody> {% for record in data %} <tr> <td>{{ forloop.counter}}</td> <td>{{ record.user_id }}</td> <td><a href="/user/{{record.user_id}}/">{{ record.user_name }}</a> <br>({{ record.user_type }})</td> <td>{{ record.user_status }}</td> {% endfor %} </tbody> </table> {% … -
Using Django Views and Forms without a Models based Database
I am kind of new to Django (been writing Python for a while now) and I was wondering if it is at all possible to use the Views and Forms framework in Django without having the need for a database or the use of Models. The content is dynamic, and gets populated into a dictionary each time the user launches the website. So I would like to leverage the Django Views and Forms but passing through the details from the dictionary and not from a Model Class (Database) I hope I have explained myself correctly. -
How to call envdir before running fastcgi when deploying django project?
So here's a snippet of my project.fcgi sys.path.insert(0, "/var/www/project") os.environ['DJANGO_SETTINGS_MODULE'] = "project.settings.prod" from django.core.servers.fastcgi import runfastcgi runfastcgi(method="prefork", daemonize="true", host="127.0.0.1", port="3033") In my project.settings.prod I have variables that get value from os.environ like this: SECRET_KEY = os.environ["SECRET_KEY"] How do i call envdir to first setup my environment variables before running project.fcgi? Thanks in advance! -
Json parsing django rest framework
I want to parse incoming POST data in django views.py file POST data: { "number" : "17386372", "data" : ["banana","apple","grapes" ] } Here is how I tried to read above incoming data with request views.py class Fruits(APIView): def post(self, request, format=None): if request.method == "POST": number = request.data.get('number') fruits_data = json.loads(request.body) if number not in [None, '', ' ']: try: response = {"return": "OK","data":fruits_data['data']} return Response(response) except: return Response({"return": "NOT OK"}) else: return Response({"return": "NOT OK"}) else: return Response({"return": "NOT OK"}) ERROR: You cannot access body after reading from request's data stream -
Error during starting Gunicorn: "Worker failed to boot"
I'm trying to deploy a Django project to DigitalOcean with Gunicorn and Nginx. When I try to start Gunicorn I'm getting the error: "Worker failed to boot" cd /opt/blog/src && /opt/blog/env/bin/gunicorn core.wsgi:application --bind 0.0.0.0:8000 The error: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> This is my project structure: /opt/blog/ env/ src/ core/ wsgi.py In my settings.py: DEBUG=False ALLOWED_HOSTS = ['*'] /etc/init/gunicorn.conf: description "Gunicorn application server handling blog." start on runlevel [2345] stop on runlevel [!2345] respawn setuid nobody setgid nogroup chdir /opt/blog/src exec /opt/blog/env/bin/gunicorn --workers 3 --bind 0.0.0.0:8000 core.wsgi:application /etc/nginx/sites-available/umutcoskun.com: server { server_name umutcoskun.com www.umutcoskun.com; access_log off; location /static/ { alias /opt/blog/static/; } location / { proxy_pass http://0.0.0.0:8000; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Host $host; proxy_set_header X-Forwarded-Host $proxy_add_x_forwarded_for; add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"'; } } Where am I making mistakes? -
Get latest record from a django foreign key related models using annotations
I am new to Django and I would like to create a dynamic field using annotate. The field is calculated like follows: market_cap = issued_shares * latest_closing_price The question is how do I get the latest closing price. I have tried the below code: companies= Company.objects.annotate(latest_price=Max('price__price_date')) Which gives me the latest price_date. Is there a way to get the latest closing_price associated with the latest price_date so that I can do the following: companies = Company.objects.annotate( market_cap=ExpressionWrapper( F('issued_shares') * Max('price__price_date'), output_field=DecimalField(max_digits=20, decimal_places=2)) The above code is not right because we are multiplying int and date field. I would like to multiply issued_shares(integer) with the latest closing_price(decimal) to get the current market capitalization of a company. Any ideas are welcome. Below are my models. The model Price has a lot of records showing the price of each company at a particular date. The column ticker provides the relationship. models.py class Company(models.Model): ticker = models.CharField(primary_key=True, max_length=32) name = models.CharField(max_length=255) sector = models.CharField(max_length=255) currency = models.CharField(max_length=10) isin_code = models.CharField(max_length=255) issued_shares = models.BigIntegerField() def __unicode__(self): return u"%s %s %s %d" % ( self.ticker, self.name, self.sector, self.issued_shares) class Price(models.Model): company = models.ForeignKey( Company, on_delete=models.CASCADE, related_name='price') price_date = models.DateField() closing_price = models.DecimalField(max_digits=8, decimal_places=2) opening_price = models.DecimalField(max_digits=8, … -
pip install pyscopg2 error: cdefs.h not found
On Debian 8, i'm trying to setup a django 1.10 project. Installing requirements I have a problem. $ pip install psycopg2 /usr/include/features.h:374:25: fatal error: sys/cdefs.h: File or directory not found I search in which package cdefs.h is: $ dpkg -S cdefs.h libc6-dev:amd64: /usr/include/x86_64-linux-gnu/sys/cdefs.h I checked if I have installed it and yes, it's installed. What is strange is that in the same server I have another django project and it's working! What i'm forgetting?? -
Run a script which is in a django app under management folder in command folder
I have a django project and inside I have an app. Inside this app I created a management folder, inside this one I create a commands folder, and inside the last one I put my script with the init.py file too. My question is how I can run the script, because if I'm in the django project folder (where is manage.py file) and I execute the line: python manage.py myscript.py the terminal is displaying this: Unknown command: 'myscript.py'