Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django User model throws duplicate key value violates unique constraint "user_user_username_key" on user creation
I am testing my user model to see if it's signal works correctly however, I am getting an error: psycopg2.errors.UniqueViolation: duplicate key value violates unique constraint "user_user_username_key" DETAIL: Key (username)=() already exists. Currently my test is: class UserTestCase(TestCase): obj1 = None obj2 = None def setUp(self): self.obj1 = User.objects.create(first_name="james", last_name="adams", email="jamesadams@gmail.com") self.obj2 = User.objects.create(first_name="amy", last_name="", email="12amy_123jackson@hotmail.com") And my signals file is: @receiver(pre_save, sender=User, dispatch_uid="set_username_of_user") def set_username(sender, instance, **kwargs): """ Every time a user is saved, ensures that user has a certain username This method avoids users having username field set to null """ if not instance.username: email = instance.email email_without_domain = email[:email.find("@")].replace("-","_").lower().strip()[:20].replace(' ','') username = create_username(email_without_domain) print(username) if User.objects.filter(username=username).exists(): while User.objects.filter(username=username): username = create_username(email_without_domain) instance.username = username instance.save() I can confirm that the signal is being called however, it still throws that error. What could be causing this issue? -
How can I start and view a zoom meeting with python Django and zoom api?
I'm trying to create a LMS system with Django and I need to be able start and view zoom meetings from the website using zoom api. I found a python library called zoomus for python to connect to the api but they don't give any documentation. does anyone have an idea how to do this ? Thank you! -
Unable to locate react static files when running collectstatic in python and uploading to heroku
I'm trying to add a Django backend and a react frontend to Heroku. Following this tutorial. I'm using whitenoise for serving static files. When runnning python manage.py collectstatic I keep getting the same error: django.core.exceptions.SuspiciousFileOperation: The joined path (C:\Users\Obenheimer\Documents\combined_connect\static\media\background-pattern.f6347303.png) is located outside of the base path component (C:\Users\Obenheimer\Documents\combined_connect\staticfiles) This command is also run by heroku python hooks when deploying. The python hook runs after the react hook, so the react build folder is definitely there. For testing purposes I also ran build locally for when I call the collectstatic command. The problem is something to do with how I'm defining static roots, but for the life of me I can't figure it out. I've used multiple tutorials, the django docs on static files, and the heroku dev docs on static files. Why is it looking for my media files (background-pattern.png etc.) in static? On collectstatic everything gets put into the staticfiles directory. No matter what I change the file names or variables to, that error about the lookup conflict between staticfiles and static always happens. Here's how I'm defining them: settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'build')], # pointing to … -
How to explicitly instruct PyTest to drop a database after some tests?
I am writing unit-tests with pytest-django for a django app. I want to make my tests more performant and doing so is requiring me to keep data saved in database for a certain time and not drop it after on test only. For example: @pytest.mark.django_db def test_save(): p1 = MyModel.objects.create(description="some description") # this object has the id 1 p1.save() @pytest.mark.django_db def test_modify(): p1 = MyModel.objects.get(id=1) p1.description = "new description" What I want is to know how to keep both tests separated but both will use the same test database for some time and drop it thereafter. -
Auto Refresh Token Middleware for Django Graphql
I am trying to build a site using React with Apollo Client on the frontend and Django GraphQl on the backend and I am using django-graphql-auth with jwt token to handle authentication. Now I am trying to write a middleware with gets access and refresh token through http headers and I want to refresh the tokens if the access token is expired using the refresh token. I was able to do the basic steps like get the access and refresh token from the request, but couldn't able to figure out how to refresh access token. def refreshTokenMiddleWare(get_response): # this middleware functionality is check the validity of the # token and if the access token is expired then the access token # is refreshed and set the appropriate headers def middleware(request): # implement the logic # get token and refresh token AUTH_HEADER = request.headers.get('authorization') refreshToken = request.headers.get('X-Refresh-Token') token = get_http_authorization(request) # check if the tokens are valid try: payload = jwt_settings.JWT_DECODE_HANDLER(token) except jwt.ExpiredSignature: pass except jwt.DecodeError: raise exceptions.JSONWebTokenError(_('Error decoding signature')) except jwt.InvalidTokenError: raise exceptions.JSONWebTokenError(_('Invalid token')) # check if token is expired # refresh token # add appropriate headers response = get_response(request) return response return middleware I couldn't able to figure out … -
Variable not updating along other attributes in template
I'm writing a webapp that pings a list of IP's retrieved from a model in the app. The issue I'm having is when the code that pings the IP and stores its status code (Either 0, 256, or 512) in a variable, the template just takes the last stored value and displays that. Here's my code: models.py from django.db import models # Create your models here. class NewServer(models.Model): name = models.CharField(max_length=200) ip = models.CharField(max_length=200) def __str__(self): return self.ip return self.name views.py from django.shortcuts import render from django.http import HttpResponse from .models import NewServer import os # Create your views here. def index(request): servers = NewServer.objects.order_by('id') for ids in servers: #get object from NewServer get_server = NewServer.objects.get(id=ids.id) #setup the ping command, with the IP being #grabbed from get_server.ip ping = "ping -c 1 " + get_server.ip + " > /dev/null" #set/run command to the status_code variable status_code = os.system(ping) #for debugging purposes: sstring = f"{get_server.name} is: {status_code}" print(sstring) context = {'servers':servers, 'status_code': status_code} return render(request, 'monitor/index.html', context) index.html {% extends 'monitor/base.html' %} {% block content %} <table> <tr> <th> Server Name: </th> <th> Status: </th> <th> Up/Down </th> </tr> {% for server in servers %} <tr> <td>{{server.name}}</td> <td>{{server.ip}}</td> {% if status_code … -
NGINX and Django (Can't load Django app after server reboot)
I'm just experimenting around at the minute getting use to Django which is fully installed on my VPS. Everything has been working fine, but I needed to reboot my server - After rebooting, the default NGINX (Welcome to Redhat Enterprise) page appeared again. I just wanted to pick people's brains with what people believe is the most suitable way to load in a custom NGINX conf.d file after a server reboots? Within the /etc/nginx/conf.d I do have a custom service file configured which worked as intended before my server was rebooted. The custom service file directs traffic through proxy_pass to the default location of where my app.sock file is located. After rebooting my server, I noticed that the default NGINX (Welcome to Redhat Enterprise) was displaying. After doing a little digging, I found a solution whereby a gentleman recommended that it would be a good idea to comment out the default server within the nginx.conf file. (Which did work and my Django app did reppear) - However, is this the most suitable way to default the nginx server to the server I have specified within my custom conf.d service file? Thanks, Jay -
How to filter active users connected using an extended model class field
I have extended the user model to a model class 'Student' using OneToOne relation. Now I want to filter all active students with a field in the 'Student' class such as 'name'. Tried this in django shell: Student.objects.filter(user.is_active == True) Traceback (most recent call last): File "<console>", line 1, in <module> NameError: name 'user' is not defined my View: def entry(request): user = request.user if request.user.is_active: print("Already logged in") return redirect('home') else: return render (request, 'entry.html') my Models: class Student(models.Model): name = models.CharField(max_length=200) branch = models.CharField(max_length=200, choices=BRANCHES) sem = models.CharField(max_length=200, choices=SEMESTERS) reg_no = models.CharField(max_length=200, unique = True) balance = models.IntegerField(default=0) pin_no = models.CharField(max_length=200, unique = True) college = models.ForeignKey(Institute, on_delete=models.CASCADE ) user = models.OneToOneField(User, on_delete=models.CASCADE) -
wrong attributes for <pdf:font> xhtml2pdf
I am trying to specify a font for my xhtml2pdf file. By i get this error wrong attributes for <pdf:font> I am not sure the correct way to specify the attributes for the font? I have tried searching for a solution to this, but can't find anything. <!DOCTYPE html> <html> <style> @import url('https://fonts.googleapis.com/css2?family=Itim&display=swap'); </style> <style> @media print { .pagebreak { page-break-before: always; } /* page-break-after works, as well */ } @page { size: a4; margin: 1cm; @frame footer { -pdf-frame-content: footerContent; bottom: 0cm; margin-left: 9cm; margin-right: 9cm; height: 1cm; } @font-face { font-family: 'Itim', cursive; src: url('https://fonts.googleapis.com/css2?family=Itim&display=swap'); } </style> <body> <p style="font-size:1.3rem;font-family: Itim,sans-serif;">We have generated your PDF!</p> </body> -
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8000/api/task-list/
I'm working on a vuejs and django rest single page application. the problem is so clear, that I'm getting the Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource error. My vuex code be like: mutations:{ addTask: function(){ axios({ url: 'http://127.0.0.1:8000/api/task-list/', method: 'POST', headers: { 'X-CSRFToken': getCookie('csrftoken') } }).then(response => { console.log(response.data); }).catch(err => { console.log(err.response); }) } }, and my django rest urls.py, in my django application urls: urlpatterns = [ path('task-list/', TaskList.as_view()), path('task-create/', TaskCreate.as_view()) ] and my main app urls: urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('task.urls')), path('api/', include('authentication.urls')), path('home/', returnHome) ] my views.py code: class TaskList(APIView): def get(self, request): tasks = Task.objects.all() serialized = TaskSerializer(tasks, many=True) return Response(serialized.data, status=200) my vue app is running on http://localhost:8080, so I installed django cors headers, configured it like the below code: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # rest api 'rest_framework', 'rest_framework.authtoken', 'corsheaders', # my apps 'authentication', 'task' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOWED_ORIGINS = [ 'http://localhost:8080' 'https://localhost:8080' ] Although, I'm still getting the Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8000/api/task-list/. (Reason: CORS request did not succeed) Error! I … -
Django models DB queries optimisation (using select_related / prefetch_related). run 1-2 queries instead of multiple queries
I have this one-to-many relation models [each domain can have several kpis]. i use MySQL DB. class Domains(models.Model): class Meta: managed = True db_table = 'edison_domains' id = models.AutoField(primary_key=True) name = models.CharField(max_length=50, unique=True) display_name = models.CharField(max_length=50) description = models.TextField(blank=True, null=True) class Kpis(models.Model): class Meta: managed = True db_table = 'edison_kpis' id = models.AutoField(primary_key=True) name = models.CharField(max_length=50, unique=True) MORE FIELDS... domain_id = models.ForeignKey(Domains, on_delete=models.CASCADE, db_column='domain_id') What i want is to present for each domain, the list of its KPIs. I tried lots of combinations of select_related and prefetch_related but it always end up that the DB perform a query for each domain, instead of 1 or 2 queries. I tried to read about it here. My main goal is to reduce the number of DB calls and improve the overall performance time. My current code: (views.py) class DomainsAndKpisDescriptionsPage(View): def __init__(self): self.resource = 'domains_kpis_descriptions' def get(self, request, *args, **kwargs): final_list = [] domains_list = Domains.objects.all().prefetch_related('kpis_set').order_by('display_name') kpis = Kpis.objects.select_related('domain_id').values('id', 'display_name', 'number_display_format', 'description', 'calculation_type').order_by('display_name') for domain in domains_list: # For each domain, get all related KPIs domain_kpis = kpis.prefetch_related('domain_id').filter(domain_id=domain.id).order_by('domain_display_order') final_list.append({'name':domain.name, 'display_name':domain.display_name, 'description':domain.description, 'kpis':domain_kpis}) context = {'domains_and_kpis_data':final_list} return render(request, 'tests_details/domains_kpis_descriptions.html', context=context) And my HTML template <div class="row"> <div class="col-lg-3 col-xlg-2 col-md-4"> <div class="stickyside"> <h3> Domains … -
Django settings settings module programmatically at runtime based on environment
I have a dev and prod environment, I am trying to programmatically assign the settings module based on an environment variable DEV so fat my settings have the following structure: project --settings ----__init__.py ----common.py ----dev.py ----prod.py inside my __init__.py I have: import os if os.environ['DEV_ENV']: os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings.dev' else: os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings.prod' However, when I run python3 manage.py migrate I get this error: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. however if I run with --settings flag manually, it works python3 manage.py migrate --settings=project.settings.dev -
Django Foreign key to not loaded object
Hello I have a problem that I want to link foreign key to model's related object in other words I want to link foreign key to not loaded object's fields. class Category(models.Model): ... filter_option_content_type = models.ForeignKey(ContentType, on_delete=models.SET_NULL, limit_choices_to=( models.Q(app_label='catalog', model='FrameSize') | models.Q(app_label='catalog', model='ShoeSize') | models.Q(app_label='catalog', model='ClothSize') ), null=True) ... class Product(models.Model): ... category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) ... class ProductItem(models.Model): ... model = models.ForeignKey(Product, verbose_name='Модель', on_delete=models.CASCADE, related_name='productitem') size = models.ForeignKey('model.category.filter_option_content_type', on_delete=models.SET_NULL, null=True) ... And sure i got this error: ValueError: Invalid model reference 'model.category.filter_option_content_type'. String model references must be of the form 'app_label.ModelName' is it possible to do relation like this wtihout using GenericForeignKey instead of ForeignKey? -
How do i remove html tags in tinymce
How do I remove HTML tags which show in my browser as a result of being entered in the django administration using timymce -
google-analytics with proxy server on apache2 and django
i have googled a lot for last few days. but i couldn't find a appropriate solution. my website uses google analysis as commonly used. but ad-blockers seems to blocking it. my code <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=G-4RPCXXXXX"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'G-4RPCXXXXX'); </script> while researching i found many articles about CNAME cloacking and server proxy with node.js. can someone guide me with apache proxying or maybe a way around with django for google-analytics. or am i missing something? -
In Django I cant retrieve the fields of values of Upload cv, gender, status but the other fields are working fine which is full name
This is my edit.html code and during retrieving the values from database it shows only the text fields like value={{ i.full_name}} but when I am writing value={{ i.cv}}, value={{ i.status}}, value={{ i.gender}} it does not shows the value which needs to bed edited I have two choice fields and one file field. this is my edit.html <section class="site-section"> <div class="container"> <div class="row"> <div class="col-lg-12 mb-5"> <h2 class="mb-4 text-center">Update Candidate Details</h2> <form method="POST" action="/update/ {{i.id}}/" enctype="multipart/form-data" class="p-4 border rounded" onsubmit="myFunction()" > {% csrf_token %} {% comment %} <input type="hidden" name="csrfmiddlewaretoken" value="UabxqpD8HGPOu1ZSFnIHAPbMtRgWBAnVHEs8bLDx0HnxN6uhG3LyYvZShvcx1ekn"> {% endcomment %} <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="full_name">Full Name :</label> <input type="text" class="form-control" value ={{ i.full_name}} name="full_name" id="id_full_name" placeholder="Enter First Name"> </div> </div> <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="recruiter_name">Recruiter Name :</label> <input type="text" class="form-control" value ={{ i.recruiter_name }} name="recruiter_name" id="id_recruiter_name" placeholder="Enter Recruiter Name"> </div> </div> {% comment %} <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="id_last_name">Last Name :</label> <input type="text" class="form-control" name="last_name" id="id_last_name" placeholder="Enter Last Name"> </div> </div> {% endcomment %} <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="email">Email :</label> <input type="email" class="form-control" value ={{i.email }} name="email" id="id_email" placeholder="Enter Email"> </div> </div> <div class="row form-group"> <div class="col-md-12 … -
DockerHub: Incorrect copying of files
I am trying to upload a Django app to Docker Hub. On local machine (Ubuntu 18.04) everything works fine, but on Docker Hub there is an issue that the requirements.txt file cannot be found. Local machine: sudo docker-compose build --no-cache Result (it's okay): Step 5/7 : COPY . . ---> 5542d55caeae Step 6/7 : RUN file="$(ls -1 )" && echo $file ---> Running in b85a55aa2640 Dockerfile db.sqlite3 hello_django manage.py requirements.txt venv Removing intermediate container b85a55aa2640 ---> 532e91546d41 Step 7/7 : RUN pip install -r requirements.txt ---> Running in e940ebf96023 Collecting Django==3.2.2.... But, Docker Hub: Step 5/7 : COPY . . ---> 852fa937cb0a Step 6/7 : RUN file="$(ls -1 )" && echo $file ---> Running in 281d9580d608 README.md app config docker-compose.yml Removing intermediate container 281d9580d608 ---> 99eaafb1a55d Step 7/7 : RUN pip install -r requirements.txt ---> Running in d0e180d83772 [91mERROR: Could not open requirements file: [Errno 2] No such file or directory: 'requirements.txt' Removing intermediate container d0e180d83772 The command '/bin/sh -c pip install -r requirements.txt' returned a non-zero code: 1 app/Dockerfile FROM python:3.8.3-alpine ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /code COPY . . RUN file="$(ls -1 )" && echo $file RUN pip install -r requirements.txt docker-composer.yml version: '3' services: web: … -
Error while trying to communicate between django and postgresql inside a docker
I've deployed Django+Vue application on server and changed psql ports from "5432:5432" to "5433:5433" because I'm running other applications on this server and this port is already in use, now I have a problem when making api requests, the error is: Is the server running on host "db" (ip) and accepting backend | TCP/IP connections on port 5433? When I'm doing docker-compose up db service is saying: db | 2021-05-08 11:52:02.547 UTC [1] LOG: starting PostgreSQL 13.2 (Debian 13.2-1.pgdg100+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 8.3.0-6) 8.3.0, 64-bit db | 2021-05-08 11:52:02.547 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 db | 2021-05-08 11:52:02.547 UTC [1] LOG: listening on IPv6 address "::", port 5432 db | 2021-05-08 11:52:02.551 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" db | 2021-05-08 11:52:02.555 UTC [27] LOG: database system was shut down at 2021-05-08 11:51:10 UTC db | 2021-05-08 11:52:02.560 UTC [1] LOG: database system is ready to accept connections It says that it listening on port 5432, while my docker-compose.yaml is: version: "3.8" services: backend: container_name: backend build: context: ./mkstat_backend dockerfile: Dockerfile volumes: - static:/app/static - media:/app/media env_file: - ./mkstat_backend/.env.prod depends_on: - db networks: - backdb db: container_name: db build: context: … -
Django, how to create accounts just by importing a user list
I'm currently working on an LMS. I have a list of student in an excel file, but I want to create an account for students at the time I have uploaded the file to the system, and then the students should be forced to edit the username and password Is it possible to do that with Django? -
What does PYTHONUNBUFFERED in Dockerfile do?
I'm just getting started with docker, and I've been seeing a PYTHONUNBUFFERED environment variable in every Dockerfile for python. Can anyone kindly explain what it actually is? -
Cannot parse FormData into django backend
hope you all are doing well I have been working on a custom form that I want to send to django backend via ajax request, the only problem that I am encountering is I am wrapping the form into FormData it works well on the frontend site but on the backend it shows a querydict with some strane data in it and making it much harder to parse the data, if there can be a way to easily get the data out. Any leads or any response is much appreciated Following is my code of the javascript function that sends the data to the backend Javascript function Edit_Content(e){ var form_data=new FormData(document.querySelector("#edit-form")) let csrftoken=getCookie("csrftoken") $.ajax({ url:"{% url 'EditPost' %}", method:"post", datatype:"json", processData:false, "headers":{ "X-CSRFToken":csrftoken }, data:form_data, success:function (data){ console.log("Post or idea edited") } }) } views.py def Edit(request): print(request.POST,request.FILES) data=dict(request.POST) print(data) if data["type"] == "post": post=Post.objects.get(pk=data['id']) content=data.get("post-content",None) media=data.get("media",None) post.edit(content,media) else: idea=Idea.objects.get(pk=data["id"]) title=data.get("title",None) privacy=data.get("privacy",None) requirements=data.get("requirements",None) category=data.get("category",None) content=data.get("idea-content",None) media=data.get("media",None) idea.edit(requirements,title,privacy,category,content,media) return HttpResponse(status=200) After converting request.POST into dictionary object it it gives {'------WebKitFormBoundaryW30RtYeVz4cXnUNf\r\nContent-Disposition: form-data; name': ['"type"\r\n\r\nidea\r\n------WebKitFormBoundaryW30RtYeVz4cXnUNf\r\nContent-Disposition: form-data; name="id"\r\n\r\n1\r\n------WebKitFormBoundaryW30RtYeVz4cXnUNf\r\nContent-Disposition: form-data; name="title"\r\n\r\nProgramming is great\r\n------WebKitFormBoundaryW30RtYeVz4cXnUNf\r\nContent-Disposition: form-data; name="privacy"\r\n\r\n public\r\n------WebKitFormBoundaryW30RtYeVz4cXnUNf\r\nContent-Disposition: form-data; name="requirements"\r\n\r\nnothing\r\n------WebKitFormBoundaryW30RtYeVz4cXnUNf\r\nContent-Disposition: form-data; name="category"\r\n\r\nFisica\r\n------WebKitFormBoundaryW30RtYeVz4cXnUNf\r\nContent-Disposition: form-data; name="idea-content"\r\n\r\nProgramming is not for kids\r\n------WebKitFormBoundaryW30RtYeVz4cXnUNf\r\nContent-Disposition: form-data; name="media"; filename=""\r\nContent-Type: application/octet-stream\r\n\r\n\r\n------WebKitFormBoundaryW30RtYeVz4cXnUNf--\r\n']} Which is hard to parse … -
Replacing static site with Django/Serving static files with mod_wsgi
I have an existing static website that is served via apache. I wanted to add dynamic features to that site so I created a Django app that lives in a subfolder (ie. /django-site/). I have this configured like this: WSGIDaemonProcess django_site processes=5 threads=5 user=user group=group python-home=path/to/virtualenv WSGIScriptAlias /django-site /var/www/django_site/wsgi.py <Location /django-site> WSGIProcessGroup group </Location> But now I would like to replace certain pages that were originally static pages in the root directory. But I don't want to replace all of the static pages. I know that Django recommends putting your static files in a subdirectory like /media or /static and Django configured to be the root directory but since I have a long legacy of these static pages being in the root directory and external links to these pages I don't want to change that. Is there a recommended way to replace these static pages with a dynamic ones? Here are a few ideas that I have thought of: Use ProxyPass to replace pages one at a time Redirect static pages to dynamic versions, change internal links to new dynamic version Move dynamic site to root, and use something like whitenoise to serve those files -
Can you figure this out, i have no idea why there's error
sqlite> CREATE TABLE flights( id int NOT NULL, origin_id, destination_id, duration, PRIMARY KEY (id), FOREIGN KEY (id), REFERENCES (flight) ); Error: near ",": syntax error -
how to make work adsense on django web app
i'm trying to config google adsense on my django app but i can't activate my account because of my website has no content. my app is a repository to find videos or music creators which aren't famous. i have 80 creators in my database and i show them on 8 pages of my website. so that's surprised me when i've seen no content website... did somebody can tell to me if my website is maybe too empty for google adsense ? yufinder.com (my site is in french for the moment) does google has an approach to install adsense on django app ? because i don't find anything. maybe did i need to config something in my django app ? for the moment i've only had de script tag that google gave to me in my main html file but i've seen on other forums that maybe i need to install "django-ads" or something called sekizai but i haven't found a lot of informations about. if you need any informations i'll give you. thank you for helping me -
Get all files of a model in Django Shell
Is it possible to output names of all fields of a specific model in Django Shell? For example, how to get fields from User model": >>> from django.contrib.auth.models import User