Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Conditional Many-to-One Relationship?
I have three models: Product Variation BundledItem Variation and BundledItem each have a many-to-one relationship with Product. A Product's 'type' (CharField with choices) can be 'simple', 'variable', or 'bundle'. I want to ensure that a Variation can only be related to a Product of type 'variable' and a BundledItem can only be related to a Product of type 'bundle'. How can I implement this as a condition or verify the Product type as part of linking a Variation/BundledItem? -
django slug issue noreversematch
I'm new with django and I need little help to fix this issue. I'm getting error NoReverseMatch, django.urls.exceptions.NoReverseMatch: Reverse for 'blog_details' with keyword arguments '{'slug': 'Cybercrime-Could-Cost-the-World-$10.5-Trillion-Annually-by-2025-aee2db6e-29ca-4ff9-94e8-09d8656905f3'}' not found. 1 pattern(s) tried: ['blog/details/(?P<slug>[-a-zA-Z0-9_]+)$'] I'm not sure where is my mistake and how can I fix this. Any help is appreciated! views.py def blog_details(request, slug): blog = Blog.objects.get(slug=slug) return render(request, 'App_Blog/blog_details.html', context ={'blog':blog}) urls.py urlpatterns = [ path('', views.BlogList.as_view(), name = 'blog_list'), path('write/', views.CreateBlog.as_view(), name = 'create_blog'), path('details/<slug:slug>', views.blog_details, name = 'blog_details'), ] blog_list.html {% extends 'base.html' %} {% block title %} Detail{% endblock %} {% block body_block %} <h2>I am a blog list home page.</h2> {% if blogs %} {% for blog in blogs %} <h2>{{ blog.blog_title }}</h2> <div class="row"> <div class="col-sm-4"> <img src = "{{ blog.blog_image.url }}" alt="{{ blog.blog_title }}" width='100%;'> </div> <div class="col-sm-8"> <p>{{ blog.blog_content | linebreaks }} <a href = "{% url 'blog_details' slug=blog.slug %}">Read More</a> </p> </div> <p><i>{{ blog.publish_date }}</i></p> <h5>Posted by {{ blog.author }}</h5> </div> {% endfor %} {% else %} <p>No articles available!</p> {% endif %} {% endblock %} models.py class Blog(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='post_author') blog_title = models.CharField(max_length=264, verbose_name='Put a title') slug = models.SlugField(max_length=264, unique = True) blog_content = models.TextField(verbose_name='What is on your … -
Django CSS static files randomly stops working
My relationship with django is almost over. Everything was going great until my CSS file stopped working. I did not change anything. I tried changing the color of my title and it would not change. I refreshed everything and ctrl + C. Instead of changing the CSS, the CSS stopped working completely and I can't get it to work again. When I run python manage.py runserver, I get: [24/Feb/2021 18:19:53] "GET /dreamboard/ HTTP/1.1" 200 11844 [24/Feb/2021 18:19:53] "GET /static/css/main.css HTTP/1.1" 304 0 [24/Feb/2021 18:19:53] "GET /dreamboard/ HTTP/1.1" 200 11844 It looks like it's accessing the CSS file fine. Here are my other files: settings.py """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 3.1.6. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '$hggs$iztdeeb@x0b=5y42ykz((un)jtmf--$1$z2778(we5@8' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] STATICFILES_DIRS = [ … -
"detail": "No active account found with the given credentials" django
im trying to get a token for manual tests, but when i POST for a simple_jwt's view TokenObtainPairView: in: { "password": "aaabbb", "email": "email@mail.ru" } out: { "detail": "No active account found with the given credentials" } although if i list all users its like { "count": 1, "next": null, "previous": null, "results": [ { "first_name": "", "last_name": "", "username": "geddon", "bio": null, "email": "email@mail.ru", "role": "admin" } ] } although theres no password if i dont POST it, it returns that its needed the user model is: class User(AbstractUser): email = models.EmailField('email address', unique=True) bio = models.TextField(max_length=300, blank=True, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['role',] USER_ROLE = ( ('user', 'user'), ('moderator', 'moderator'), ('admin', 'admin'), ) role = models.CharField(max_length=9, choices=USER_ROLE, default='user') and its serializer is: class UserSerializer(serializers.ModelSerializer): def create(self, validated_data): user = super().create(validated_data) user.set_password(validated_data['password']) user.save() return user def validate_password(self, value: str) -> str: return make_password(value) class Meta: model = User fields = 'first_name', 'last_name', 'username', 'bio', 'email', 'role' lookup_field = 'username' -
Django. How to remove a field from objects in the database?
First, field division had choices with list of available divisions with default='No' . Then it ceased to be necessary, i tried just delete field from model, but get django.core.exceptions.FieldError: Unknown field(s) (division) specified for Team. Then i remove choice, default and set division='None' for all objects. I thought if the value is null (None) then the field can be safely removed, but got the same FieldError: Unknown field(s) specified again. How can I remove a field from a model, If the database already contains objects with specified field? models.py class Team(models.Model): name = models.CharField("Name", max_length=50, unique=True) image = models.ImageField("Logo", upload_to="img/teams",default="img/team.jpg") city = models.CharField("City",max_length=30, default="Moscow") division = models.CharField("Division", max_length=50, null=True) url = models.SlugField( max_length=30, unique=True) def __str__(self): return self.name -
Postgres error while deploying django project on server
When i'm running sudo -u postgres psql it returns following traceback: psql: error: could not connect to server: Permission denied Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? -
Django: saving model instance from function inside class based view not working
TLDR: I am probably doing something wrong. I am attempting to update and save a record from a function (get_context_data) inside a class based view (generic.UpdateView). I have read so many diffrent things I am confused and stuck. Please forgive me if I am doing something sub optimal. I am newish to Django and cannot find any examples of what I am attempting to do. I presume I am doing something foolish that could be done much easier in another way or what I am attempting is an edge case. I have already tried a bunch of things and this seems to work and prints out all the information to the console, it is just not saving. Please forgive the code gore. OVERVIEW: I have a model (Record) that, amongst other things tracks the Stage of work for the a work order. A Record tracks it's Stage via a FoerignKey relationship. When a Record is saved I am using signals to check if the Stage value has changed, and if so track it in another model (RecordStageChange). I need to also record the time difference between the each Record's entry on the RecordStageChange table and the previous. MODELS class Record(models.Model): … -
No 'Access-Control-Allow-Origin' header issue in Django httpresonse
In my Django project, I have a simple function that creates a json and returns a httpresponse. I plan to use this httpresponse on my wordpress site. Since the django project and wordpress are being hosted on different domains, I'm getting CORS error. Since I need the CORS issue to be resolved for this only issue and the rest of the django project is being used for something else I don't want to use django-cors-headers and looking for alternative. I've tried adding headers to the httpresponse but that did not work. def show_info(request): data = {} data['currency_pair'] = 'EURUSD' data['bid'] = 1.5 data['ask'] = 1.3 response = HttpResponse(json.dumps(data)) response["Access-Control-Allow-Origin"] = "*" response["Access-Control-Allow-Methods"] = "GET, OPTIONS" response["Access-Control-Max-Age"] = "1000" response["Access-Control-Allow-Headers"] = "X-Requested-With, Content-Type" return response -
'LogSetupMiddleware' object is not callable?
i am trying to use a django-requestlogging for my website to log ip addresses when i try to open any page in the website it keeps giving me the following error: 'LogSetupMiddleware' object is not callable what can i do to solve this problem and also is there any other way to get the ip address of the current user without that much hastle to use it in my logs here is the settings.py INSTALLED_APPS = [ 'django_requestlogging', 'website.apps.WebsiteConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles',] MIDDLEWARE = [ 'django_requestlogging.middleware.LogSetupMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware',] LOGGING = { 'version': 1, 'disable_existing_loggers': False, # Handlers ############################################################# 'handlers': { 'file1': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'filename': './logs/debug.log', 'formatter':'simple' 'filters': ['request'], }, 'file2': { 'level': 'INFO', 'class': 'logging.handlers.RotatingFileHandler', 'filename': './logs/info.log', 'formatter':'simple', 'filters': ['request'], }, 'console': { #'level': 'DEBUG', #'class': 'logging.StreamHandler', #'filters': ['request'], #'formatter': 'simple' }, }, # Loggers #################################################################### 'loggers': { 'django': { 'handlers': ['file1','file2', ], 'level': 'DEBUG', 'propagate': True, 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'), 'filters': ['request'], }, }, # Formatters #################################################################### 'formatters': { 'simple': { 'format': '[%(asctime)s] %(levelname)s|%(remote_addr)s|%(username)s|%(name)s|%(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S', }, }, # Filters #################################################################### 'filters': { 'request': { '()': 'django_requestlogging.logging_filters.RequestFilter', }, }, } -
_getfullpathname: path should be string, bytes or os.PathLike, not list
TypeError at /admin/news/itnews/add/ _getfullpathname: path should be string, bytes or os.PathLike, not list Request Method: POST Request URL: http://localhost:8080/admin/newebs/itens/add/ Django Version: 3.1.6 Exception Type: TypeError Exception Value: enter code here _getfullpathname: path should be string, bytes or os.PathLike, not list Exception Location: C:\Program Files (x86)\Python38-32\lib\ntpath.py, line 527, in abspath Python Executable: C:\Djangos\MultWebsites\virtual\Scripts\python.exe Python Version: 3.8.8 Python Path: ['C:\Djangos\MultWebsites\websites', 'C:\Program Files (x86)\Python38-32\python38.zip', 'C:\Program Files (x86)\Python38-32\DLLs', 'C:\Program Files (x86)\Python38-32\lib', 'C:\Program Files (x86)\Python38-32', 'C:\Djangos\MultWebsites\virtual', 'C:\Djangos\MultWebsites\virtual\lib\site-packages'] O meu problema esta no add no admin imagens, coloco todas as informações escrita ai coloco uma imagem de um diretório de uma aplicação diferente das outras; acontece esse problema Já fiz de tudo alguém me ajuda com uma solução que não terei problema em salvar essas informações dessa aplicação e das demais que esta no mesmo projeto. HELPSSSSSSS -
Django exclude with iteration over related model
I have a problem that is very similar to this one here: Django exclude from annotation count. The answer presents from django.db.models import IntegerField, Sum, Case, When workers = Worker.objects.annotate( num_jobs=Sum( Case( When(job__is_completed=True, then=1), default=0, output_field=IntegerField() ) ) ) as a solution. Can I get something like to following to work with exclude instead of annotate? workers = Worker.objects.exclude( 0==Sum( Case( When(job__is_completed=True, then=1), default=0, output_field=IntegerField() ) ) ) i.e. exclude the workers that did no job finish? I run into a cannot unpack non-iterable bool object error in django... -
Customize Django Admin Add Form
I'm stuck on Django, in fact, I would like to know how to customize a model's Admin add form and also process the information. I was able to modify the form from the add_form_template attribute of ModelAdmin but after nothing more, I also cannot use correctly add_view here's code: # admin.py from django.contrib import admin from .models import Schedule @admin.register(Schedule) class ScheduleAdmin(admin.ModelAdmin): list_display = ['doctor_name', 'date', 'timerange'] list_display_links = ('doctor_name',) list_filter = ['date'] add_form_template = 'admin/add_schedule.html' def add_view(self, request, extra_context=None): return super().add_view(request) def doctor_name(self, schedule): return schedule.doctor.name doctor_name.short_description = "Medecin" And add_schedule.html: {% extends "admin/base_site.html" %} {% block title %}My title{% endblock %} {% block content %} My content and forms here. {% endblock %} -
Django - complicated ORM Query (related_set)
I have model Car, Listing and Website. class Listing.. car = ForeignKey... website = ForeignKey... active = BooleanField... I want to filter all car objects that have listing object on the given website but the listing needs to be active. To get all car objects that have listing object on the given website: website = ... Car.objects.filter(listings__website__in=website) But how do I filter out inactive listings? I want something like: website = ... Car.objects.filter(listings[only_active]__website__in=website) -
sitemap and error page(404+500) react django
hello I am in the optimization I found some non video tutorial but apparently he forgets a step or two sitemap current code public/sitemap.js enter code here import express from 'express' import { SitemapStream, streamToPromise } from 'sitemap' import mongoose from 'mongoose' import { domain } from '../src/env' const port = `${domain}` const app = express() let sitemap; app.get('/sitemap.xml', async function(req, res) { res.header('Content-Type', 'application/xml'); res.header('Content-Encoding', 'gzip'); if (sitemap) { res.send(sitemap) return } try { const allCategories = await Category.Category.find().select('title') const categories = queryCategories.map( ({ title }) => `/category/${title}`) const smStream = new SitemapStream({ hostname: 'https://yourWebsite.com/' }) const pipeline = smStream.pipe(createGzip()) categories.forEach(function(item) { smStream.write({ url: item, changefreq: 'monthly', priority: 0.6}) }); streamToPromise(pipeline).then(sm => sitemap = sm) smStream.end() pipeline.pipe(res).on('error', (e) => {throw e} console.error(e) res.status(500).end() } }); for the error pages I created a page page not found but it is not a page with a status 400 in addition the page removes all the pages which have '/ word' here is the code app.js ... return ( <BrowserRouter> <NavBar/> <Switch> <Route exact path="/" component={HomePage}/> <Route exact path="/product/:id" component={ProductDetails}/> <Route exact path="/category/:id" component={CategoryProduct}/> <Route exact path="*" component={Pagenotfound}/> { profile !==null ? ( <> <Route exact path="/profile" component={ProfilePage}/> <Route exact path="/cart" component={Cart}/> … -
Django - Ajax refresh, value inserted into multiple tables instead of one
I am creating a restaurant web application and I am currently trying to implement an interface for staff so they can view incoming takeaway orders. I plan on updated this page at a set time interval. The process of inserting a takeaway order into the database works fine. However, when I create a new order, the food items on one order is inserted into every other order as well. I am utilizing django sessions to try ensure every order id is different. I believe I am making an error in the script in the following template. I will also show my views.py that is responsible for creating an order etc. template.html {% load bootstrap4 %} {% bootstrap_css %} {% bootstrap_javascript jquery='full' %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Yuppa</title> </head> <body> {% for takeaways in takeaway_orders %} <div class="takeaway_container"> <p>Order ID: {{ takeaways.order_id }}</p> <p>Basket ID: {{ takeaways.basket }}</p> <table class="table {{ takeaways.order_id }}"> <tr> <th>Item</th> <th>Quantity</th> <th>Price</th> <th>Action</th> </tr> {% for basket_item in basket_items %} <tr> <td>{{ basket_item.menu_item }}</td> <td>{{ basket_item.quantity }}</td> <td>{{ basket_item.menu_item.price }}</td> <td>{{ takeaways.status }}</td> </tr> {% endfor %} </table> <p>Total: {{ takeaways.basket.total }}</p> {% endfor %} </div> <script> function autoReload() { setTimeout(function() { $.ajax({ … -
How to display formatted body of an email in html - Python/Django/PostgreSQL
I retrieve emails from Outlook and store them in PostgreSQL. I then display the e-mails in a .html page with Django: {% extends "base.html" %} {% load static %} {% block page_content %} {% for i in ticket %} <p>Requester: {{i.requester}}</p> <P>Subject: {{i.title}}</p> <p>Description: {{i.description}}</p> {% endfor %} {% endblock %} The body(i.description) of the email has the format of a html xmlns file, for example: <html xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns:m="http://schemas.microsoft.com/office/2004/12/omml" xmlns="http://www.w3.org/TR/REC-html40"><head> <meta name="Generator" content="Microsoft Word 15 (filtered medium)"> <style><!-- /* Font Definitions */ @font-face {font-family:"Cambria Math"; panose-1:2 4 5 3 5 4 6 3 2 4;} @font-face {font-family:Calibri; panose-1:2 15 5 2 2 2 4 3 2 4;} /* Style Definitions */ p.MsoNormal, li.MsoNormal, div.MsoNormal {margin:0cm; margin-bottom:.0001pt; font-size:11.0pt; font-family:"Calibri",sans-serif; mso-fareast-language:EN-US;} span.EmailStyle17 {mso-style-type:personal-compose; font-family:"Calibri",sans-serif; color:windowtext;} .MsoChpDefault {mso-style-type:export-only; font-family:"Calibri",sans-serif; mso-fareast-language:EN-US;} @page WordSection1 {size:612.0pt 792.0pt; margin:72.0pt 72.0pt 72.0pt 72.0pt;} div.WordSection1 {page:WordSection1;} --></style><!--[if gte mso 9]><xml> <o:shapedefaults v:ext="edit" spidmax="1026" /> </xml><![endif]--><!--[if gte mso 9]><xml> <o:shapelayout v:ext="edit"> <o:idmap v:ext="edit" data="1" /> </o:shapelayout></xml><![endif]--> </head> <body lang="EN-GB" link="#0563C1" vlink="#954F72"> <div class="WordSection1"> <p class="MsoNormal">Testing how body works now<o:p></o:p></p> ... How can I display the email with this html xmlns text format, such that it keeps the original formatting? Is there a way to embed that wall of … -
How to use pytest with Django?
When I use pytest with Django, no test_<db_name> is created. Minimum reproducible example: In Django project: ./manage.py startapp testing_pytest in models.py class Snippet(models.Model): created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, blank=True, default='') code = models.TextField() linenos = models.BooleanField(default=False) external_id = models.CharField(max_length=100, default='0') class Meta: ordering = ['created'] then create a db named loc_db in Postgres, ./manage.py makemigrations ./manage.py migrate in serializers.py class BulkUpdateOrCreateListSerializer(serializers.ListSerializer): def create(self, validated_data): result = [self.child.create(attrs) for attrs in validated_data] try: res = self.child.Meta.model.objects.bulk_create(result) except IntegrityError as e: raise ValidationError(e) return res class SnippetSerializer(serializers.ModelSerializer): class Meta: model = Snippet fields = ['id','title', 'code', 'linenos'] read_only_fields = ['id'] list_serializer_class = BulkUpdateOrCreateListSerializer def create(self, validated_data): instance = Snippet(**validated_data) if isinstance(self._kwargs["data"], dict): instance.save() return instance in views.py class SnippetGetView(generics.ListAPIView): serializer_class = SnippetSerializer queryset = Snippet.objects.all() class SnippetUpdateView(generics.ListCreateAPIView): queryset = Snippet.objects.all() serializer_class = SnippetSerializer def get_serializer(self, *args, **kwargs): if isinstance(kwargs.get("data", {}), list): kwargs["many"] = True return super(SnippetUpdateView, self).get_serializer(*args, **kwargs) in tests.py @pytest.fixture(scope='session',autouse=True) def my_faker(): return Faker() @pytest.fixture(scope='session',autouse=True) def factory(): return APIRequestFactory() @pytest.fixture(scope='session',autouse=True) def snippets(): snippets = [] for i in range(TEST_SIZE): snippets.append({'title':'snippet'+str(i),'code':'print(True)','linenos':False,'external_id':'1'}) return snippets @pytest.mark.django_db def test_update_snippet(factory,snippets): request = factory.post('/add-snippets/',snippets) view = SnippetUpdateView.as_view() response = view(request) response.render() assert status.is_success(response.status_code) and in <project_name>/settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'loc_db', 'USER': … -
Django Model/Class Context Renders Empty
I am attempting to render the context of an object array to be used in the HTML, but it does not render out. During debugging (Visual Studio), I can see the object is populated, but nothing actually renders. What am I doing wrong? Model/Class class SalesReps(): def __init__(self, SalesRep = ""): self.SalesRep = SalesRep class Meta: managed = False View def salesReps(request): sqlString = "EXEC [dbo].[sp_GetSalesRep]" objSalesReps = callProcSingleResult(sqlString, "SalesReps") context={ 'SalesReps' : objSalesReps } return render(request, 'app/page.html', context) def callProcSingleResult(sqlString, clsName = None): cursor = connection.cursor() dataResults = [] try: cursor.execute(sqlString) results = cursor.fetchall() if clsName is not None: #Get column names columns = [column[0] for column in cursor.description] #populate class for row in results: constructor = globals()[clsName] p = constructor() i=0 for x in columns: #set property value of matching column name setattr(p, x, row[i]) #get property value #x = getattr(p, x) i=i+1 dataResults.append(p) except Exception as ex: print(ex) finally: cursor.close() return dataResults HTML {% for obj in SalesReps %} $('#txtSalesRep').append('<option value="{{ obj.SalesRep }}">{{ obj.SalesRep }}</option>'); {% endfor %} -
Looping through Beautiful Soup results
I have searched for all elements with the tag p as shown below def get_html_content(request): import requests number = request.POST.get('number') USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36" LANGUAGE = "en-US,en;q=0.5" session = requests.Session() session.headers['User-Agent'] = USER_AGENT session.headers['Accept-Language'] = LANGUAGE session.headers['Content-Language'] = LANGUAGE html_content = session.get(f'https://sdahymnal.net/sda-hymnal-{number}').text return html_content def home(request): result = None if 'number' in request.POST: html_content = get_html_content(request) soup = BeautifulSoup(html_content, 'html.parser') result= soup.find_all("p").text return render(request, 'user/home.html', {'result': result}) but I get the error below; AttributeError: ResultSet object has no attribute 'text'. You're probably treating a list of elements like a single element. Did you call find_all() when you meant to call find()? please help as I want to pass all elements to the template and show them in stanza form..here is my template code {% for result in result %} {{ result }} {% endfor %} -
Connecting mqtt and django
I am working on python Django APIs. I am using rest APIs And in my views I am calling flask APIs ( Flask APIs are written inside raspberry pi) Here I want to use Mqtt I created a MQTT server in local mode , I am using mosquitto broker pip install paho-mqtt but I am not getting idea about how can I change my APIs , that calling device API( flask API) with the use of MQTT Views.py url = "http/"+ deviceCode + "/empdata" resp = requests.post(url, json=reqData) in raspberry pi we added flask code and we called the flaskAPI like this.. but while using MQTT , what are the changes I need for execute the functionality -
Django python manage.py makemigrations causes a problem with databases
I am starting with Django and I got this problem. I understand only that there is a problem with database. I would really like to get some help. Thank you, If it is important I use Fedora 33 Guys really, not my bad that the 90% of problem is code, let me as a question XD (project_venv) [mikolajwojtowicz@localhost src]$ python3 manage.py makemigrations Traceback (most recent call last): File "/home/mikolajwojtowicz/.local/lib/python3.9/site-packages/django/db/backends/utils.py", line 82, in _execute return self.cursor.execute(sql) File "/home/mikolajwojtowicz/.local/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 411, in execute return Database.Cursor.execute(self, query) sqlite3.DatabaseError: file is not a database The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/mikolajwojtowicz/Django/my_project/src/manage.py", line 22, in <module> main() File "/home/mikolajwojtowicz/Django/my_project/src/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/mikolajwojtowicz/.local/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/mikolajwojtowicz/.local/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/mikolajwojtowicz/.local/lib/python3.9/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/home/mikolajwojtowicz/.local/lib/python3.9/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/home/mikolajwojtowicz/.local/lib/python3.9/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/home/mikolajwojtowicz/.local/lib/python3.9/site-packages/django/core/management/commands/makemigrations.py", line 101, in handle loader.check_consistent_history(connection) File "/home/mikolajwojtowicz/.local/lib/python3.9/site-packages/django/db/migrations/loader.py", line 290, in check_consistent_history applied = recorder.applied_migrations() File "/home/mikolajwojtowicz/.local/lib/python3.9/site-packages/django/db/migrations/recorder.py", line 77, in applied_migrations if self.has_table(): File "/home/mikolajwojtowicz/.local/lib/python3.9/site-packages/django/db/migrations/recorder.py", line 56, in has_table tables = self.connection.introspection.table_names(cursor) File "/home/mikolajwojtowicz/.local/lib/python3.9/site-packages/django/db/backends/base/introspection.py", line 48, in … -
how can I merge two responses Serializer in to a single serializer and perform actions over that?
I have serializers that i want to return both responses , and merge the responses as a new attribute subtitles if the parent id are equal e.g. T1134 , and T1134.001 where T1134.001 will be merged into subtitle attribute viewset class BooksViewSet(mixins.ListModelMixin, viewsets.GenericViewSet): queryset = ModelB.objects.all() serializer_class = BSerializer class ASerializer(serializers.ModelSerializer): class Meta: model = ModelA fields = '__all__' class BSerializer(serializers.ModelSerializer): class Meta: model = ModelB fields = '__all__' def merge_responses(ASerializer, BSerializer): merge responses api response { "_id":"T1134", "title":"Manipulation", "url":"xxxxxxxx", "queries":[ ], }, { "_id":"T1134.001", "title":"Psychological manipulation", "url":"xxxxxxxx", "queries":[ ], }, final response { "_id":"T1134", "title":"Manipulation", "url":"xxxxxxxx", "queries":[ ], "subtitles":[ { "_id":"T1134.001", "title":"Psychological manipulation", "url":"xxxxxxxx", "queries":[ ] } ] } -
Aggregating Django object using Avg in an API view
I keep getting null values when applying .aggregate(Avg(column_name)) in a Django API My code looks like this: Models.py class Glucose_level(models.Model): patient = models.ForeignKey(Patients, on_delete=models.CASCADE) glucose_reading = models.FloatField(blank=True, null=True) date = models.DateField(auto_now=True) timestamp = models.TimeField(auto_now=True) Serializers.py class GlucoseSerializer(serializers.ModelSerializer): class Meta: model = Glucose_level fields = ('date', 'glucose_reading', 'id', 'patient_id', 'timestamp') My API in views.py class FourteenDayAvg(viewsets.ModelViewSet): serializer_class = GlucoseSerializer def get_queryset(self): patient_id = self.request.query_params.get('patient_id') sdate = (datetime.date.today() - datetime.timedelta(days=14)).strftime('%Y-%m-%d') edate = (datetime.date.today() + datetime.timedelta(days=1)).strftime('%Y-%m-%d') patient_list = Glucose_level.objects.filter(date__range =(sdate,date), patient_id=patient_id).aggregate(Avg('glucose_reading')) Output: [ { "glucose_reading": null } ] Please let me know if something is wrong with my syntax. -
Django Hide / Show Fields in Admin Site Based on Model Bool Value
New to Django here. I have a model that holds the operating hours of a restaurant that looks like so: class OperatingHours(models.Model): MONDAY = "Monday" TUESDAY = "Tuesday" WEDNESDAY = "Wednesday" THURSDAY = "Thursday" FRIDAY = "Friday" SATURDAY = "Saturday" SUNDAY = "Sunday" WEEKDAYS = [ (MONDAY, "Monday"), (TUESDAY, "Tuesday"), (WEDNESDAY, "Wednesday"), (THURSDAY, "Thursday"), (FRIDAY, "Friday"), (SATURDAY, "Saturday"), (SUNDAY, "Sunday") ] weekday = models.CharField(max_length=9, choices=WEEKDAYS) from_hour = models.TimeField(null=True, blank=True) to_hour = models.TimeField(null=True, blank=True) closed = models.BooleanField(default=False) class Meta: ordering = ('weekday', 'from_hour') unique_together = ('weekday', 'from_hour', 'to_hour') def __str__(self): return self.weekday def __unicode__(self): return u'%s: %s - %s' % (self.get_weekday_display(), self.from_hour, self.to_hour) What I am attempting (but failing) to accomplish is hiding / showing the from_hour and to_hour field based on the value of closed. I believe my fix will need to be in admin.py, but how exactly can I show the from_hour and to_hour fields in the admin site when closed=False and hide them when closed=True? -
Django ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine when POST
I'm working on a wep app in Django that gives me ConnectionAbortedError: [WinError 10053] whenever I post information on a specific page. The code works fine, it does all that has to do, but gives that error and sometimes the pages don't load. Template </body> {{ dtMaterialesSZ|json_script:"dtMaterialesSZ" }} </body> Js file var vrData = JSON.parse(document.getElementById('dtMaterialesSZ').textContent); vrData=JSON.parse(vrData) function fnCotMat(vrData) { var vrData = JSON.stringify(vrData); $.ajax({ url: '/CotMat', type: 'post', data: { axMat: vrData, csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val() }, }); return false; }; Views def vwCotMaterial(request): if request.method == "POST": request.session["Mat"]=request.POST.get('axMat') return redirect('/CotComp') I already turn off the windows firewall and the antivirus (Avast) Also installed "Allow CORS" extension in google chrome and whitelisted http://localhost:8080/reactive-commands . When testing CORS I get this: CORS is allowed for POST ✔ CORS is allowed for HEAD ✔ CORS is allowed for DELETE ✔ CORS is allowed for OPTIONS ✔ CORS is blocked for PROPFIND ✖ CORS is blocked for PROPPATCH ✖ CORS is blocked for MKCOL ✖ CORS is blocked for COPY ✖ CORS is blocked for MOVE ✖ CORS is blocked for LOCK ✖ CORS is allowed for GET (with credentials) ✔ CORS is allowed for GET (with redirect) ✔ (Don't know how to allow PROPPATCH …