Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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) -
Python: Django comparing timezone.now() with DateTimeField Object
I'm trying to validate if the date isn't earlier than the current time. So I've read somewhere in the forums that I should use timezone.now() instead of datetime.now() Django is giving you a timezone-aware datetime object. datetime.now() is giving you a timezone-naive datetime object. You can't compare these. Instead use django.utils.timezone.now(), which provides the type of datetime So basically as a Django developer, I should better use what Django can offer in default. I got these settings in the main settings file: TIME_ZONE = 'Europe/Vilnius' USE_I18N = True USE_L10N = True USE_TZ = True This is my logic for validating the provided date/time: if date <= timezone.now(): raise serializers.ValidationError("Meeting could not start earlier than the current time") return date But it always returns the date object instead of raising the ValidationError. These are the times which I'm playing with: if timezone.now() < parse(reservation['date_from']): raise serializers.ValidationError("Meeting could not start earlier than the current time") !NOTE: I'm using .parse() to convert the object from str to datetime object. timezone.now() returns - 2020-11-22 00:16:55.334792+00:00 parse(reservation['date_from']) and reservation['date_from'] returns the same - 2020-11-21 23:50:42.375116+00:00 -
Django + React app deployed on GAE with static files in Google Storage but deployment won't work
I have a Django/React application. The frontend is being served by Django using static files. Because I am using GeoDjango, I've had to move from using GAE standard to GAE flex (to build a container with GDAL as it is required for GeoDjango etc). However, now my site won't load and requests get cancelled when trying to load the static content. I have an app.yaml which looks like this: runtime: custom env: flex entrypoint: gunicorn -b :$PORT appname.wsgi runtime_config: python_version: 3 env_variables: DJANGO_SECRET_KEY: "someVariable" GOOGLE_API_KEY: "someVariable" handlers: # This configures Google App Engine to serve the files in the app's static # directory. - url: /static static_dir: static/ # This handler routes all requests not caught above to your main app. It is # required when static routes are defined, but can be omitted (along with # the entire handlers section) when there are no static files defined. - url: /.* script: auto My app settings contain the cloud storage url like this: STATIC_ROOT = 'static' STATIC_URL = '/static/' REACT_APP_DIR = os.path.join(BASE_DIR, 'frontend') STATICFILES_DIRS = [ os.path.join(REACT_APP_DIR, 'build', 'static'), ] And last but not least, this is the view that renders the frontend via Django: class FrontendAppView(View): """ Serves the … -
How can you access a digital ocean "Access Key"?
Earlier in Digital Ocean an "AWS_ACCESS_KEY_ID" and "AWS_SECRET_ACCESS_KEY" were easily created. The "AWS_ACCESS_KEY_ID" has now been removed and been replaced by a scope (Read/Write). Has it been removed? Where can you find it? I've been searching everywhere... am i missing something very obvious? I need it to access the Digital Oceans spaces within my Django app... AWS_ACCESS_KEY_ID = 'xxxxxxxxxxxxxxxxxx' AWS_SECRET_ACCESS_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' AWS_STORAGE_BUCKET_NAME = 'xxxxxxxxx' AWS_S3_ENDPOINT_URL = 'xxxx--xxxxxxxxx' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'xxxxxx-xxxxxx' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_URL = 'https://%s/%s/' % (AWS_S3_ENDPOINT_URL, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' -
Django Rest Framework - Serializing Model Relationships
I have been working on this problem for a while now and cannot get to the bottom of what I'm doing wrong. I am trying to add a many-to-many relationship between two models using Django REST framework using the PrimaryKeyRelatedField, but cannot get the relationship to save. What the code I've got below does is save the newly created first_model item, but it does not save the relationship (if i view the relationship table it remains empty) Any tips on where I'm going wrong would be appreciated! Here is a snippet of the code I have: Here is the views: @api_view(['POST']) def RiskCreate(request): serializer = First_ModelSerializer(data = request.data) if serializer.is_valid(): serializer.save() else: print("data is not valid") return Response(serializer.data) Here are the models: class First_Model(models.Model): Model_Title = models.CharField(max_length = 500, blank=True) Model_Descr = models.CharField(max_length = 500, blank=True) relationship = models.ManyToManyField(Second_Model) class Second_Model(models.Model): Title_two = models.CharField(max_length = 50, unique = True) Descr_two = models.CharField(max_length = 50, unique = True) Here are is the serializer: class First_ModelSerializer(serializers.ModelSerializer): relationship = serializers.PrimaryKeyRelatedField(many = True, read_only=True) class Meta: model = Risks fields = ('Model_Title', 'Model_Descr', 'relationship') And here is how I'm passing the data to the view: function addHazard(item){ var url = baseurl + 'api/Create/' var …