Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problem in install django-cors-middleware
I installed django-cors-headers 3.5.0 and I got this error when I try to run the project. this is my configurations: requirement.txt: Django==2.2.0 djangorestframework==3.9.1,<3.10.0 psycopg2>=2.7.5,<2.8.0 Pillow>=5.3.0,<5.4.0 django-jalali-date==0.3.1 django-cors-headers==3.5.0 settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'corsheaders', #<------There it is 'core', 'user', 'land', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', # its middleware 'django.middleware.security.SecurityMiddleware', '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', ] CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = ( 'http://localhost:3000', ) docker-compose: version: "3" services: app: build: context: . ports: - "8000:8000" volumes: - ./app:/app command: > sh -c "python manage.py wait_for_db && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" environment: - DB_HOST=db - DB_NAME=app - DB_USER=postgres - DB_PASS=supersecretpassword depends_on: - db container_name: land_api db: image: postgres:10-alpine environment: - POSTGRES_DB=app - POSTGRES_USER=postgres - POSTGRES_PASSWORD=supersecretpassword container_name: land_db but when I run "docker-compose up" i get this error: ModuleNotFoundError: No module named 'corsheaders' I try to add the installation in dockerFile but it didn't too. Is it really bug? or I miss something? -
TypeError in django while creating model instances
I have a model onlinebooking and I am trying to save the data the user inputs. However I am getting the error TypeError at /onlinebooking/ onlinebooking() got an unexpected keyword argument 'name'. I get this error after clicking the register button. Here is my model: class onlinebooking(models.Model): name = models.CharField(max_length=30) email = models.CharField(max_length=30) phone_number = models.IntegerField() room_type = models.CharField(max_length=10) booking_date = models.DateField() views.py from django.shortcuts import render,redirect from .models import onlinebooking def onlinebooking(request): if request.method == "POST": name = request.POST['Name'] email = request.POST['email'] phone_number = request.POST['phone_no'] room_type = request.POST['room_type'] booking_date = request.POST['booking_date'] online = onlinebooking(name=name,email=email,phone_number=phone_number,room_type=room_type,booking_date=booking_date) online.save() return redirect('/') else: return render(request,'hotel/onlinebooking.html') form used: <form action="/onlinebooking/" method="post"> {% csrf_token %} <div class="text-primary"> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputEmail4">Name</label> <input type="text" class="form-control" id="inputEmail4" name="Name" required> </div> <!-- <div class="form-group col-md-6"> <label for="lastname">Last name</label> <input type="text" class="form-control" id="lastname" name="lastname" required> </div> --> <div class="form-group col-md-6"> <label for="inputPassword4">Email</label> <input type="text" class="form-control" id="inputPassword4" name="email" required> </div> <div class="form-group col-md-6"> <label for="inputPassword4">Phone no</label> <input type="text" class="form-control" id="inputPassword4" name="phone_no" required> </div> <div class="form-group col-md-6"> <label for="inputState">Room Type</label> <select id="inputState" class="form-control" name="room_type"> <option selected>Standard</option> <option>Delux</option> <option>Premium</option> </select> </div> <div class="form-group col-md-6"> <label for="bookingtime">Booking Date</label> <input type="date" id="bookingtime" name="booking_date" required> </div> <div class="text-center"> <input type="submit" value="Register" name="submit-emp" class="btn … -
I am getting failed on gunicorn status on aws ec2 instance
I installed gunicorn on my aws ec2 instance and start the gunicorn but when I checked the status of gunicorn ubuntu@ip-address:~$ sudo systemctl status gunicorn ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Sun 2020-11-22 07:40:01 UTC; 2s ago Process: 25002 ExecStart=/webapps/myapps/bin/gunicorn --access-logfile - --workers 3 --preload --bind unix:/webapps/myapps/bin/siteapp.sock siteapp.wsgi:application (code=exited, status=1/FAILURE) Main PID: 25002 (code=exited, status=1/FAILURE) Nov 22 07:40:01 ip-address gunicorn[25002]: File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed Nov 22 07:40:01 ip-address gunicorn[25002]: File "/webapps/myapps/myapps/settings.py", line 244, in <module> Nov 22 07:40:01 ip-address gunicorn[25002]: 'propagate': False, Nov 22 07:40:01 ip-address gunicorn[25002]: File "/usr/local/lib/python3.6/logging/config.py", line 795, in dictConfig Nov 22 07:40:01 ip-address gunicorn[25002]: dictConfigClass(config).configure() Nov 22 07:40:01 ip-address gunicorn[25002]: File "/usr/local/lib/python3.6/logging/config.py", line 566, in configure Nov 22 07:40:01 ip-address gunicorn[25002]: '%r: %s' % (name, e)) Nov 22 07:40:01 ip-address gunicorn[25002]: ValueError: Unable to configure handler 'logfile': [Errno 13] Permission denied: '/webapps/myapps/logs/logfile' Nov 22 07:40:01 ip-address systemd[1]: gunicorn.service: Main process exited, code=exited, status=1/FAILURE Nov 22 07:40:01 ip-address systemd[1]: gunicorn.service: Failed with result 'exit-code'. How can we solve it? -
lookup_field Return None In Django get_queryset
I have a class extend with GenericAPIView , I Can access to the lookup_field in my functions, but I can't use it in the queryset function. serializer_class = ShopItemSerializer permission_classes = [AllowAny] lookup_field = 'phone_number' def get_queryset(self): print(self.lookup_url_kwarg) # It Return None print(self.lookup_field) # It Return 'phone_number' shop_items = ShopItem.objects.filter(Q(seller_id__user_id__phone_number=self.lookup_field)) return shop_items def get(self, request, phone_number): result = self.list(request, phone_number) print(result.status_code) return result How Can I Access to the lookup_field in get_queryset ? -
Django admin has no design in live server
I uploaded my whole site in my live server after uploading django admin is not showing any design before uploading it was fine but after upload in it got like this :- -
"detail": "JSON parse error - Expecting value: line 1 column 1 (char 0)" django rest framework
when I make post request via XMLHttpRequest it work very well but, when I make a get request in the django API view http://127.0.0.1:8000/create/ and I write a new text in the text box I got an error "detail": "JSON parse error - Expecting value: line 1 column 1 (char 0)" here are my files code. serlizers.py the app is just like tweet app where I'm following this course from rest_framework import serializers from .models import Tweet class TweetActionsSerlizer(serializers.Serializer): id = serializers.IntegerField() action = serializers.CharField() content = serializers.CharField(allow_blank=True, required=False) def validate_action(self, value): # lower = lower case letter. # strip = drop spaces for example "like ".strip() = "like" value = value.lower().strip() if not value in ['like', 'unlike', 'retweet']: raise serializers.ValidationError("this is not avalid action") return value class CreateTweeSerializers(serializers.ModelSerializer): class Meta: model = Tweet fields = ['id', 'content', 'like'] # def get_likes(self, obj): # return obj.like.count() # this convert the array of users ids wholiekd to the number of likes def validate_content(self, value): if len(value) > 200: raise serializers.ValidationError("This Tweet is too long") return value class TweeSerializers(serializers.ModelSerializer): # like = serializers.SerializerMethodField(read_only=True) # if the is no is_retweet @property function in models you will nedd this line. # is_retweet = serializers.SerializerMethodField(read_only=True) … -
GET http://127.0.0.1:9000/static/lib/slick/slick.css net::ERR_ABORTED 404 (Not Found)
https://github.com/vaishnavkm/Shopping_site.git master can u help me what is wrong -
Download csv file from api with axios in ReactJS
My Django API response with a CSV file (content-type: CSV/text). how can I download this? I am using axios to fetch the data -
Django: How to Update Multiple Objects using forms
I'm fairly new to Django and web design, just a quick question. Is there a way in my views to generate a single form with all my Game objects I have already created and update both the attributes in the game class and possibly the team class as well as they are connected through the foreign keys? I've seen a lot about forms, model forms, and formsets everywhere online, but they seem to all update a single object. Ideally what I would like to be able to have is one page with a form or a bunch of forms that when I input the scores of the games that happen that day it will update the game objects referring to the games that day as well as the corresponding teams objects. Not sure if this is possible or not. These are my models below: class Game(models.Model): teamone = models.ForeignKey(Team, on_delete = models.SET_NULL, null = True, related_name = 'teamone') teamtwo = models.ForeignKey(Team, on_delete = models.SET_NULL, null = True, related_name = 'teamtwo') teamonegoals = models.IntegerField(null = True) teamtwogoals = models.IntegerField(null = True) gamedate = models.DateField(null = True) class Team(models.Model): position = models.IntegerField(null = True) name = models.CharField(max_length = 200, null = True) … -
Why do we need to deploy Django with gunicorn?
We can simply start a Django server1 with python manage.py runserver 8080, so why do we need to deploy Django server2 like gunicorn myproject.wsgi? I googled about wsgi, it says that wsgi connects between nginx and Django, but what confused me is that we can make http requests(like with postman) to server1 and everything works well. So what's the difference? -
my third-party package makemigrations not working
I have created a third-party package. when I add the package to a new project and run makemigrations command, Django can't find new models and says No changes detected but when I mention the new app [makemigrations package_name] it works. what should I do it works by simple makemigrations? -
Django SECRET_KEY on github
What is the danger of placing a project on Django on github with an open Secret_key and how can it be encrypted, not making the project private? thanks -
data is not inserting
I am trying to insert data using django forms API but it not working whenever I try to insert data it doesn't insert into the database Here is my VIews.py def create_product(request): if request.method == 'POST': form = CreateProductForm(request.POST) if form.is_valid(): p_name = form.cleaned_data['name'] p_cat = form.cleaned_data['category'] p_brand = form.cleaned_data['brand'] p_price = form.cleaned_data['price'] p_image = form.cleaned_data['image'] p_desc = form.cleaned_data['desc'] save_product = Product(name=p_name, category=p_cat, brand=p_brand, price=p_price, image=p_image, desc=p_desc) save_product.save() else: return HttpResponse("Failed To Insert Data!") else: form = CreateProductForm() params = {'form':form} return render(request, 'adminpanel/createPro.html', params) Here is my index.html: <form class="col-sm-9 m-6" action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{form.as_p}} <input type="submit" value="Add Product"> </form> Here is my forms.py from django import forms from django.core import validators from .models import Product class CreateProductForm(forms.ModelForm): class Meta: model = Product fields = ['name', 'category', 'brand', 'image', 'price', 'desc'] Here is my Product Model class Product(models.Model): name = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE, default='UNCATEGORIZED') brand = models.ForeignKey(Brand, on_delete=models.CASCADE, default='NoBrand') image = models.ImageField(upload_to='images/') price = models.FloatField() desc = models.CharField(max_length=1000, blank=True) -
Django:URL Mapping ,Page not found (404)
I am a newbie to Django. Trying to create my first webapp. I ran into a problem. I have 3 templates store, kart and checkout. I am able to navigate from store to kart without any issues. Now I wish to move to checkout page from the kart page. I am using a button for this purpose. Below given is the code present in my kart.html page. I am facing the below issue: Below given is my urls.py file And this is my views.py file Could anyone tell me what I am doing wrong. Thanks in advance!! -
How to call a method inside the class model in python django
In models.py class ModelA(models.Model): ... def methodA(self): return ... methodA() # How to call this methodA, this line is giving error. How to call methodA from inside the class. I tried self.methodA(), but there is NameError on 'self'. I also tried ModelA.methodA(), but here comes an error as name 'ModelA' is not defined. -
Understanding the importance of Gunicorn and Nginx for Django web development
I'm entirely uninitiated to the world of web development, and only have a tentative grasp on Django and web development through the test server it works through. From the guide I'm reading, the author turns to using Nginx once he starts working on site deployment, because Django is "not designed for real-life workloads." What does that mean, and why doesn't it? In terms of justification for using Gunicorn, the author remarks: Do you know why the Django mascot is a pony? The story is that Django comes with so many things you want: an ORM, all sorts of middleware, the admin site… "What else do you want, a pony?" Well, Gunicorn stands for "Green Unicorn", which I guess is what you’d want next if you already had a pony… Well and good, but I don't really know what the two are doing for the server. I know for web developers this is like asking what multiplication is to a maths professor, so please excuse the naivety. In your please keep in mind I have almost no knowledge of web development other than what I've thus far learned from this guide, doing my best to understand as much as I can … -
Google Calendars API with Django -- Error 403, Missing valid API key
We're trying to use the Google Calendars API in our Django project, when I try python manage.py runserver I get a 404 error, and when I click the link it provides me I get this: { "error": { "code": 403, "message": "The request is missing a valid API key.", "errors": [ { "message": "The request is missing a valid API key.", "domain": "global", "reason": "forbidden" } ], "status": "PERMISSION_DENIED" } } I went to the developer console and made an API key, but I'm not really sure how to use it. I came across someone using the API key as part of the "context" variable when making a POST request, but I haven't even attempted submitting the form that is supposed to call the API; I'm getting this error on startup. I tried adding a key: [my API key] in my service account json file, but that did not fix anything. Here is the Calendars code we have: BASE_DIR = os.getcwd() CLIENT_SECRET_FILE = BASE_DIR + '\calendar_api\credentials.json' # 'calender_key.json' SCOPES = 'https://www.googleapis.com/auth/calendar' scopes = [SCOPES] APPLICATION_NAME = 'Google Calendar API Python' class google_calendar_api: def build_service(self): credentials = ServiceAccountCredentials.from_json_keyfile_name( CLIENT_SECRET_FILE, SCOPES ) http = credentials.authorize(httplib2.Http()) service = build('calendar', 'v3', http=http, cache_discovery=False) return … -
Create a social authentication functionality with google django
Hello I am a newbie and have a task to do,I have tried simple social authentication that is working but below is bit complicated: Create a social authentication functionality with google and add user in a database. After adding user in a database, customer should also be created using django signals. Note:- Customer is one to one related with user? -
raise InconsistentMigrationHistory( django.db.migrations.exceptions.InconsistentMigrationHistory:
I run python manage.py migrate, and I get this error: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Dell\Desktop\Django\newspaper\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Dell\Desktop\Django\newspaper\venv\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Dell\Desktop\Django\newspaper\venv\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Dell\Desktop\Django\newspaper\venv\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\Dell\Desktop\Django\newspaper\venv\lib\site-packages\django\core\management\base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\Dell\Desktop\Django\newspaper\venv\lib\site-packages\django\core\management\commands\migrate.py", line 95, in handle executor.loader.check_consistent_history(connection) File "C:\Users\Dell\Desktop\Django\newspaper\venv\lib\site-packages\django\db\migrations\loader.py", line 302, in check_consistent_history raise InconsistentMigrationHistory( django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency users.0001_initial on database 'default'. I have a custom user model, so here it is: from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): age = models.PositiveIntegerField(null=True, blank=True) I dont get any error in running python manage.py makemigrations users What is the problem? -
Generate HTML Table that has Rows and Columns as Models in django with normal time complexity
I would like to populate a table in a template, but I noticed that its extremely slow and i think that I am doing something terribly wrong (to be specific ... it take 3 seconds to handle one request from my localhost). I think that the whole reason of it being so slow is because of I am generating it over and over again ... which in my opinion is very bad thing to do ... sadly, I would like it to be pulled from DB in case of any problems (like server restart etc.) so thats why i do not want to initialise it as a global var and work with it that way. models.py class Category(models.Model): name = models.CharField(max_length=120) class Note(models.Model): name = models.CharField(max_length=120) class Whistle(models.Model): name = models.CharField(max_length=120) category = models.ForeignKey(Category, on_delete=models.CASCADE) note = models.ForeignKey(Note, on_delete=models.CASCADE) views.py class ProductTableView(TemplateView): template_name = "whistles_shop/table.html" def get_context_data(self, *args, **kwargs): request = self.request context = super().get_context_data(**kwargs) context['whistle'] = Whistle.objects.all() context['note'] = Note.objects.all() context['category'] = Category.objects.all() all_rows = [] for cat in Category.objects.all(): one_row = [cat.name] for note in Note.objects.all(): whist = Whistle.objects.filter(category=cat, note=note) if whist: one_row.append("X") else: one_row.append("-") all_rows.append(one_row) context['tab'] = all_rows return context template.html <table class="table table-dark"> <thead> <tr> <th>#</th> … -
Synchronise Google Gsheet with Django Error
I`ve followed this tutorial https://labs.meanpug.com/sync-data-to-and-from-google-sheets-with-django-gsheets/ but got an error IndexError: list index out of range How can I debug this error? Many thanks, -
How do I add a database constraint in a Many-to-Many Relation
I have the following model: class School(models.Model): principal = models.OneToOneField(User, on_delete=models.CASCADE) The User model is Django's stock auth model. I want to only allow a school.principal to be instances of the User model that belongs to the Principals group. (By group, I also mean Django's stock auth Group model). I'm basically stuck on how the implementation of check should be: class School(models.Model): principal = models.OneToOneField(User, on_delete=models.CASCADE) class Meta: constraints = [ models.CheckConstraint( check=<allow_only_User_instances_that_belongs_to_the_Principals_group>, name='principal_is_actually_a_principal', ), ] On the chance that a database/Django version specific implementation is necessary, I'm using the following stack: Python 3.8 Django 3.1 PostgreSQL 12.1 I know I can add the check on the application level, but having database constraints makes me feel confident that my data is always in valid state. Any help or nudge to the right direction will be greatly appreciated. Thanks! -
How to restart a timer for a task in Celery/Python?
Stack - Python/Django/Celery/Redis Celery config is absolutely basic, such as https://docs.celeryproject.org/en/4.4.0/django/first-steps-with-django.html#using-celery-with-django I have this task: @periodic_task(run_every=timedelta(minutes=settings.CRONTAB_MINUTES),name='get_current_rate_automaticallY') def get_current_rate_automatically(): logger.info("Got automatic request to get current rate") res = get_current_rate() if not res: return res.save() Basically this task hits external API to get bank rate for a predefined currency, which is working fine. In addition, I have django endpoint which manually triggers this function to get this currency rates manually. I need to restart timer for such task in case this endpoint is activated. Possibly stupid question, but was not able to find anything suitable in the Celery documentation or onsite. Any sort of help is appreciated :) Thanks! -
Django bulk_create leaks memory
We are using Django 2.2 and python 3.6 for scheduling data intensive jobs. Memory is increasing over time for a long running job. DEBUG=False in settings.py simple code like this for record_batch in readFromSomewhere(batch_size): for record in record_batch: product = parse(record) product_list.append(product) Product.objects.bulk_create(product_list) #db.reset_queries() #gc.collect() I read a lots of stackoverflow post and put gc.collect() and django.db.reset_query(), but it does not prevent the increase. If I comment out Product.objects.bulk_create(products), Memory stops increasing. the batch size is very small, around 100. I notice if the batch size is smaller, which means the number of bulk_create calls is larger, memory increases faster. If the batch size is larger, then memory increase slower. Any thoughts to release the memory after batch created into db? -
cannot insert NULL into Primary Key Django
when im trying to create an object in django, oracle db ask to me for the primary key, "id_orden". but its suppossed to django insert the next value, because is a IntegerField(primary key=True), so why is asking to me for it?. The error: IntegrityError at /listado_carro/ ORA-01400: cannot insert NULL into ("SUSHIFU"."MTV_ORDEN"."ID_ORDEN") The error is in the line from views.py: orden =Orden.objects.create(id_carro=carro,fecha_hora=timezone.now(),nombre_cliente=usuario2.nombre+' '+usuario2.apellido,direccion=usuario2.direccion,nota='',total=total2) Models.py class Orden(models.Model): id_orden = models.IntegerField(primary_key=True) id_carro = models.OneToOneField('Carro', on_delete=models.CASCADE) fecha_hora = models.DateTimeField(default=timezone.now) nombre_cliente = models.CharField(max_length=50) direccion = models.CharField(max_length=99) nota = models.CharField(max_length=200) total= models.IntegerField(default='0') Views.py def listado_carro(request): usuario = request.user usuario2 = Usuario.objects.get(id=usuario.id) locale.setlocale(locale.LC_ALL, '') carros = Carro.objects.filter(id_carro=usuario.id) carro = Carro.objects.filter(id_carro=usuario.id).first() total = locale.format('%.0f',Carro.objects.filter(id_carro=usuario.id).aggregate(sum=Sum('precio_producto')) ['sum'], grouping=True, monetary=True) total2 = Carro.objects.filter(id_carro=usuario.id).aggregate(sum=Sum('precio_producto'))['sum'] orden =Orden.objects.create(id_carro=carro,fecha_hora=timezone.now(),nombre_cliente=usuario2.nombre+' '+usuario2.apellido,direccion=usuario2.direccion,nota='',total=total2) data = {'carros':carros,'total':total, 'orden':orden} return render(request, "listado_carro.html", data)