Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I automate this sendinblue api?
Trying to automate the adding of contacts to sendinblue's api. The example given on their site shows adding a email and then adding it to a list in your account. I have tried fstrings and .format(email, industry, role) but for some reason it keeps throwing back errors. Heres what their website shows which works. import requests url = "https://api.sendinblue.com/v3/contacts" payload = "{\"email\":\"someonesEmail97@gmail.com\",\"listIds\":[1,4],\"updateEnabled\":false}" headers = { 'accept': "application/json", 'content-type': "application/json" } response = requests.request("POST", url, data=payload, headers=headers Here's what I tried import requests url = "https://api.sendinblue.com/v3/contacts" payload = "{\"email\":\f"{email}"\",\"listIds\":[f"{industry}",f"{role}"],\"updateEnabled\":false}" headers = { 'accept': "application/json", 'content-type': "application/json" } response = requests.request("POST", url, data=payload, headers=headers) I want this in the signup part of my site so it will grab their email thats been authenticated and add it to the appropriate list that I have set up. But what I get back from using fstrings is invalid syntax in the terminal pointing to the email field. I then tried .format and that didn't show any errors on the terminal but on the webpage I got this error back payload = "{\"email\":\{}\",\"listIds\":[{},{}],\"updateEnabled\":false}".format(email, industry, role) KeyError at /accounts/signup/activate/ "'email'" points to line that the payload is on. What am I missing? Thanks for reading -
How to handle return render in django function
def url_filter(request,x): if x<10: url=request.path[1:-9] elif x<100: url=request.path[1:-10] elif x<1000: url=request.path[1:-11] else: url=request.path[1:-12] return url def form_valid(form,request,url): if form.is_valid(): form.save() if request.user.is_staff: messages.success(request, f''+url+' List has been updated!') else: messages.warning(request, f'You do not have Admin access!') else: print(form.errors) context={ "form":form, "form_name":url, } return render(request,'movies_list/list_create.html',context) @login_required def Award_list_update(request,award_id): obj=get_object_or_404(Award_list,award_id=award_id) url=url_filter(request,award_id) form=Create_Award_list_form( data=(request.POST or None), files=(request.FILES or None), instance=obj, ) form_valid(form,request,url) I want to use same template for multiple views so,i decleared a seprate function form_valid for this but i dont know how to handle the return render function. -
How to download a csv file from django docker container
I have an mounted django app using docker-compose. I also have generated a csv file in the server django app directory and inside the docker container. server django directory /restapi |*filename.csv |*app1 |*app2 inside docker container directory /django |*filename.csv |*app1 |*app2 i already tried setting up a static absolute path for both server and docker directory, but i still couldn't download the csv file. response = HttpResponse(content_type='text/csv') django_root_path = '/django' file_path = '{}/myfilename.csv'.format(django_root_path) logger.info(file_path) response['Content-Disposition'] = 'attachment; filename=file_path' response.write(u'\ufeff'.encode('utf8')) return response -
Django ValueError: Missing staticfiles manifest entry, but the manifest appears to show the entry
On a Django 1.11 app deployed to Heroku. When loading the root URL / (and I presume when Django gets to {% static 'angular/angular.min.js' %} in the homepage.html template) I get the following error: ValueError: Missing staticfiles manifest entry for 'angular/angular.min.js' File "django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "homepage/views.py", line 87, in homepage "latest_python3": Version.objects.filter(supports_python3=True).select_related("package").distinct().order_by("-created")[0:5] File "django/shortcuts.py", line 30, in render content = loader.render_to_string(template_name, context, request, using=using) File "django/template/loader.py", line 68, in render_to_string return template.render(context, request) File "django/template/backends/django.py", line 66, in render return self.template.render(context) File "django/template/base.py", line 207, in render return self._render(context) File "newrelic/api/function_trace.py", line 60, in dynamic_wrapper return wrapped(*args, **kwargs) File "django/template/base.py", line 199, in _render return self.nodelist.render(context) File "django/template/base.py", line 990, in render bit = node.render_annotated(context) File "django/template/base.py", line 957, in render_annotated return self.render(context) File "django/template/loader_tags.py", line 177, in render return compiled_parent._render(context) File "newrelic/api/function_trace.py", line 60, in dynamic_wrapper return wrapped(*args, **kwargs) File "django/template/base.py", line 199, in _render return self.nodelist.render(context) File "django/template/base.py", line 990, in render bit = node.render_annotated(context) File "django/template/base.py", line 957, in render_annotated return self.render(context) File "django/template/defaulttags.py", line 411, in render return strip_spaces_between_tags(self.nodelist.render(context).strip()) … -
Django category didn't work corrctly href not work
I have made a script to display all posts in a categroy so, when I try to open the single category it didn't open the page and show the article page, I've followed a tutorial for makeing this code, the link is: https://www.youtube.com/watch?v=o6yYygu-vvk . Can someone help me plz? Models.py from django.db import models from django import forms from django.contrib.auth.models import User from django.urls import reverse # Categorie class Category(models.Model): class Meta: verbose_name = 'category' verbose_name_plural = 'categories' name = models.CharField('Titolo', max_length = 250) slug = models.SlugField(max_length = 250, unique = True) desc = models.TextField('Descrizione', max_length=10000, blank=True) def get_absolute_url(self): return reverse("blog:CategoryList", args=[self.slug]) def __str__(self): return self.name # Articles class Article(models.Model): class Meta: verbose_name = 'Articolo' verbose_name_plural = 'Articoli' ''' Classe per creare articoli generali con media ''' title = models.CharField('Titolo', max_length=100) author = models.ForeignKey(User, on_delete=models.CASCADE,) category = models.ForeignKey (Category, on_delete=models.CASCADE) desc = models.CharField('Descrizione', max_length=10000, blank=True) text = models.TextField('Testo', max_length=10000, blank=True) image = models.ImageField('Foto', blank=True, upload_to="img") data = models.DateTimeField('Data di pubblicazione', blank=True) slug = models.SlugField(max_length = 250, null = True, blank = True, unique=True) class Meta: # Order post by date ordering = ['-data',] def __str__(self): return "Crea un nuovo articolo" Views.py from django.shortcuts import render, get_object_or_404 from django.shortcuts import render … -
type str doesn't define __round__ method/how to grab form fields ? django and cropper.js?
I have a Django form where users would upload images and sometimes crop only parts from it so I used cropper javascript to grab the coordinates but the problem is the data received is treated as strings here's how i grab data of the form /* SCRIPT TO COLLECT THE DATA AND POST TO THE SERVER */ $(".js-crop-and-upload").click(function () { var cropData = $image.cropper("getData"); $("#id_x").val(cropData["x"]); $("#id_y").val(cropData["y"]); $("#id_height").val(cropData["height"]); $("#id_width").val(cropData["width"]); $("#formUpload").submit(); }); Forms.py class ImageForm(ModelForm): x = forms.FloatField(widget=forms.HiddenInput()) y = forms.FloatField(widget=forms.HiddenInput()) width = forms.FloatField(widget=forms.HiddenInput()) height = forms.FloatField(widget=forms.HiddenInput()) class Meta: model = UploadedImages fields = ('pre_analysed', 'x', 'y', 'width', 'height', ) and this is how i get the data from the form if form.is_valid(): image = form.save(commit=False) x = request.POST.get('x') y = request.POST.get('y') w = request.POST.get('width') h = request.POST.get('height') but it always returns this error type str doesn't define round method so what i get is that I'm grabbing the data as strings instead of floats as it's saved in the form feild so how can i grab the data right ? -
Stripe Connect Express - Callback URI for Localhost Doesn't Seem to Work
I'm trying to set up a platform that uses Stripe, and since I need marketplace type of setup I'm using Connect, which does payments and payouts. I'm testing on local and the redirect URLs I've tried don't seem to work. After registering with Stripe, I'm still taken to their default redirect URI, which says: Congrats, you're almost done setting up your application! After connecting with Stripe, your users will be redirected to a page of your choosing (this is just the default). Make sure to change the test redirect URI under your application settings to something that makes sense on your own server (or localhost). However, I have tried all of these as redirect URIs in my Stripe Connect Dashboard, under the 'testing' option: http://localhost:8000/test-stripe/connect/default/oauth/test http://localhost:8000/test-stripe/oauth/callback http://localhost:8000/test-stripe/ These are supposed to be the URI that Stripe redirects back to on my site, with an added parameter at the end. Am I missing something? I find their documentation labyrinthine, as you have to click on link after link to get one part of their solution working, and then see if you can find your way back to where you left off. Maybe I missed something along the way. Thanks in advance … -
Channel Worker crash: how do some task?
For debugging purposes, I need to send an email when some Channel Workers stops for an error. I don't find a closure method in the SyncConsumer or AsyncConsumer. channels==2.2.0 channels-redis==2.4.0 -
How to use instance object with request.FILES and request.POST
views.py form=Create_Award_list_form(request.POST or None,instance=obj,request.FILES) if form.is_valid(): form.save() using request.FILES django doesn't let me to use instance object and using instance django doesn't let to use request.FILES. -
Cannot auth users in django
I have a problem with my code in django. I can't login user, I have form, display users but if i write password is ignored, there is any authentication and when i click submit button i go to next site with any authentication. And when entering a password user or not does not matter as if the password was not checked. I only see in comment in html all list users and their password from db when I do examine the login page. Please look at my code. login.html {{context.error}} {%else%} <form action="../logistics/choosework/" method="post"> {% csrf_token %} <select list="employees" id="opr_login" name="opr_login"> <option hidden="">Login</option> {% for login in peoples %} <option value="{{login.opr_login}}">{{ login.opr_name }} {{ login.opr_surname }}</option> {% endfor %} </select> <br> <input placeholder="Password" value="{{login.opr_pass}}" type="password" id="opr_pass" name="opr_pass"> <br> <input type="submit" value="login" /> </form> {% endif %} <hr> dbmodel_index.py class Peoples(models.Model): opr_login = models.CharField(db_column='OPR_LOGIN', primary_key=True, max_length=50) # Field name made lowercase. opr_name = models.CharField(db_column='OPR_NAME', max_length=255, blank=True, null=True) # Field name made lowercase. opr_surname = models.CharField(db_column='OPR_SURNAME', max_length=255, blank=True, null=True) # Field name made lowercase. opr_pass = models.CharField(db_column='OPR_PASS', max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'PEOPLES' views.py peoples = dbmodel_index.Peoples.objects.all() context={} if request.method == 'POST': opr_login = request.POST['opr_login'] opr_pass = … -
How to run django server and show it inside a NWjs application
I want to use Django Rest Framework to provide an API for saving data to a sqlite3 database, with the frontend made in React. And I want it to be a NW.js app. I have used succesfully Django and react. It works correctly. But when I try to save a file, it does not let the user choose a directory. It goes to the default "Downloads" in windows. The option to let the user choose a custom directory is something that can be done with NW.js. I used the file-saver and it saves the file but does not let the user choose a directory, wich is very important var FileSaver = require('file-saver'); var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"}); FileSaver.saveAs(blob, "hello world.txt"); I expect the user to be shown a window similar to the FileUpload type, but it just downloads it. -
Django findstatic: "No matching file found" but the file is there
On a Django 1.11 app deployed to Heroku. The Django management command findstatic is saying that it cannot find a file angular.min.js even though the file appears to be in a folder findstatic is checking. $ heroku run python manage.py findstatic --verbosity 2 angular.min.js Running python manage.py findstatic --verbosity 2 angular.min.js No matching file found for 'angular.min.js'. Looking in the following locations: /app/static /app/.heroku/python/lib/python3.6/site-packages/django/contrib/admin/static /app/.heroku/python/lib/python3.6/site-packages/django_extensions/static /app/.heroku/src/django-floppyforms/floppyforms/static /app/.heroku/python/lib/python3.6/site-packages/rest_framework/static $ heroku run ls /app/static/angular/ Running ls /app/static/angular/ angular.min.js controllers.js So it appears that angular.min.js is at /app/static/angular/. Why does findstatic not find it? Relevant part of settings.py: I followed Heroku's instructions for service Static Files with Django: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") STATIC_URL = "/static/" STATICFILES_DIRS = [os.path.join(BASE_DIR, "static"),] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', # ...others here too ] Also, whitenoise in requirements.txt Related questions that did not solve my problem: Django findstatic : No matching file found (STATICFILES_DIRS appears to me to be correctly set up) django findstatic not looking in every directory (In my situation, findstatic appears to be looking in the correct parent directory) -
Password Change URL in Django is accessible by directly entering URL, but fails when clicking on "Change Password" button
I am making a website based on William S. Vincent's "Django for Beginners." In the project I am building I have a homepage, with a drop-down menu that includes, among other options, a "Change Password" selection. When I go directly to the URL 127.0.0.1:8000/users/password_change/ I arrive at the correct page, but clicking the "Change Password" option gives me the following error: "Using the URLconf defined in newspaper_project.urls Django tried these URL patterns in this order: 1. admin/ 2. users/signup/ [name='signup'] 3. users/login/ [name='login']...11. articles/ 12. [name='home']. The current path, users/password_change/{% url 'password_change' %}. didn't match any of these." Below are the relevant sections of code: /Desktop/news/templates/base.html {% if user.is_authenticated %} <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link dropdown-toggle" href="#" id="userMenu"\ data-toggle="dropdown" aria-haspopup="true" aria-expanded\ ="false"> {{ user.username }} </a> <div class="dropdown-menu dropdown-menu-right"\ aria-labelledby="userMenu"> <a class="dropdown-item" href="{% url 'article_list' %}">Entries</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="{% url 'password_change' %}">Change password</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="{% url 'logout' %}"> Log Out</a> /Desktop/news/users/urls.py from django.urls import path from .views import SignUpView urlpatterns = [ path('signup/', SignUpView.as_view(), name='signup'), ] /Desktop/news/users/views.py from django.shortcuts import render from django.urls import reverse_lazy from django.views.generic import CreateView from .forms import CustomUserCreationForm class SignUpView(CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy('login') template_name = … -
ibm_db_dbi::ProgrammingError: Cursor cannot be closed; connection is no longer active
I am new with django and I am trying to set up db2 with it. I am following the documentation's steps in order to get this done. The database connection was done successfully but when I try to do this: (myproject) C:\Users\myuser\mysite>py manage.py shell (InteractiveConsole) >>> from polls.models import Choice, Question # Import the model classes we just wrote. # No questions are in the system yet. >>> Question.objects.all() Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\myuser\Envs\myproject\lib\site-packages\django\db\models\query.py", line 250, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "C:\Users\myuser\Envs\myproject\lib\site-packages\django\db\models\query.py", line 274, in __iter__ self._fetch_all() File "C:\Users\myuser\Envs\myproject\lib\site-packages\django\db\models\query.py", line 1242, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\myuser\Envs\myproject\lib\site-packages\django\db\models\query.py", line 55, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "C:\Users\myuser\Envs\myproject\lib\site-packages\django\db\models\sql\compiler.py", line 1136, in execute_sql cursor.close() File "C:\Users\myuser\Envs\myproject\lib\site-packages\ibm_db_dbi.py", line 1145, in close raise self.messages[len(self.messages) - 1] ibm_db_dbi.ProgrammingError: ibm_db_dbi::ProgrammingError: Cursor cannot be closed; connection is no longer active. I appreciate any help on this. Thanks in advance. I have tried to install ibm_db 3.0.1 and early versions and I get the same error. I have installed: python 3.7.4, django 2.2, ibm_db_django 1.2.0.0 and ibm_db 3.0.0 I expect this: # No questions are in the system yet. >>> Question.objects.all() <QuerySet []> -
How to avoid race conditions on celery tasks?
Considering the following task: @app.task(ignore_result=True) def withdraw(user, requested_amount): if user.balance >= requested_amount: send_money(requested_amount) user.balance -= requested_amount user.save() If this task gets executed twice, at the same time, it would result in an user with a negative balance... how can I solve it? It is just an example of race, but there are lots of situations like this in my code.. -
How to save data in the table to database using Django?
I use Django 2.1 and Python 3.7. I have some data in a table: <table class="table" border="1" id="tbl_posts"> <thead> <tr> <th>Name</th> <th>Age</th> </tr> </thead> <tbody id="tbl_posts_body"> <tr id="rec-1"> <td><span class="sn">1</span>.</td> <td><INPUT type="text" name="txt1" value="Name"/></td> <td><INPUT type="text" name="txt2" value="0"/></td> <td><a class="btn btn-xs delete-record" data-id="1"><i class="glyphicon glyphicon-trash"></i></a></td> </tr> </tbody> </table> A user can edit it and has to save it to the database in Django. How can I do it? I am a beginner in Django. Can I do it using form or ajax or any other suggestions. But I want to keep this structure. -
<hr> below each three <div>s
I'm trying to put a <hr> below each three <div>s (one <hr> per three <div>s), however I'm getting unexpected results. I came to the conclusion that I have to put a <hr> below each third <div>, but when I do that, it is not positioned correctly (see the demo). I am using this Django template: {% extends 'pages/base.html' %} {% load static %} {% block cssfiles %} <link rel="stylesheet" href="{% static 'products/css/list.css' %}" /> {% endblock %} {% block jsfiles %} <script type="text/javascript" src="{% static 'products/js/ellipsis.js' %}" defer></script> {% endblock %} {% block content %} {% for product in products %} <div class='product'> <div class='product-title'><a href="{{ product.get_absolute_url }}">{{ product.title }} ({{ product.year }})</a></div> <hr class='product-separator'> {% if product.image %} <div class='product-image'> <img src='{{ product.image.url }}' width='100' height='100'> </div> {% endif %} <p class='product-price'>${{ product.price }}</p> </div> {% if forloop.counter|add:1|divisibleby:3 %} <hr> {% endif %} {% endfor %} {% endblock %} Here is the jsfiddle link. -
bash script for docker permission denied in django project
I am learning docker and implemented docker in my Django project, currently, it is working great! no issue at all Now I am trying to make some command easy to run, that is why I write a shell script. coz, I am bored writing this too long command: docker-compose run web python /code/manage.py migrate --noinput docker-compose run web python /code/manage.py createsuperuser and more like above, to avoid writing long-lined command, i just wrote a shell script and this below: manage.sh is shell script file #!/bin/bash docker-compose run web python /code/manage.py $1 and later I tried to use my manage.sh file to migrate like ./manage.sh migrate Bit terminal throws me an error that is bash: ./manage.sh: Permission denied I am not getting actually what's wrong with it even I tried with sudo I believe if you are a docker expert, you can solve my problem. can you please help me in this case? -
Why isn't Django URL converter type working?
I am trying to write a unit test that will test a URLconf that follows Django's latest simplified URL routing syntax. This syntax allows the captured value to include a converter type. But what I've found is that the converter type doesn't seem to be working. Here is the URLconf I want to test: urlpatterns = [ path('club/<int:club_id>/', login_required(views.show_club), {'template': 'show_club.html'}, name='show-club'), ... ] As you can see, I want to pass the club ID as an integer. Now here is my test: class TestURLs(TestCase): def test_show_club(self): path = reverse('show-club', kwargs={'club_id': 10}) match = resolve(path) assert match.view_name == 'show-club' assert 'club_id' in match.kwargs assert match.kwargs['club_id'] == 10 When I run this test, I get an assertion error on the third assert: File... in test_show_club assert match.kwargs['club_id'] == 10 AssertionError If I insert a set_trace in my code and examine the match variable, I can see that the assertion is failing because the club_id key contains a string value of '10': ResolverMatch(func=activities.views.show_club, args=(), kwargs={'club_id': '10', 'template': 'show_club.html'...}) If my converter type is <int:club_id>, shouldn't kwargs['club_id'] contain the integer value 10 instead of the string '10'? I also inserted a set_trace in my code and then ran the code through that view. … -
Refresh from DB keeps OneToOneField Relation
I have a simple model relation: class Foo(models.Model): bar = models.OneToOneField(Bar) Say I do the following: >>> bar = Bar.objects.create() >>> foo = Foo.objects.create(bar=bar) >>> Foo.objects.all().delete() >>> bar.foo is None False This is expected because bar is still referencing the foo object. But now when I try to get a fresh copy of bar from the DB, i.e. without the related foo, I tried: >>> bar.refresh_from_db() >>> bar.foo is None False Why does foo not come back as None? I see that in the docs it says that only fields of the model are reloaded from the database when using refresh_from_db(). Does foo not count as a field of bar in this case? -
javascript snippet not working in django template
it's been a while since I did Django and I found an example of calling a view from a button that I needed: How do I call a Django function on button click? I built my template to match the example given: <html> <head> <title>Tournament Registration</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script> function register() { alert("Hi") } </script> </head> <body> <p>{{ tournament.name }}</p> <p>Start time: {{ tournament.start_time }}</p> <button onclick="register">Register</button> </body> </html> At first I just wanted it to pop an alert box so I know it's working at all. When I click the button however, nothing happens, and I get no error message in console. Are you able to call script tags in a Django template, or am I doing something else wrong here? Thank you -
How to link and update several Django models with a Foreignkey
I'm trying to make a link between two models, for achieve this I'm using several Foreignkey. Everything works fine until I delete one object of Url_lb. It seems Django can't update his table index and stuck whith a past index of Url_lb class Url_lb(models.Model): url = models.URLField(max_length=500) name = models.CharField(max_length=300) headers = models.TextField(max_length=3000) payload = models.TextField(max_length=3000) user = models.ForeignKey(User, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) state_item = models.BooleanField(default=True) def __str__(self): return self.url class Scrapper(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=300) url = models.URLField(max_length=300) image = models.URLField(max_length=300, default='.....') price = models.IntegerField(default=0) date = models.DateTimeField(auto_now=False) user = models.ForeignKey(User, on_delete=models.CASCADE) state_item = models.ForeignKey(Url_lb, on_delete=models.CASCADE) def __str__(self): return self.name I understand that the ID of Url_lb is never the same, but I don't understand why the table didn't update itself after an event like deleting an object... Error Display in Django server : db_1 | 2019-09-13 15:03:33.216 UTC [179] ERROR: insert or update on table "scrapper_scrapper" violates foreign key constraint "scrapper_scrapper_state_item_id_f11f58e2_fk_scrapper_url_lb_id" db_1 | 2019-09-13 15:03:33.216 UTC [179] DETAIL: Key (state_item_id)=(1) is not present in table "scrapper_url_lb". db_1 | 2019-09-13 15:03:33.216 UTC [179] STATEMENT: INSERT INTO "scrapper_scrapper" ("id", "name", "url", "image", "price", "date", "user_id", "state_item_id") VALUES (477944121, 'Chapeau ****', 'https://***.****', 'https://******', 1, '2019-09-13T17:03:18'::timestamp, 1, 1) Error … -
Deploy sentry helm in kubernetes cluster
I have deployed sentry on kubernetes last week, using this helm chart stable/sentry. Pods work fine but i cannot access to the website, it crash every time I access to the endpoint. I checked logs of the worker, sentry-web and postgres pods and see this. This is logs of the website pod: self._result_cache = list(self.iterator()) File "/usr/local/lib/python2.7/site-packages/django/db/models/query.py", line 220, in iterator for row in compiler.results_iter(): File "/usr/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 713, in results_iter for rows in self.execute_sql(MULTI): File "/usr/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 786, in execute_sql cursor.execute(sql, params) File "/usr/local/lib/python2.7/site-packages/sentry_sdk/integrations/django/__init__.py", line 396, in execute return real_execute(self, sql, params) File "/usr/local/lib/python2.7/site-packages/django/db/backends/util.py", line 53, in execute return self.cursor.execute(sql, params) File "/usr/local/lib/python2.7/site-packages/django/db/utils.py", line 99, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/usr/local/lib/python2.7/site-packages/django/db/backends/util.py", line 53, in execute return self.cursor.execute(sql, params) File "/usr/local/lib/python2.7/site-packages/sentry/db/postgres/decorators.py", line 80, in inner raise_the_exception(self.db, e) File "/usr/local/lib/python2.7/site-packages/sentry/db/postgres/decorators.py", line 78, in inner return func(self, *args, **kwargs) File "/usr/local/lib/python2.7/site-packages/sentry/db/postgres/decorators.py", line 22, in inner return func(self, *args, **kwargs) File "/usr/local/lib/python2.7/site-packages/sentry/db/postgres/decorators.py", line 101, in inner six.reraise(exc_info[0], exc_info[0](msg), exc_info[2]) File "/usr/local/lib/python2.7/site-packages/sentry/db/postgres/decorators.py", line 94, in inner return func(self, sql, *args, **kwargs) File "/usr/local/lib/python2.7/site-packages/sentry/db/postgres/base.py", line 74, in execute return self.cursor.execute(sql, clean_bad_params(params)) django.db.utils.ProgrammingError: ProgrammingError('relation "sentry_projectkey" does not exist\nLINE 1: ...te_limit_window", "sentry_projectkey"."data" FROM "sentry_pr...\n ^\n',) SQL: SELECT "sentry_projectkey"."id", "sentry_projectkey"."project_id", "sentry_projectkey"."label", "sentry_projectkey"."public_key", "sentry_projectkey"."secret_key", "sentry_projectkey"."roles", "sentry_projectkey"."status", "sentry_projectkey"."date_added", "sentry_projectkey"."rate_limit_count", … -
How to define a field that automatically takes the mean of all the data of another integer field of the model of which it is foreign key?
I want this field to be predefined, and automatically calculate the average of all integer data in the field of which it is a foreign key. Exemple : class Product (models.Model): title = CharField(...) #this field set automatically the average, and also update after #adding new price_average = FloatField(...) class ProductItem (models.Model): title = CharField(...) price = IntegerField(...) _product = ForeignKey(Product) is it possible in this way or do I have to implement a method that does it automatically in the background? -
I am getting an error whenever I import forms in the models.py file
So basically, I am making a website where users can upload posts, with images in them. In my models.py file, I have a bit of code where I need a forms.py thing, so in the top of the models.py file, I imported the needed form. from .forms import PostForm But then I get this error: ImportError: cannot import name 'UserProfileInfo' from 'mainapp.models' I have tried to do mainapp.forms import PostForm mainapp.forms import * But none of these work. I can't find anything online either about this problem. Imports from forms.py. This is where the error is occuring. from .models import UserProfileInfo, Post, Comment In the above snippet, I am importing some of models And this is thre models.py import from .forms import PostForm Here is the Post model class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=75) text = models.TextField(max_length=4000) created_date = models.DateTimeField(default=timezone.now) image = models.ImageField(upload_to='post_images',blank=True,null=True) published_date = models.DateTimeField(blank=True,null=True,auto_now_add=True) tags = TaggableManager() def __str__(self): return self.title def __init__(self, *args, **kwargs): super(PostForm, self).__init__(*args, **kwargs) self.fields['image'].required = False def save(self, *args, **kwargs): super().save(*args, **kwargs) So the reason I need to import forms is because of the super(PostForm) bit. Here is the needed form class PostForm(forms.ModelForm): class Meta(): model = Post fields = …