Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to match specific fields on models?
I have model as below, I need to get bookname as ForeignKey and it works on Django Admin but I also need pageCount related with bookPageCount to auto determine on Django Admin or on add new record. When I add new log to ReadList I want pageCount to define automatically depending on record selected from Book; class Book(models.Model): bookname = models.CharField(max_length=200, verbose_name='Kitap Adı') bookAuthor = models.CharField(max_length=100, verbose_name='Yazar Adı') bookPublisher = models.CharField(max_length=100, verbose_name='Yayın Evi') bookPageCount = models.PositiveIntegerField(verbose_name='Sayfa Sayısı') bookAddDate = models.DateField(verbose_name='Kitaplığa Eklenme Tarihi') class Meta: verbose_name = 'Kitap' verbose_name_plural = 'Kitaplar' class ReadList(models.Model): bookName = models.ForeignKey('kitaplik.Book.bookname', related_name='bookName', on_delete=models.CASCADE, verbose_name='Kitap Adı') readerName = models.ForeignKey('ogrenciler.Students.studentName', on_delete=models.CASCADE, related_name='readerName', verbose_name='Okuyan Kişi') dateOfRead = models.DateField(verbose_name='Okuma Tarihi') pageCount = models.ForeignKey('kitaplik.Book.bookPageCount', related_name='pageCount', on_delete=models.PROTECT, verbose_name='Sayfa Sayısı') class Meta: verbose_name = 'Okuma Günlüğü' -
Image does not upload to database. ValueError. The 'image' attribute has no file associated with it
I'm working on a project (simple social media site). Logged in users should create posts with text and image. When I submit the form, the image does not uploads and a ValueError occurs, saying that "The 'image' attribute has no file associated with it." The only way to attach an image to the post is from admin panel, but that's not what I want to do. I think there's a problem in views.py - I saw many posts, where this is done by using Function Based Views, but I didn't manage to find a solution with Class Based Views. I'm pretty new to Django and most probably I'm missing something small (or at least I hope so). Could you have a look and advise how to proceed. Any help will be much appreciated! models.py class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField(null=True) image = models.ImageField(upload_to='post_pics/', null=True, blank=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) views.py - CBV for creating a post class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'content', 'image'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) -
foriegn key object not iterable in template
I have basic models for a section, subsection and clause. 1 section can hold multiple subsections. Each subsection can hold multiple clauses. The models look like: **models.py** class Clause(models.Model): number = models.CharField(max_length=8, unique=True) requirements = models.TextField(max_length=2000, unique=False, blank=True, null=True) documentation = models.TextField(max_length=2000, unique=False, blank=True, null=True) class Subsection(models.Model): number = models.CharField(max_length=5, unique=True) name = models.CharField(max_length=150, unique=False) descriptor = models.TextField(max_length=2000, unique=False, blank=True, null=True) clause = models.ForeignKey(Clause, on_delete=models.DO_NOTHING, related_name="clause") class Section(models.Model): number = models.CharField(max_length=2, unique=True) name = models.CharField(max_length=150, unique=False) descriptor = models.TextField(max_length=2000, unique=False, blank=True, null=True) subsection = models.ForeignKey(Subsection, on_delete=models.DO_NOTHING, related_name="subsection") basic view function to call the desired section: **views.py** def main(request): form = MainSearchForm() user = request.user sections = [] show_results = True if 'query' in request.GET: show_results = True query = request.GET['query'].strip() if len(query) <= 2: sections = Section.objects.filter(number__iexact=query) if sections: records = sections tpl = "display_console.html" context = {'user': user, 'records': records, 'form': form} return render(request, tpl, context) else: tpl = "main.html" context = {'user': user, 'form': form} return render(request, tpl, context) unfortunately, I can't get my template to return my subsection data. The following returns a 'Subsection' object is not iterable error: **template** <table class="section_tb"> {% if records %} {% for record in records %} <tr> <td>{{ record.number }}</td><td>{{ record.name … -
Django Rest Framework will not accept my CSRF Token
I'm trying to build a Single Page Application with Django Rest Framework. For authentication, I'm using a login view that initiates a session and requires csrf protection on all api routes. Because there is no templating going on, the csrf_token tag is never used, so I have to manually get the token with get_token. Instead of putting it in the main index file that will be given in the home view, I want to set it on its own cookie. No this is not the CSRF Cookie that django provides, as that one has the CSRF secret, plus I mentioned I'm using sessions, so the secret is stored there. This cookie will have the token which will be used for all mutating requests. I have tried everything to get django to accept the cookie but nothing has worked. I can login just fine the first time, because there was no previous session, but anything after that just throws an error 403. I tried using ensure_csrf_cookie but that didn't help. I tried without sessions and still nothing. I even tried rearranging the middleware order and still nothing. I even tried my own custom middleware to create the cookie but it didn't … -
Django - model not defined
I'm trying to add a new form to my Django project, but i keep getting this error: model = SomeModel NameError: name 'SomeModel' is not defined I don't get why, since i defined SomeModel in my models file. Here is my code: from .models import SomeModel from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from captcha.fields import CaptchaField from django.forms import ModelForm class TestForm(ModelForm): data = forms.CharField(label='Data', max_length=100) class Meta: model = SomeModel fields = ("test",) def save(self, commit=True): send = super(TestForm, self).save(commit=False) send.data = self.cleaned_data['Data'] if commit: send.save() return send And here is my model: class SomeModel(models.Model): data = forms.CharField(max_length=100) def save(self): # ALL the signature super(SomeModel, self).save(using='dataset') What am i doing wrong? Am i not declaring my model properly? Thanks in advance! -
Django Project -error in the URLconf defined in mysite.urls, cannot spot error
I have looked at previous answers, but cannot spot the error in my code. I get a 'page not found' error, on running the server, and clicking on the 'submit' button for the form. The relevant views.py code and function** def addMessage(request): new_item =GuestBookItem(content=request.POST['content']) new_item.save() return HttpResponseRedirect('worldguestbook/worldguestbook.html') the form (in the html) <form action="/addMessage/" method="post">{% csrf_token %} <input type="text" name="content"/> <input type="submit" value="Add"/> </form> urls.py urlpatterns = [ path('admin/', admin.site.urls), path('worldguestbook/',worldguestbookView), path('login/',loginView), path('addMessage/',addMessage), ] Error 1 Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/addMessage/worldguestbook/worldguestbook.html Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ worldguestbook/ login/ addMessage/ The current path, addMessage/worldguestbook/worldguestbook.html, didn't match any of these. Note: The content is actually submitted, but it doesn't redirect correctly. -
I have an app with react as frontend and django rest framework as backend, i use axios to send my response, but the data is empty
I have an app with react and Django rest framework. I use Django allauth for login and registration. when I want to log in, everything is ok, and the response is 201 but the data is empty and I don't get token. I send this request with the postman and I get the token. what should i do? -
Django Rest Auth customize login endpoints
I'm very new to Django and I'm using DjangoDjango-rest-auth with standard endpoints (/login, /logout, /registration... ). I need to do some things : If a user is logged in, he can't login from another device/client. I need to set a custom timeout for the session How to do that ? I think I have to write a customLoginView ? : from rest_auth.views import LoginView class CustomLoginView(LoginView): renderer_classes = [JSONRenderer, TemplateHTMLRenderer] But it will override all the login logic, do I need to reimplement myself ? -
Do you know How can fix this problem with the pip install Neo4django?
I have just learning Neo4j and I want to do a web app with Django with Neo4j. I search in google and find the framework Neo4django. When I use "pip install noe4django" I have the error below. I already have tried install Django == 1.4, but it is the same. Also, install first noe4django. Thanks. Using cached https://files.pythonhosted.org/packages/60/75/f692a584e85b7eaba0e03827b3d51f45f571c2e793dd731e598828d380aa/certifi-2019.3.9-py2.py3-none-any.whl Building wheels for collected packages: Django Building wheel for Django (setup.py) ... error ERROR: Complete output from command 'c:\users\backu\onedrive\documentos\dmega\dev\gitknow\ndjango\scripts\python.exe' -u -c 'import setuptools, tokenize;file='"'"'C:\Users\backu\AppData\Local\Temp\pip-install-1nbkx9g3\Django\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\backu\AppData\Local\Temp\pip-wheel-c24wx4zh' --python-tag cp37: ERROR: Traceback (most recent call last): File "", line 1, in File "C:\Users\backu\AppData\Local\Temp\pip-install-1nbkx9g3\Django\setup.py", line 69, in raise RuntimeError('Django 1.4 does not support wheel. This error is safe to ignore.') RuntimeError: Django 1.4 does not support wheel. This error is safe to ignore. ERROR: Failed building wheel for Django Running setup.py clean for Django Failed to build Django Installing collected packages: urllib3, chardet, idna, certifi, requests, neo4jrestclient, Django, six, python-dateutil, lucene-querybuilder, decorator, neo4django -
Django REST Framework URLPathVersioning not working
I followed the guide here to add versioning to our API. This is what the urls.py looks like: from django.conf.urls import url from django.contrib import admin from django.urls import path from api import views urlpatterns = [ url( r'^(?P<version>(v1|v2))/foo/bar', views.foo_bar, ), ] However, when I hit my API with the URL http://localhost:5555/v1/foo/bar I get an error: TypeError at /v1/foo/bar foo_bar() got an unexpected keyword argument 'version' -
Firebase Authentication with Django
I'm building a website with Django which can have registered users. For this registration process, I'm using Firebase Authentication. When I try it in my local machine, in Django debug mode set to true, everything works fine. But, when I turn to my cloud machine, in which debug is set to false and https is used, Firebase Authentication doesn't work. It just don't authenticate users, no error message displayed. This is my login code: <script src="https://www.gstatic.com/firebasejs/5.10.0/firebase.js"></script> <!-- Firebase App is always required and must be first --> <script src="https://www.gstatic.com/firebasejs/5.8.4/firebase-app.js"></script> <!-- Add additional services that you want to use --> <script src="https://www.gstatic.com/firebasejs/5.8.4/firebase-auth.js"></script> <script> // Initialize Firebase var config = { apiKey: "...", authDomain: "...", databaseURL: "...", projectId: "...", storageBucket: "...", messagingSenderId: "..." }; firebase.initializeApp(config); </script> <script> function googleLogin(){ var provider = new firebase.auth.GoogleAuthProvider(); firebase.auth().useDeviceLanguage(); firebase.auth().signInWithPopup(provider).then(function(result) { // This gives you a Google Access Token. You can use it to access the Google API. var token = result.credential.accessToken; // The signed-in user info. var user = result.user; // ... firebase.auth().currentUser.getIdToken(/* forceRefresh */ true).then(function(idToken) { var csrftoken = '{{ csrf_token }}'; $.post("/api/login", {'csrfmiddlewaretoken': csrftoken, 'token': idToken}); document.location.reload(true); }).catch(function(error) { alert("Error al iniciar sesión") // Handle error }); }).catch(function(error) { // Handle Errors here. … -
Django - image not upload
On the site already have some queries related to this, but none of them solved my problem in fact. I have a table without a database with a user table, with a table of my image that shows the image of the user profile. Models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(upload_to='profile_image', null=True, blank=True) def __str__(self): return str(self.user.first_name) Views.py @login_required() def editaFoto(request, id): data = {} foto = UserProfile.objects.get(user_id=id) form = UserProfileForm(request.POST or None, instance = foto) # inicia um formulario com os campos preenchidos data['foto'] = foto data['form'] = form if request.method == 'POST': if form.is_valid(): form.save() return redirect('lista_perfil') else: return render(request, 'sistema/perfil/editafoto.html', data) forms.py class UserProfileForm(ModelForm): class Meta: model = UserProfile fields = '__all__' Editafoto.html {% extends "base.html" %} {% load bootstrap %} {% block title %} Editar Foto {% endblock title %} {% block main %} <div class="container"> <h3>Editar Foto</h3> <div class="row"> <div class="col-sm-6"> {{ foto }} <form action="{% url 'edita_foto' user.id %}" method="POST"> {% csrf_token %} {{ form | bootstrap}} <button type="submit" class="btn btn-success">Salvar</button> <a href="{% url 'lista_perfil' %}" class="btn btn-danger">Cancelar</a> </form> </div> </div> </div> {% endblock main %} Base.html {% load static %} <!DOCTYPE html> <html lang="pt"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, … -
Django 403 Error After Submitting Password Change Form ("CSRF used incorrectly") (may be due to .asview())
After submitting the PasswordChangeForm, I get a 403 response: Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: CSRF token missing or incorrect. In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure: Your browser is accepting cookies. The view function passes a request to the template's render method. In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL. If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data. The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to reload the page with the form, because the token is rotated after a login. You're seeing the help section of this page because you have DEBUG = True in your Django settings file. Change that to False, and only the initial error message will be displayed. You can customize this page using … -
LDAP connect failed: invalid server address
I am using the django_python3_ldap plugin to authenticate logins on my django application (in production) through an ldap server. For some reason it all the sudden doesn't like my server address , even though it is correct and can connect to the same address on my workstation. I get this wsgi error [wsgi:error] [pid 6439] LDAP connect failed: invalid server address I have tried enabling httpd_can_connect_ldap to on, but that didn't fix the problem. What could be the cause of this? -
Accessing multiple schemas from a Django app
Say I have a Postgres DB with schema1 and schema2. I would like my Django application myapp to access data from both schema1 and schema2. I nearly found a workaround solution using app_labels (based on this answer), until I realized this broke the Django admin, and therefore possibly other functionalities. What I tried was to specify a custom app_label in the models' Meta: class OneModel(models.Model): gid = models.AutoField(primary_key=True) name = models.CharField(max_length=40, blank=True, null=True) class Meta: managed = False db_table = 'one_table' app_label = 'myapp_to_schema1' class AnotherModel(models.Model): gid = models.AutoField(primary_key=True) color = models.CharField(max_length=40, blank=True, null=True) class Meta: managed = False db_table = 'another_table' app_label = 'myapp_to_schema2' I then implement two separate routers for myapp, each routing to one of the schemas: class MyappToSchema1Router: def db_for_read(self, model, **hints): if model._meta.app_label == 'myapp_to_schema1': return 'schema1' return None def db_for_write(self, model, **hints): if model._meta.app_label == 'myapp_to_schema1': return 'schema1' return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == 'myapp_to_schema1': return db == 'schema1' return None class MyappToSchema2Router: def db_for_read(self, model, **hints): if model._meta.app_label == 'myapp_to_schema2': return 'schema2' return None def db_for_write(self, model, **hints): if model._meta.app_label == 'myapp_to_schema2': return 'schema2' return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == 'myapp_to_schema2': return db … -
django model permission vs group permissions
My django model looks like this: class testModel(models.Model): ... def has_add_permission(self, request): return False ... My group permission looks like this: employee: testApp | testModel | can add testModel The user can still add objects: It look like the the has_add_permission function is being ignored as the button only disappears when the permission is removed from the group; group permission: can add testModel and has_add_permission returns true Result: Can add test model group permission: can add testModel and has_add_permission returns false Result: Can add test model group permission: cannot add testModel and has_add_permission returns true Result: cannot add test model group permission: cannot add testModel and has_add_permission returns false Result: cannot add test model Is this expected behaviour? -
Django database error: sqlite3.OperationalError: near "SCHEMA": syntax error
I'm integrating a Django app with circleci which is being deployed at heroku. However, after setting up Heroku and installing 'django_heroku' circleci tests keep failing due to some configuration error with the database. I currently do not have a database and just want the tests to run. Any help would be greatly appreciated -
comprehend.start_topics_detection_job Fails with Silent Error?
I have Amazon sample code for running comprehend.start_topics_detection_job. Here is the code with the variables filled in for my job: import re import csv import pytz import boto3 import json # https://docs.aws.amazon.com/code-samples/latest/catalog/python-comprehend-TopicModeling.py.html # https://docs.aws.amazon.com/comprehend/latest/dg/API_InputDataConfig.html # Set these values before running the program input_s3_url = "s3://comprehend-topic-modelling-bucket//input_800_cleaned_articles/" input_doc_format = "ONE_DOC_PER_LINE" output_s3_url = "s3://comprehend-topic-modelling-bucket/output" data_access_role_arn = "arn:aws:iam::372656143103:role/access-aws-services-from-sagemaker" number_of_topics = 30 # Set up job configuration input_data_config = {"S3Uri": input_s3_url, "InputFormat": input_doc_format} output_data_config = {"S3Uri": output_s3_url} # Begin a job to detect the topics in the document collection comprehend = boto3.client('comprehend') start_result = comprehend.start_topics_detection_job( NumberOfTopics=number_of_topics, InputDataConfig=input_data_config, OutputDataConfig=output_data_config, DataAccessRoleArn=data_access_role_arn) # Output the results print('Start Topic Detection Job: ' + json.dumps(start_result)) job_id = start_result['JobId'] print(f'job_id: {job_id}') # Retrieve and output information about the job describe_result = comprehend.describe_topics_detection_job(JobId=job_id) print('Describe Job: ' + json.dumps(describe_result)) . #<===LINE 36 # List and output information about current jobs list_result = comprehend.list_topics_detection_jobs() print('list_topics_detection_jobs_result: ' + json.dumps(list_result)) It's failing with the error: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-8-840a7ee043d4> in <module>() 34 # Retrieve and output information about the job 35 describe_result = comprehend.describe_topics_detection_job(JobId=job_id) ---> 36 print('Describe Job: ' + json.dumps(describe_result)) 37 38 # List and output information about current jobs ~/anaconda3/envs/python3/lib/python3.6/json/__init__.py in dumps(obj, skipkeys, ensure_ascii, check_circular, allow_nan, cls, indent, separators, default, … -
What is the right way to build an intermediate model schema in django
I am having an issue to design my database and create an intermediate table for a specific model. Below is the schema i want to create: (The questionnaire will be a multipleChoice) Course: (Eg. Python) Module: (Eg. Web development, Data science) Quiz : (set of questions related to module) Answer : (Set of answers to Quiz to choose from. Only one choice can be selected) class Course(models.Model): name = models.CharField(max_length=70) profile = models.ManyToManyField(Profile) description = models.CharField(max_length=150, blank=False) number_of_course = models.IntegerField() def get_absolute_url(self): return reverse('courses:module-detail', kwargs={'pk': self.pk}) class Module(models.Model): name = models.CharField(max_length=70) course = models.ForeignKey(Course, on_delete=models.CASCADE) document = models.URLField(max_length=250, blank=True) description = models.TextField(max_length=500) class Quiz(models.Model): title = models.CharField(max_length=100) subtitle = models.CharField(max_length=100, blank=True) description = models.TextField(max_length=1000) module = models.ManyToManyField(Module, through='Answer') class Answer(models.Model): answer_text = models.TextField(max_length=1000, null=True) answer_quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) answer_module = models.ForeignKey(Module, on_delete=models.CASCADE) Above is the way i tried to structure things but for some reason I am not able to makemigrations therefore not to migrate either the Answer table. the terminal return : courses.Answer: (fields.E336) The model is used as an intermediate model by 'courses.Quiz.quiz through', but it does not have a foreign key to 'Couse' or 'Module'. (I have modified table names for the sack of asking this question. … -
Unable to migrate models from django to sql server
I'm trying to learn django and have to use sql server as a data base and unable to migrate models using manage.py migrate I'm using django 2.1.8 Pyodbc python 3.7.3 I've tried to reinstall django, python and even sql server but it didn't solve the problem. On running py manage.py migrate, i get the following error py manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, testApp Running migrations: Applying contenttypes.0001_initial...Traceback (most recent call last): File "C:\Users\Hamza\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Users\Hamza\AppData\Local\Programs\Python\Python37-32\lib\site-packages\sql_server\pyodbc\base.py", line 546, in execute return self.cursor.execute(sql, params) pyodbc.ProgrammingError: ('42S02', '[42S02] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Cannot find the object "django_content_type" because it does not exist or you do not have permissions. (4902) (SQLExecDirectW)') The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\Hamza\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Hamza\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Hamza\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Hamza\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 353, in execute output = self.handle(*args, **options) File "C:\Users\Hamza\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\Hamza\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\commands\migrate.py", line 203, in handle fake_initial=fake_initial, File "C:\Users\Hamza\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\migrations\executor.py", line 117, in … -
How to suppress extra django-created HTML?
I want to create an "clean" HTML document from a django view that the user can save and import into excel. "Clean" in this case means it only contains tags specified in my template without any extraneous tags being added by the back-end. Some part of Django or a Django extension is adding extra unwanted HTML to my final rendered pages. How can I suppress this? For example if I pass the "blank" html template shown below to render: return render(request, 'blank.html') the output contains extra divs and a hidden textarea at the end of the body tag (out put also shown below). I disabled django-debug-toolbar to get rid of most of the extra, back-end html that was being added to my files, however I can't seem to get rid of this last set of extra tags. File: blank.html <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title></title> </head> <body> </body> </html> Output html saved by chrome: <!DOCTYPE html> <!-- saved from url=(0028)http://localhost:57362/test/ --> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title></title> </head> <body> <div style="background: rgba(135, 206, 235, 0.7); border: 3px double; box-sizing: content-box; display: none; pointer-events: none; position: absolute; z-index: 32767;"></div><textarea style="border-radius: 0px; margin: 0px; opacity: 0; position: … -
Querying Django on a derived field
Using Django 1.8 I have an unmanaged model that points to a view in the db and I'm trying to return a queryset based on a derived field. Here is a basic example of the model structure: class Book(models.Model): book_id = models.IntegerField() publisher = models.CharField(max_length=20, null=True) # Can join to Publisher.publisher_name sku = models.CharField(max_length=15, null=True) # Can join to Sku.sku class Meta: managed = False db_table = 'vw_book' class Sku(models.Model): sku = models.CharField(max_length=15) publisher = models.ForeignKey('myapp.Publisher') class Publisher(models.Model): publisher_name = models.CharField(max_lenth=20) region = models.ForeignKey('myapp.Region') class Region(models.Model): region_name = models.CharField(max_length=20) I'm looking for a way to return a queryset of Book based on the region, derived from the publisher as the preferred field and then the sku. It is possible for these fields in Book to refer to different region fields as the data is unlcean and has been derived from multiple sources. I can add a method to the Book model to derive the region, but trying to get a queryset from this is too slow. class Book(models.Model): publisher = models.CharField(max_length=20, null=True) sku = models.CharField(max_length=15, null=True) class Meta: managed = False db_table = 'vw_book' def get_region(self): if not self.publisher: if not self.sku: return '' try: sku = Sku.objects.get(sku=self.sku) return sku.publisher.region.region_name … -
How to count occurences in list with template filters in django and pass them to the template
I have a django app in which I am counting the clicked urls. I am saving the clicked urls in a list in my view. Now I want to iterate through the list and count each occurence (of the urls). Then I want to show each url with the counted number in the template. What I am doing so far looks like this: My view: class AnalyticsIndexView(StaffRequiredMixin, ListView): template_name = 'analytics_list.html' model = UrlTime def get_context_data(self, **kwargs): context = super(AnalyticsIndexView, self).get_context_data(**kwargs) context['url_views_list'] = UrlTime.objects.all() context['total_views'] = UrlTime.objects.all().count context['home_view'] = UrlTime.objects.filter(associated_url='/').count() context['job_list'] = UrlTime.objects.filter(associated_url='/jobs/').count() context['job_detail'] = UrlTime.objects.filter(associated_url='/jobs/{How to pass id??}').count() context['job_'] = UrlTime.objects.filter(associated_url='/jobs/{???id?????}').count() return context Now that works. But I don't want to hardcode the links obviously, also because I don't know which urls will be in it. (that handles my custom middleware). I would like to capture each url in the list, count it, and show link and linkcount in the template. I already tried with Collections but it didn't work as I wanted it. Also with the harcoding I don't know how to do that with links that have a dynamic id.... Anyone has any suggestions? Help is very much appreciated. Thanks! -
pytest - How to patch a method to avoid database call
For the purpose of learning I am trying to write a test that patches Django's authenticate function in order to avoid having to hit the database. The code I have written does not work and I do not understand why. I have scoured the web but am finding a lot of what I read confusing. Any help would be appreciated. I am using Django, DRF, pytest, pytest-django, and pytest-mock. from django.contrib.auth import authenticate from rest_framework.test import APIRequestFactory def test_authtenticate(mocker, user_factory): user = user_factory.build() mocker.patch('django.contrib.auth.authenticate', return_value=user) factory = APIRequestFactory() request = factory.get('/') data = { 'username': user.email, 'password': 'testpassword', } assert user == authenticate(request=request, **data) In the code above user_factory comes from conftest.py and we can assume it works as expected. The error I receive is: E Failed: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it. Again, I want to avoid having to mark the test for db access. Instead, I want to be able to mock authenticate and control its return value. -
how to fix " 'QuerySet' object has no attribute 'posts' "
bookmark model : class Bookmark(models.Model): user = models.ForeignKey(User, related_name='users', on_delete=models.CASCADE) post = models.ForeignKey(Post, related_name='posts', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) class Meta: app_label = 'content' verbose_name_plural = _('Bookmarks') unique_together = [['user', 'post']] I want a query to return the user's bookmarked posts , I tried this one Bookmark.objects.filter(user_id=user.id).order_by('-created_at').posts() and it return this error : AttributeError: 'QuerySet' object has no attribute 'posts'