Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add cores headers in Django ajax call
I tried to hit the API using an ajax call. but it's throwing this Error (from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request). I add cores headers settings in Django settings and headers also added in ajax call. but I could not get the data throwing the same error. Ajax Code $.ajax({ url: "{{ api.endpoint }}", type: "GET", beforeSend: function(request) { request.setRequestHeader("Access-Control-Allow-Origin", 'http://127.0.0.1:8000'); }, data: { "limit" : 1, "api_key" : "{{ api.token }}" }, success: function(data) { alert("Your Connection is successful. Retrieved " + data.length + " records from the dataset!"); }, error: function(err) { console.log(err) alert("Connection Failed."); } }); -
why the django admin console is terminating the web server automatically?
I have created a custom User model as I wanted to use email as unique constraint. Below is the code snippet models.py from django.db import models from django.contrib.auth.base_user import BaseUserManager from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin class AccountManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, shop_name, contact, password, **extra_fields): values = [email, contact] field_value_map = dict(zip(self.model.REQUIRED_FIELDS, values)) for field_name, value in field_value_map.items(): if not value: raise ValueError('The {} value must be set'.format(field_name)) email = self.normalize_email(email) user = self.model( email=email, contact=contact, shop_name=shop_name, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, shop_name, contact, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, shop_name, contact, password, **extra_fields) def create_superuser(self, email, shop_name, contact, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, shop_name, contact, password, **extra_fields) class Shop(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) shop_name = models.CharField(max_length=150) contact = models.CharField(max_length=10) State = models.CharField(max_length=100) district = models.CharField(max_length=100) location = models.CharField(max_length=100) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(null=True) objects = AccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['shop_name', 'contact', 'State', 'district', 'location', 'is_staff'] def get_full_name(self): return self.shop_name def get_short_name(self): return self.shop_name.split()[0] class Medicine(models.Model): medicine_name = models.ForeignKey(Shop, on_delete=models.CASCADE, … -
Theme Choosing Option for a Django Project not working properly
Helloo, I am following a tutorial to allow User to select Light/Dark Mode using HTML, CSS, JS. I have following documentation and tutorial but the issue is that the content of the page itself is not showing and I am not sure the reason. So what I did is I created 2 css files dark and light, and create a mode application with the settings. I am currently receiving an error: django.contrib.auth.models.User.setting.RelatedObjectDoesNotExist: User has no setting. To start here is the base.html <link id="mystylesheet" href="{% static 'css/app-light.css' %}" type="text/css" rel="stylesheet"> <!-- Mode --> <div id="mode" class="section" style="padding-top: 1rem; padding-bottom: 3rem;text-align: right"> <button onclick="swapStyle('css/app-light.css')" type="button" class="btn btn-secondary">Light Mode</button> <button onclick="swapStyle('css/app-dark.css')" type="button" class="btn btn-dark">Dark Mode</button> </div> <!-- Mode --> <script type="text/javascript"> function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); var cssFile = "{% static 'css' %}" function swapStyles(sheet){ document.getElementById('mystylesheet').href = cssFile … -
Can't get kwargs data in function in Django Celery Beat
I'm implementing a reminder module in the application using Django celery-beat, I'm creating cron tab in periodic tasks and passing dictionary in kwargs parameter. It's successfully saved in Django periodic task table but when the scheduled task runs on time and calls the mentioned function, it's not getting kwargs data and through the exception. settings.py INSTALLED_APPS = [ 'django_celery_beat', ] # CELERY STUFF CELERY_BROKER_URL = "redis://localhost:6379" CELERY_RESULT_BACKEND = "redis://localhost:6379" CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' init.py from .celery import app as celery_app all = ("celery_app",) celery.py import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings_local") app = Celery("baseapp") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() Here is the task scheduler function which is creating periodic tasks: def task_scheduler(raw_data): try: if raw_data["start"] and raw_data["reminder"]: reminder_time = datetime.datetime.strptime(raw_data["start"], '%Y-%m-%dT%H:%M:%S.%fZ') - datetime.timedelta(minutes=raw_data["reminder"]) reminder, _ = CrontabSchedule.objects.get_or_create( minute=reminder_time.minute, hour=reminder_time.hour, day_of_week="*", day_of_month=reminder_time.day, month_of_year=reminder_time.month, ) PeriodicTask.objects.update_or_create( name=raw_data["summary"], task="reminder_notification", crontab=reminder, expire_seconds=7200, kwargs=json.dumps({'test111':'123'}), ) except Exception as error: print(error) Here is a reminder notification function which is called when the task runs on time: @shared_task(name="reminder_notification") def reminder_notification(*args, **kwargs): print("hello task") Here are tasks in the database: Here is the error: What am I doing wrong? -
What does "django.db.utils.ProgrammingError: relation "silk_request" does not exist LINE 1: INSERT INTO "silk_reque mean?
So, here is what I have done. I have cloned this repo https://github.com/hitul007/complianceok followed by git stash then git checkout due_date and git pull origin due_date when i tried to run the server, it throws an error which i couldnt understand. Not only that, I could not even locate the file where this actual problem is? What is this silk thing? Can someone please explain what is the actual issue and how do I solve it? I am using python 3.8 and django 3.1.2enter image description here Thank you very much -
Styling Email with inlinecss
I am looking to send email after a form is validated in Django. The email works well, except that it is delivered with no CSS formating. I was told to add the following to the template: {% load inlinecss %} {% inlinecss "css/MegaTemplate-dashboard.css" %} Code... {% endinlinecss %} My set up is as follow NewAlgo > Core > Static > assers > css > MegaTemplate-dashboard.css In my settings.py I have : # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' # Extra places for collectstatic to find static files. STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'core/static'), ) When I submit the form, everything goes well until the mailing section, and I get the error : FileNotFoundError at /restrictedname/new/ [Errno 2] No such file or directory: 'P:\\NewAlgo \\staticfiles\\css\\MegaTemplate-dashboard.css' Does anybody knows what I am not doing right please ? -
Django contact page without sendgrid
I have a working django contact page, currently configured to send the mail message to the console, as well as tested with my server. The only issue with using my server settings, is that it uses the pre-configured email in my settings.py to send the message. And I'd like custom email addresses to be entered. I've seen sendgrid is one way of doing this, but I'd like to know if I can achieve this without using a service like sendgrid? -
how to sum the two definition functon value in django
how can i sum these two Hbase user and Hbase system in one def function? I wan t do like this but now i have no idea how to continue... def HbaseStagingCpuUser(self): request = self.request self.request.set_MetricName('cpu_user') responseCpuUsed = response_dict['Datapoints'] cpu_user_data = json.loads(responseCpuUsed) cpu_user_list = [] for user_data in cpu_user_data: cpu_user_dict = { 'host': user_data['host'], 'value': user_data['Average'], 'timestamp': math.trunc(datetime.fromtimestamp(user_data['timestamp']/1000.0).replace(second=0, microsecond=0).timestamp()) } cpu_user_list.append(cpu_user_dict) #print(cpu_user_list) return cpu_user_list def HbaseStagingCpuSystem(self): request = self.request request.set_MetricName('cpu_system') cpu_system_list = [] cpu_system_data = json.loads(responseCpuSystem) for system_data in cpu_system_data: cpu_system_dict = { 'host':system_data['host'], 'value':system_data['Average'], 'timestamp': math.trunc(datetime.fromtimestamp(system_data['timestamp']/1000.0).replace(second=0, microsecond=0).timestamp()) } cpu_system_list.append(cpu_system_dict) #print(cpu_system_list) return cpu_system_list sum def SumHbaseCpu(HbaseStagingCpuUser,HbaseStagingCpuSystem): -
how to store a dictionary in a djongo model?
I need to store daily values of date and price for many stocks. I get this data in the next format: {"stockname":"XXX","currency":" ","values":[["2021-01-06","1.00"]]} Im using Djongo to store the data, however, i don't know what kind of Field i should use to store the dictionary in my app. My goal is to add the latest date and price of a stock daily. My idea was to have each document with the next structure: {"stockname":"NAME","FirmName":"Firm","DailyValues":[["2020-01-01","1.00"],...,["2020-01-06","2.00"]]} But im not sure if a list of lists is supported for a django model. Thank you in advance. -
Django 404 Email spam
I recently launched a web application based Django, and have been very pleased with its results. I also turned on a feature in Django where you can have emails sent to MANAGERS for 404's by adding the middleware 'django.middleware.common.BrokenLinkEmailsMiddleware'. However, ever since I did that, I'm getting LOTS of spam requests hitting 404s. I'm not sure if they are bots or what but this is the information I'm getting from Django: Referrer: http://34.212.239.19/index.php Requested URL: /index.php User agent: Mozilla/5.0 (Windows; U; Windows NT 6.0;en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6) IP address: 172.31.23.16 Why am I getting requests to URL's that don't exist on my site and is there a way to filter out requests so I don't get emails for them? These URL's have never existed on my site (my site is very recently launched). I'm getting roughly 50-100 emails a day from spam requests to my site. Any help is appreciated! -
How to add multiple ckeditor in django template for same model field?
I have Multiple Choice Question model and answer model. For one question there are 4 answers. I need to add ckeditor in all 5 field. No problem with question field, but i can not get it work for 4 answer fields. I tried replace textarea with ckeditor but can not get image upload to work. -
The included URLconf 'myapp.urls' does not appear to have any patterns in it
I have an interesting issue.. hope you have seen this kind of behavior. I have django 3.1.4 and running on python 3.6.2. The project I am working on works fine, i can access all the urls and the endpoints function like they way they should. While working on the code, when I make a mistake in one of the classmethod of a class and try to run django, python manage.py runserver localhost:4444, I get this error, 'The included URL.conf 'myapp.urls' does not appear to have any patterns in it.` I know that I didnt touch the urls file and everything is how it should be (besides the error in my classmethod). If I run, python manage.py makemigrations, only then can i see the actual error that needs to be resolved. Otherwise, only error that django throws when running the runserver is the URL.conf error. Besides the imports, I only have this block in my myapp.urls. I need these for the @api_views that I have in my views.py file. urlpatterns = [ url('admin/', admin.site.urls), url('api/', include('other.urls')), url(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}), ] Anything I need to configure or is it by design? If you need more information, happy to provide that. -
How do I store environment variables both locally and not to have to change code when deploying on Heroku in Django
I have a Django project I have been working on offline and now I have hosted it on Heroku and it works well on Heroku but fails on my local machine with this error. File "/usr/lib/python3.9/os.py", line 679, in __getitem__ raise KeyError(key) from None KeyError: 'DEBUG' and I think it is because I used environment variables like this. from boto.s3.connection import S3Connection import os DEBUG = S3Connection(os.environ['DEBUG'], os.environ['DEBUG']) I also have a .env file in my root(project folder) with the environment variables like this. export JWT_SECRET_KEY = "dfge..." export DEBUG = 1 What is the right way to store the environment variables on my local machine? -
502 Bad Gateway : gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3>
I was trying to deploy a Django app on aws using postgres, gunicorn and nginx After the initial setup, I added the Django app from a git repository after that I am getting a 502 Bad Gateway Here is the gunicorn status ubuntu@ip-172-31-4-106:~/myproject$ sudo systemctl status gunicorn ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; disabled; vendor preset: enabled) Active: failed (Result: exit-code) since Thu 2021-01-07 01:08:56 UTC; 2h 25min ago TriggeredBy: ● gunicorn.socket Process: 54260 ExecStart=/home/ubuntu/myproject/myprojectenv/bin/gunicorn --access-logfile - --workers 3 --bind uni> Main PID: 54260 (code=exited, status=1/FAILURE) Here is the nginx error log: Jan 07 01:08:56 ip-172-31-4-106 gunicorn[54260]: File "/home/ubuntu/myproject/myprojectenv/lib/python3.8/site-package>Jan 07 01:08:56 ip-172-31-4-106 gunicorn[54260]: self.reap_workers() Jan 07 01:08:56 ip-172-31-4-106 gunicorn[54260]: File "/home/ubuntu/myproject/myprojectenv/lib/python3.8/site-package>Jan 07 01:08:56 ip-172-31-4-106 gunicorn[54260]: raise HaltServer(reason, self.WORKER_BOOT_ERROR) Jan 07 01:08:56 ip-172-31-4-106 gunicorn[54260]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> Jan 07 01:08:56 ip-172-31-4-106 systemd[1]: gunicorn.service: Main process exited, code=exited, status=1/FAILURE Jan 07 01:08:56 ip-172-31-4-106 systemd[1]: gunicorn.service: Failed with result 'exit-code'. Jan 07 01:08:56 ip-172-31-4-106 systemd[1]: gunicorn.service: Start request repeated too quickly. Jan 07 01:08:56 ip-172-31-4-106 systemd[1]: gunicorn.service: Failed with result 'exit-code'. Jan 07 01:08:56 ip-172-31-4-106 systemd[1]: Failed to start gunicorn daemon. Couldn't find any solution for this problem please help -
Why is docker-compose creating files with a root owner and how can I modify the docker-compose.yml file to stop it?
I am building a Django app to run using Docker. In the docker-compose.yml file, I am using volumes to save changes. services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 When I create a new application within the Django project, I use... docker-compose exec web python manage.py startapp app_name Docker-compose writes the app (app_name) to my local file, as expected, but with a root owner. This is causing problems, because, if I want to then create a new file within the app, I don't have permission. If I exit docker-compose and create the app as a user, then there are no issues. How can I change the .yml file to fix this? -
How to check if the email id is private in django?
I want to give a validation in django for email ids, If a user enters a email from free email service provider then a validation error must popup that "This is not a business email id".. Only User having private email ids or business email ids can be eligible. How can this be possible using Django python version : 3.7.9 django version : 2.2.3 -
FAILED SQL: ('ALTER TABLE "app_employee" ADD COLUMN "industry_id" int NULL',)
I am working on a project in Django with mongoDB. my app's name is app. my models.py: class myCustomeUser(AbstractUser): #id = models.AutoField(primary_key=True) username = models.CharField(max_length=20, unique="True", blank=False) password = models.CharField(max_length=20, blank=False) is_Employee = models.BooleanField(default=False) is_Inspector = models.BooleanField(default=False) is_Industry = models.BooleanField(default=False) is_Admin = models.BooleanField(default=False) def __str__(self): return self.username class Industry(models.Model): user = models.OneToOneField(myCustomeUser, on_delete=models.CASCADE, primary_key=True, related_name='industry_releted_user') name = models.CharField(max_length=200, blank=True) owner = models.CharField(max_length=200, blank=True) license = models.IntegerField(null=True, unique=True) industry_extrafield = models.TextField(blank=True) def __str__(self): return self.name class Employee(models.Model): user = models.ForeignKey(myCustomeUser, null=True, blank=True, on_delete=models.CASCADE) industry = models.ForeignKey(Industry, null=True, blank=True, on_delete=models.CASCADE) i_id = models.IntegerField(unique=True) name = models.CharField(max_length=200, blank=False, null=True) gmail = models.EmailField(null=True, blank=False, unique=True) rank = models.CharField(max_length=20, blank=False, null=True) employee_varified = models.BooleanField(default=False, blank=True, null=True) def __str__(self): return self.name class Inspector(models.Model): user = models.ForeignKey(myCustomeUser, on_delete=models.CASCADE, related_name='inspector_releted_user') name = models.CharField(max_length=200, blank=False, null=True) gmail = models.EmailField(null=True, blank=False, unique=True) nationalid = models.IntegerField(null=True, blank=False, unique=True) inspector_extrafield = models.TextField(blank=True) def __str__(self): return self.name class Admin(models.Model): user = models.ForeignKey(myCustomeUser, on_delete=models.CASCADE, related_name='admin_releted_user') name = models.CharField(max_length=200, blank=False, null=True) gmail = models.EmailField(null=True, blank=False, unique=True) admin_extrafield = models.TextField(blank=True) def __str__(self): return self.name class PrevJob(models.Model): employee = models.ForeignKey(Employee, null=True, blank=True, on_delete=models.CASCADE) industry = models.ForeignKey(Industry, null=True, blank=True, on_delete=models.CASCADE) i_id = models.IntegerField(unique=True) #name = models.CharField(max_length=200, blank=False, null=True) rank = models.CharField(max_length=20, blank=False, null=True) def __str__(self): return self.employee.name in … -
Django - How to differentiate between users in the database?
I'm building a Django server for my company and I'm still unfamiliar with some processes. I'm sure this is super simple, I'm just completely unaware of how this works. How do I differentiate between user's data so it doesn't get mixed up? If Jill is a user and she requests a page of her profile data, how do I not send her Jack's profile data, especially if there are multiple models invovled? For example, the code in the view would look like this: def display_profile(request) profile = Profile.objects.get(???) # What do I put in here? I understand that I can do: def display_profile(request, user) profile = Profile.objects.get(user_id=user) But that's not my design intention. Thank you in advance. -
GeoDjango OpenLayers.js don't display correct
I have Problem with Open Layers here it and it display correctly when i remove Jet Admin but it's OK ... now it happen in my frontend like the oic bellow -
How to change rest-framework form format in django?
My Application is working. but As in the photo below, I have not been able to change the date form format provided by django-rest-framework. show Image how to change date format?? -
Django Querying chained Foreign Key
Hello I am learning Django ORM queries and come to figure out reverse relationship in Foreign Key. I cannot visualize _set in foreign key field hope I will be cleared here. Here are my model I have been working. class Location(BaseModel): name = models.CharField( max_length=50, validators=[validate_location_name], unique=True, ) I have Route model linked with Location as FK: class Route(BaseModel): departure = models.ForeignKey( Location, on_delete=models.PROTECT, related_name='route_departure' ) destination = models.ForeignKey( Location, on_delete=models.PROTECT, related_name='route_destination' ) Similarly I have Bus Company Route linked Foreign key with Route class BusCompanyRoute(BaseModel): route = models.ForeignKey(Route, on_delete=models.PROTECT) Finally I have Schedule Model linked with BusCompanyRoute as Fk class Schedule(BaseModel): bus_company_route = models.ForeignKey(BusCompanyRoute, on_delete=models.PROTECT) Problem is I want to query from views being on Schedule model want to link with departure and destination how will I do that? I have only done this so far on view.py schedule = Schedule.objects.all() I am stuck on querying Chained foreign key -
No name 'DjangoWhiteNoise' in module 'whitenoise.django' Error
I'm currently in the process of deploying my django app to Heroku, and the walkthrough I'm following is having me add the following code to my wsgi file. Only issue is that I'm getting an error that No name 'DjangoWhiteNoise' in module 'whitenoise.django' I have whitenoise 5.1.0 installed, but can't figure out how to install whitenoise.django or what the issue is. Any ideas? wsgi.py from whitenoise.django import DjangoWhiteNoise application = DjangoWhiteNoise(application) -
Manipulate bokeh plot using javascript
I have a long plot which the user is supposed to be able to pan in the x direction, but I want to add buttons to position the user in an specific region of the plot. How can I do this? I guess using javascript but I have no idea how to manipulate an already rendered bokeh plot. -
Django best practice for views.py files?
Large companies obviously have huge request loads and tons of information to render, so where in a Django project does that information get processed? Does it happen in the views.py file? A separate .py file that's called by the views.py file? I'm asking because my views.py files become thousands of lines long very quickly... does this matter or am I missing something here? I have a couple of views in my project that processes a lot of data from the database, what is the best practice for where to put the code? -
Django Model @property To Check if One User is a Subscriber / Follower Of Another User
I have a simple Subscriber model: class Subscriber(models.Model): """ User.subscribers.all() - all my subscribers User.subscriptions.all() - all the users I am subscribed to """ user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='subscribers') subscriber = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='subscriptions') created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.subscriber.username In a template, I want to be able to write: {% if user.is_subscribed %} where user could be any authenticated (logged-in) user. Is it possible to add a @property method to either this Subscriber model or the User model? OR Is it best to put this logic in the the view and passed to the template through context? End-goal: check if the user making the request is subscribed to another user and return True or False.