Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Periodically refresh placeholder and canvas tag in Django template
I have a template that, among other things, displays a current market price through a placeholder, i.e., {{ market.current_price }}, and an accompanying price graph using ChartJS, rendered in the template in a canvas tag, <canvas id="myChart"></canvas>. My question: since the market price changes as different users engage with the underlying market, is there a straightforward way to periodically (say, every 10 seconds) refresh the placeholder and chart in the template, to make sure each user is looking at the most recent price/graph? I'm trying to avoid having to refresh the entire page, if at all possible. If it makes any difference, the chart is rendered through Ajax, as follows: {% block jquery %} var endpoint = "{% url 'chart_data' market.id %}" var defaultData = [] var labels = [] $.ajax({ method: "GET", url: endpoint, success: function(data){ defaultData = data.prices price_array_length = defaultData.length + 1 labels = data.price_dates var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'line', data: { labels: labels, datasets : [{ label: 'Market price', data: defaultData, backgroundColor: [ 'rgba(54, 162, 235, 0.2)', ], borderColor: [ 'rgba(54, 162, 235, 1)', ], borderWidth: 2 }] }, options: { scales: { yAxes: [{ ticks: { suggestedMin: 0, … -
MP4/AVI videos are not playing on safari browser : Django 2
I create one web application using django 2.1 and python3 and in my requirements is upload video and play video and its absolutely working excellent dynamically and static in all browser except safari browser I have already tried everything in html tag (video,autoplay,muted,loop playsinline,controls,type="video/mp4") etc... everything but still not playing video in safari browser. my all python logic view + model files code is perfect and working and getting excellent output in all browser except safari browser. I have already checked all inspect elements and path,all videos path are placed in right place. <html> <head> <meta charset="utf-8"> </head> <body> <div class="left-video-div"> <video autoplay muted loop playsinline controls width="320" height="240" class="video-background "> <source src="{% static "sample_test01.mp4" %}" type="video/mp4"> </video> <video autoplay muted loop playsinline controls width="320" height="240" class="video-background "> <source src="{% static "sample_test02.mp4" %}" type="video/mp4"> </video> <video autoplay muted loop playsinline controls width="320" height="240" class="video-background "> <source src="{% static "sample_test03.mp4" %}" type="video/mp4"> </video> <video autoplay muted loop playsinline controls width="320" height="240" class="video-background "> <source src="/media/static/clips/userid_420/2019-07-15_182035.991933_Test_Video_02.mp4" type="video/mp4"> </video> </div> <p><strong>Note:</strong> The video tag is not supported in Internet Explorer 8 and earlier versions.</p> </body> </html> I expect the output all static and dynamic video playing in safari browser but its not working. -
provide me solution for toaster notification box in ajax
I am trying to use toaster function in ajax to display notification ,but it is not working .please help me since I knew little about js. please give me proper code. -
could not install the packages using pipenv when using docker
I am setting up a project using cookiecutter-django with pipenv instead. I am trying to use docker however I am getting the error as ERROR: Service 'django' failed to build: The command '/bin/sh -c pipenv install' returned a non-zero code: 1. To run the docker i used the following command docker-compose -f local.yml up -d Here is my docker file local.yml version: '3' volumes: local_postgres_data: {} local_postgres_data_backups: {} services: django: &django build: context: . dockerfile: ./compose/local/django/Dockerfile image: tryavel_local_django depends_on: - postgres - mailhog volumes: - .:/app env_file: - ./.envs/.local/.django - ./.envs/.local/.postgres ports: - "8000:8000" command: /start postgres: build: context: . dockerfile: ./compose/production/postgres/Dockerfile image: tryavel_production_postgres volumes: - local_postgres_data:/var/lib/postgresql/data - local_postgres_data_backups:/backups env_file: - ./.envs/.local/.postgres mailhog: image: mailhog/mailhog:v1.0.0 ports: - "8025:8025" redis: image: redis:5.0 celeryworker: <<: *django image: tryavel_local_celeryworker depends_on: - redis - postgres - mailhog ports: [] command: /start-celeryworker celerybeat: <<: *django image: tryavel_local_celerybeat depends_on: - redis - postgres - mailhog ports: [] command: /start-celerybeat flower: <<: *django image: tryavel_local_flower ports: - "5555:5555" command: /start-flower compose/local/django/Dockerfile FROM python:3.7-alpine ENV PYTHONUNBUFFERED 1 RUN apk update \ # psycopg2 dependencies && apk add --virtual build-deps gcc python3-dev musl-dev \ && apk add postgresql-dev \ # Pillow dependencies && apk add jpeg-dev zlib-dev freetype-dev lcms2-dev … -
Django Oauth2 Configuration
I have two databases for one for separate django project and another for open edx project and I want to connect it with Oauth2, but not able to get the user status like user is super user or staff user from open edx database. can someone help me with this problem? -
Update Form Not Submitting
I am trying to update the fields of a model using fbv and I created different forms for those fields too. But still, I cannot submit the form no matter what. I think the problem is with image field and the form does not render to be valid. Is there a sloution for it? models.py class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE, default=None, null=True) role = models.CharField(max_length=50, choices=Roles) verified =models.BooleanField(default = False,blank=True) photo = models.ImageField(upload_to='images', blank=True, default='default/testimonial2.jpg') slug = models.SlugField(unique=False, blank=True) def save(self, *args, **kwargs): self.slug = slugify(self.user.username) super(UserProfile, self).save(*args, **kwargs) def __str__(self): return self.user.username def get_absolute_url(self): if (self.verified==True): return reverse("NewApp:mail", kwargs={'pk': self.pk}) else: return reverse("NewApp:userlist") views.py def UserUpdateView(request,slug): object = User.objects.get(username=request.user) user_form = UserUpdateForm(instance=object) obj = UserProfile.objects.get(slug=request.user) profile_form = UserProfileForm(instance=obj) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() return redirect('NewApp:logindex') return render(request, 'NewApp/userprofile_form.html', {'user_form': user_form, 'profile_form': profile_form,}) -
how does django-rest-auth handle the expiration of facebook access tokens
I am using django-rest-auth for authentication for my django rest server and I am using the access token given by facebook to login. django-rest-auth in turn gives me a key to use for authentication on the server. My question arouse when I realized that the access keys that are given by facebook expire, so I am having trouble finding out if the new access key given by facebook will result in the same key given by django-rest-auth or if I need to build a system to handle this fact -
Charts not displayed in django admin view?
I am trying to display some charts in my admin view( by extending admin/base.html) and I want to use a template instead of libraries such as charts.Js to display them. I want my view to be like the following (https://colorlib.com/polygon/cooladmin/index.html). Github repo here (https://github.com/puikinsh/CoolAdmin). However, in my case no charts are being displayed. I have integrated all files and folders( containing static files) and set all dependencies correctly andhe main.js(contains code for charts) are also working. Extract from main.html(includes links) <div id="content-main" class="main-content container-fluid"> <div class="section__content section__content--p30"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <div class="overview-wrap"> <h2 class="title-1">overview</h2> <button class="au-btn au-btn-icon au-btn--blue"> <i class="zmdi zmdi-plus"></i>add item</button> </div> </div> </div> <div class="row m-t-25"> <div class="col-sm-6 col-lg-3"> <div class="overview-item overview-item--c1"> <div class="overview__inner"> <div class="overview-box clearfix"> <div class="icon"> <i class="zmdi zmdi-account-o"></i> </div> <div class="text"> <h2>10368</h2> <span>members online</span> </div> </div> <div class="overview-chart"> <canvas id="widgetChart1"></canvas> </div> </div> </div> </div> </div> </div> </div> </div> <!-- Jquery JS--> <script src={% static 'hfs_admin/vendor/jquery-3.2.1.min.js' %}""></script> <!-- Bootstrap JS--> <script src={% static 'hfs_admin/vendor/bootstrap-4.1/popper.min.js' %}""></script> <script src={% static 'hfs_admin/vendor/bootstrap-4.1/bootstrap.min.js' %}""></script> <!-- Vendor JS --> <script src={% static 'hfs_admin/vendor/slick/slick.min.js' %}""> </script> <script src={% static 'hfs_admin/vendor/wow/wow.min.js' %}""></script> <script src={% static 'hfs_admin/vendor/animsition/animsition.min.js' %}""></script> <script src={% static 'hfs_admin/vendor/bootstrap-progressbar/bootstrap-progressbar.min.js' %}""> </script> <script src={% static 'hfs_admin/vendor/counter-up/jquery.waypoints.min.js' %}""></script> <script … -
Users cannot update profile info
I'm trying to let users change their profile information but instead of changing the existing profile, form.save() saves it as a new entry under the same user. (example, bio would say 'What's up', they go to edit and no visible info is changed but another set of info is put in my userprofile table.) I tried using SQL commands and it returned something about an error near 'IT', which isn't in my code. I've tried getting my user.profile and then trying to edit the info through that (i.e user.profile.sex = form.cleaned_data['sex']). I've looked through the docs and the only thing I found that makes sense is Model.save(force_update=True) but where would I put it in my view and how could I link it to the user? View with the SQL I tried... @login_required def edit_prof(request): if request.method == 'POST': form = EPIF(request.POST, instance=request.user) if form.is_valid(): user_id = request.user.id conn = sqlite3.connect('db.sqlite3') cur = conn.cursor() sex = form.cleaned_data['sex'] dob = form.cleaned_data['dob'] r_stat = form.cleaned_data['relationship_stat'] locale = form.cleaned_data['location'] bio = form.cleaned_data['bio'] cur.execute(''' UPDATE profs_customuserprofile SET sex = {}, dob = {}, relationship_stat = {}, location = {}, bio = {} WHERE ID = {}; '''.format(sex, dob, r_stat, locale, bio, user_id)) content = form.save(commit=False) … -
Server error 500 when deploy django to Heroku
I got following server error 500 when deploying django app to heroku. I have worked on this problem for 2 days to fix, but have no idea to solve the problems. I assume djangorestframework cause this problems because it has favicon.ico which leads "GET /favicon.ico HTTP/1.1" 404 77" but no idea. Does anyone detect issues? Thank you for your support in advance!! 2019-07-23T12:03:44.622777+00:00 app[api]: Release v23 created by user atnihs-do-21@hotmail.co.jp 2019-07-23T12:03:51.865737+00:00 heroku[web.1]: Starting process with command `gunicorn alumate.wsgi --log-file -` 2019-07-23T12:03:55.314454+00:00 heroku[web.1]: State changed from starting to up 2019-07-23T12:03:55.130912+00:00 app[web.1]: [2019-07-23 12:03:55 +0000] [4] [INFO] Starting gunicorn 19.9.0 2019-07-23T12:03:55.132168+00:00 app[web.1]: [2019-07-23 12:03:55 +0000] [4] [INFO] Listening at: http://0.0.0.0:20191 (4) 2019-07-23T12:03:55.132311+00:00 app[web.1]: [2019-07-23 12:03:55 +0000] [4] [INFO] Using worker: sync 2019-07-23T12:03:55.138103+00:00 app[web.1]: [2019-07-23 12:03:55 +0000] [10] [INFO] Booting worker with pid: 10 2019-07-23T12:03:55.150027+00:00 app[web.1]: [2019-07-23 12:03:55 +0000] [11] [INFO] Booting worker with pid: 11 2019-07-23T12:03:55.000000+00:00 app[api]: Build succeeded 2019-07-23T12:04:30.649490+00:00 heroku[router]: at=info method=GET path="/" host=alumate.herokuapp.com request_id=0f1e339a-08fc-4b93-9c1b-1db28b675f76 fwd="210.150.77.215" dyno=web.1 connect=1ms service=835ms status=500 bytes=234 protocol=https 2019-07-23T12:04:30.649933+00:00 app[web.1]: 10.99.197.226 - - [23/Jul/2019:12:04:30 +0000] "GET / HTTP/1.1" 500 27 "https://dashboard.heroku.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36" 2019-07-23T12:04:31.116073+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=alumate.herokuapp.com request_id=381749d5-0137-4017-bd1b-8bb8cb6feef1 fwd="210.150.77.215" dyno=web.1 connect=0ms service=186ms status=404 bytes=258 protocol=https … -
i'm having problem of accessing object in array with template language
{% for number in appliers|length|times %} {% if connector|get_by_index:number == commission.id %} {{appliers|get_by_index:number}} {% endif %} {% endfor %} i have made custom_template filter and it have worked great but the problem is that i can't access appliers[number]'s class variables. I tried accessing by {{appliers|get_by_index:number.email}} and it wouldn't work... please can any one can tell me how to solve this? -
How to delete all the files associated with the users when I delete the user
I am trying to make an web application in Django.Here I have created different fields in user model including profile picture and other pictures.When I delete a user,the files associated with the user doesn't get deleted.I want to delete the files,profile picture and other pictures when I delete the user. I am using django2.2 and I have customized my own user model and admin panel. In my user model I have added 'Profile Picture' field and 'CV' field. When I add a user in my model the profile picture are stored in 'Media/"%username/"' directory.I want to delete the files associated with the user when I delete the user.So I have written 'on_delete=..' in the () of username but it gives an error.So is there any possible way to do it? import .. import os def user_directory_path(instance, filename): return os.path.join('media', instance.username, filename) class User(AbstractBaseUser): username = models.CharField(max_length=200, unique=True, on_delete = os.remove(str(user_directory_path))) profile_photo = models.ImageField(default='media/download(1).png', upload_to = user_directory_path) cv = models.FileField(upload_to = user_directory_path) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) moderator = models.BooleanField(default=False) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) I wanted to delete the files this way username = models.CharField(max_length=200, unique=True, on_delete = os.remove(str(user_directory_path))) but some errors come -
Django Media Files during development
How can I serve media files during development? The 'image' attribute has no file associated with it. When I try to upload a new file, I get this error: SuspiciousFileOperation at /admin/accounts/userprofile/4/change/ The joined path (/media/me.jpg) is located outside of the base path component (/home/django/django_project/static-serve/media) models.py image = models.ImageField(upload_to='/media',blank=True) urls.py ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py MEDIA_ROOT = '/home/django/django_project/static-serve/media/' MEDIA_URL = 'media/' -
Python Django - Show all assigned objects on the web page
I am developing web app for tracking orders. And I would like to display all orders which were created by a user via detailView. models.py class Order(models.Model): ... user = models.ForeignKey(MyUser, on_delete=models.CASCADE) order_number = models.CharField(max_length=150) class MyUser(models.Model): eid = models.CharField(max_length=7) name = models.CharField(max_length=150) surname = models.CharField(max_length=150) views.py class UserDetailView(generic.DetailView): model = MyUser template_name = "database/user_detail.html" def get_queryset(self): return Order.objects.all().order_by("-id") user_detail.html {% extends "base.html" %} {% block content %} <body> <h1> {{ user.eid }} {{ user.name }} {{ user.surname }} </h1> {% for order in orders %} order.order_number {% endfor %} {% endblock %} With this code I receive error: page not found: No Order found matching the query. If i delete the def get_queryset() in the views.py, it shows only the users eid and name. Not sure how I can get all the assigned orders to the particular user. -
Upon login redirection is not happening django
On my localhost (127.0.0.1:8000) i have configured a Login page and upon login its not redirecting to "Automation page (form_name_view". Note:- when i click login button nothing it happening whether with right credentials or wrong. In views.py from django.contrib.auth import authenticate,login,logout # Create your views here. def login_view(request): context = {} if request.method == "post": username = request.post['username'] password = request.post['password'] user = authenticate(request, username=username, password=password) if user: login(request, user) return HttpResponseRedirect(reverse('IP form')) else: context["error"] = "Provide valid credentials" return render (request,"first_app/login.html", context) else: return render (request,"first_app/login.html", context) def form_name_view(request): #this is the view to which i want to redirect if request.method == "POST": #some code In Models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Login(models.Model): username = models.CharField(max_length=50,) password = models.CharField(max_length=32,) def __str__(self): return self.user.Username In admin.py from django.contrib import admin from first_app.models import Login # Register your models here. admin.site.register(Login) In login.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Login</title> </head> <body> <h1> Please Login</h1> <form method="post"> {% csrf_token %} <table> <tr> <td><label for="username">Enter username: </label></td> <td><input type="text" name="username" id="username" required></td> </tr> <tr> <td><label for="username">Enter password: </label></td> <td><input type="password" name="password" id="password" required></td> </tr> <p> {{ error }} </p> </table> <input type="submit" … -
How to fix "AttributeError: module has no attribute 'wsgi' " in wfastcgi
I try to set up my django 2.2.2 project 'WebGUI' on IIS 10 (Windows Server 2019), but sadly i cant get it to work. wfastcgi is installed and enabled, I created a web.config and declared a python fastcgi handler in there. the keys should be correct and as far as i know thats all i'm supposed to configure. the web.config: <configuration> <system.webServer> <handlers> <add name="Python FastCGI" path="*" verb="*" modules="FastCgiModule" scriptProcessor="c:\python\python37-32\python.exe|c:\python\python37-32\lib\site-packages\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" /> </handlers> </system.webServer> <appSettings> <!--Required Settings--> <add key="WSGI_HANDLER" value="WebGUI.wsgi.application" /> <add key="PYTHONPATH" value="C:\inetpub\wwwroot\WebGUI" /> <add key="WSGI_LOG" value="d:\wfastcgi.log" /> <add key="DJANGO_SETTINGS_MODULE" value="WebGUI.settings" /> </appSettings> </configuration> my settings.py says WSGI_APPLICATION = 'WebGUI.wsgi.application' and my wsgi.py: from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'WebGUI.settings') application = get_wsgi_application() Error occurred while reading WSGI handler: Traceback (most recent call last): File "c:\python\python37-32\lib\site-packages\wfastcgi.py", line 791, in main env, handler = read_wsgi_handler(response.physical_path) File "c:\python\python37-32\lib\site-packages\wfastcgi.py", line 633, in read_wsgi_handler handler = get_wsgi_handler(os.getenv("WSGI_HANDLER")) File "c:\python\python37-32\lib\site-packages\wfastcgi.py", line 603, in get_wsgi_handler handler = getattr(handler, name) AttributeError: module 'WebGUI' has no attribute 'wsgi' StdOut: StdErr: -
Django password-reset-confirm not working
I want to implement the Django reset password function but it gets stuck when it tries to sent the email. Error code: Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. error-code-picture I´ve tried the form with crispy and I´ve tried to let Django do it all alone (without my views) but it´s not working. urls: path('password-reset/', auth_views.PasswordResetView.as_view(template_name='web/users/password_reset.html'), name='password_reset'), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='web/users/password_reset_done.html'), name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='web/users/password_reset_confirm.html'), name='password_reset_confirm'), password-reset-confirm view (just the form): <form method="POST"> {% csrf_token %} <div class="form-group"> {{ form.email }} <label for="username" class="control-label">Email</label><i class="bar"></i> </div> <div class="button-container"> <input type="submit" class="button" value="Passwort ändern"/> </div> </form> I think the problem is that it´s not passing the uidb64 and the token to the email template. -
How to upload a list of files in database using django?
I want to upload multiple files in django that needs to be stored in a specific folder and the path of those files to be kept in the database. That field should also a no file option if the user does not want to upload any file. I am unable to find any solution to the above stated problem. def post(self, request, *args, **kwargs): print('req :', request.data) token = request.headers['authorization'] data = {'token': token} payload_decoded = jwt.decode(token, settings.SECRET_KEY) try: valid_data = VerifyJSONWebTokenSerializer().validate(data) user = valid_data['user'] self.request.user = user except ValidationError as v: print("validation error", v) serializer = QuestionsSerrializer(data=request.data) oa = Questions.objects.filter(user = user).values('outside_asset') if serializer.is_valid(raise_exception=True): serializer.save(user=self.request.user) form = UploadForm(request.POST, request.FILES) if form.is_valid(): for each in form.cleaned_data['outside_asset']: form = Questions.objects.create(user=user, outside_asset=each) form_data = form.save() form_data.save(user=self.request.user) return Response({'msg': 'Request Accepted'}, status=status.HTTP_200_OK) else: return Response({'msg': 'Invalid data'}, status=status.HTTP_400_BAD_REQUEST) The files received in request should be saved to a specific folder and their path should be stored in a single field in database -
Django view unit test conflict with custom template tag
I create a custom templatetag for my django project that returns an image url as favicon # myapp/templatetags/customtags.py @register.simple_tag def get_shop_favicon(): ''' get shop favicon ''' return Shop.objects.first().favicon.url and use it in base.html like this <!doctype html> {% load storefront_tags %} <head> <link rel="icon" href="{% get_shop_favicon %}" type="image/png" sizes="16x16"> </head> <body> ... </body> this part works great but after create test function to testing my view got an AttributeError as follow AttributeError: 'NoneType' object has no attribute 'favicon' and this is my test class # test.py from django.test import TestCase from django.urls import reverse class ProductViewTest(TestCase): ''' testing product views and urls ''' def test_get_product_list_status_code(self): ''' test to get all products ''' url = reverse('prodcuts') # url name response = self.client.get(url) self.assertEqual(response.status_code, 200) Note: with out template tag it works well -
django_crontab CRONJOBS can't read app from apps
I'm using django1.9, crontab, python2.7. I'm constrained with python2.7 for some reasons. my setting about crontab is as follow: CRONJOBS = [ ('*/1 * * * *','myapp.process.order_process','>>/logs/orders.log') ] I'm trying to add crontab task using python manage.py crontab add but it return RunTime Error: RuntimeError: No job with hash d3e49affa727e41dd02184fcad40b787 found. It seems the crontab is out of sync with your settings.CRONJOBS. Run "python manage.py crontab add" again to resolve this issue! I realized the error is because crontab can't recognize myapp which is under the folder named apps, so I changed CRONJOBS settings to CRONJOBS = [ ('*/1 * * * *','apps.myapp.process.order_process','>>/logs/orders.log') ] It actually works! However, here comes the new issue. since I used two different ways to use myapp: one is using myapp directly, another is using apps.myapp (in CRONJOBS), crontab run returns error of model conflicting. In short, my question is what the setting of crontab should be like when my app in under the folder of apps? Many Thanks!!! -
How to get login time and logout time of multiple users/students using django views
So I have written a view for getting login time and logout time of a student. Now I want to perform the same procedure for n number of students so how should I do it? Here's my view: def timestamp(request): TodayStartdate = datetime.now().strftime("%Y-%m-%d") + " 00:00" TodayEnddate = datetime.now().strftime("%Y-%m-%d") + " 23:59" Attendance = Attendance.objects.filter(reader_Timestamp__range=(TodayStartdate, TodayEnddate)) Login = Timestamp.first() Logout = Timestamp.last() print(Login) print(Logout) return render(request, 'app/timestamp.html') -
How to create an empty file using apache user in django or python instead of actual user of server
I need to create an empty file when createEmptyFile() is triggered in UI. But it is giving error "touch: cannot touch 'hello.txt': Permission denied" because instead of creating file with actual user (actualuser), it is creating with apache user This is a django app using apache server, and using 'os' module and with 'touch' command i need to create file def createEmptyFile(): print getpass.getuser() os.system('touch hello.txt') I expect file to be created but it is giving "touch: cannot touch 'hello.txt': Permission denied" because of file is creating using another user(apache) instead of actual user(anotheruser) Output: apache touch: cannot touch 'hello.txt': Permission denied -
How to use "create" model manager method on model without 'id' key
I have defined a django model as below: class MyModel_1(models.Model): ref_1 = models.ForeignKey(MyModel_2, on_delete=models.CASCADE) ref_2 = models.ForeignKey(MyModel_3, on_delete=models.CASCADE) class Meta: db_table = 'my_model_1' unique_together = (('ref_1 ', 'ref_2 '),) when i attempt to use a create() method on the model i get the below error: *** django.db.utils.ProgrammingError: column MyModel_1.id does not exist LINE 1: ...ref_1_id", "ref_2_id") VALUES (1, 12) RETURNING "... Why is the create method attempting to insert an id column even though i have not created one with it.. -
how to serve media files in django app nginx server?
I am testing my django app in production mode (debug=false) using nginx, gunicorn, postgresql. Though I am able to render static files, I am unable to access files stored in 'media' folder. In my settings.py following are the variables set: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # also tried another combination: MEDIA_ROOT = 'media' Also in urls.py the MEDIA_ROOT settings are as follows: urlpatterns = [ path('admin/', admin.site.urls), path('venter/', include('appname.urls')), ]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) And in my /etc/nginx/sites-available/ file I have the following settings: server { listen 80; server_name website.com www.website.com ; location = /favicon.ico { access_log off; log_not_found off; } location /static { root /home/a/btawebsite; } location = /media/ { root /home/a/btawebsite; } location / { include proxy_params; proxy_pass http://unix:/home/a/myproject.sock; } } However while rendering the xlsx file stored in my django database as follows it throws me NOT found error. {{file.output_file.url}} I have tried every combination of configurations required for rendering MEDIA files but unable to achieve the outcome. Thanks. -
How to update the fields of a model in which user model is inherited with some fields of user model?
I am working on a problem where I need to update some fields of user model with one field of the model in which it is inherited. Using updateview with that model shows errors. How am I supposed to do it? thanks in advance. models.py class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE, default=None, null=True) role = models.CharField(max_length=50, choices=Roles) verified =models.BooleanField(default = False,blank=True) photo = models.ImageField(upload_to='images', blank=True, default='default/testimonial2.jpg') def __str__(self): return self.user.username views.py class UserUpdateView(UpdateView): fields = ('first_name','last_name','email','photo') model = UserProfile success_url = reverse_lazy("NewApp:logindex")