Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Serializer for fetchiing data from multiple classes
Environment is Python and Django3 I want to make api which retrieve the data from multiple model class. I have models like this , each CountryStat has Country. class Country(models.Model): code = models.CharField(max_length=3,unique=True) name = models.CharField(max_length=50) class CountryStat((models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE,null=True) date = models.DateField(null=True,blank =True) stat = models.IntegerField() Now I want to get the latest Coutry Stat for each Country. So I made the serializer for Country class CountrySerializer(serializers.ModelSerializer): latest_stat = serializers.SerializerMethodField() class Meta: model = Country fields = ('id','code','latest_stat') def get_latest_stat(self,obj): # how can I get the latest stat from CountryStat model ???? Is this the correct idea or how can I make it?? -
How to adding PDF for Admin to view Orders
I have tried to add the option to view order through PDF in the admin panel but I am getting error which I do not know the reason for nor how to fix it. This is what I did step by step. The issue is now that I have tried restart everything but I am still getting the error and can't get the server to start. $ pip install weasyprint django-import-export then I added it in the installed apps 'import_export', Here is the admin.py def order_pdf(obj): return mark_safe('<a href="{}">PDF</a>'.format(reverse('orders:admin_order_pdf', args=[obj.id]))) order_pdf.short_description = 'Order PDF' class OrderAdmin(ImportExportActionModelAdmin): list_display = ['id', order_pdf] here is the views.py @staff_member_required def admin_order_pdf(request,order_id): Order = get_object_or_404(order,id=order_id) html = render_to_string('order/pdf.html',{'order':Order}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="order_{}.pdf"'.format(Order.id) # weasyprint.HTML(string=html).write_pdf(response,stylesheets=[weasyprint.CSS(settings.STATIC_ROOT + 'css/pdf.css')]) weasyprint.HTML(string=html).write_pdf(response,stylesheets=[weasyprint.CSS(settings.STATIC_ROOT)]) return response here is the url.py path('admin/order/(?P<order_id>\d+)/pdf/$', views.admin_order_pdf, name='admin_order_pdf') Here is the traceback Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\A_K\Desktop\Project 4.3\venv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\A_K\Desktop\Project 4.3\venv\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\A_K\Desktop\Project 4.3\venv\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\A_K\Desktop\Project 4.3\venv\lib\site-packages\django\core\management\commands\runserver.py", line 60, in execute super().execute(*args, **options) File "C:\Users\A_K\Desktop\Project 4.3\venv\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Users\A_K\Desktop\Project 4.3\venv\lib\site-packages\django\core\management\commands\runserver.py", line 95, in … -
How do I add Reverse for 'account_login'
Error during template rendering. In template /Library/Framework/Python.framework/versions/3.8/lib/python3.8/site-packages/allauth/templates/base.HTML, error at line 29 Reverse for 'account_login' not found. -
ImportError: cannot import name 'EMPTY_VALUES' from 'django.forms.fields'
I installed djangocms in existing django project, following the instructions: http://docs.django-cms.org/en/latest/how_to/install.html but when I run py manage.py cms check or py manage.py migrate I have this error: File "C:\Users\usuario\Envs\env_cuid_lab\lib\site-packages\cms\forms\fields.py", line 4, in from django.forms.fields import EMPTY_VALUES ImportError: cannot import name 'EMPTY_VALUES' from 'django.forms.fields' (C:\Users\usuario\Envs\env_cuid_lab\lib\site-packages\django\forms\fields.py) -
How can I make a search form working with "Name Surname"
Basically the issue is that at the moment my search bar is working if I search the exact "Name" or the exact "Surname", however, I would like it to work also if a user searches "Name Surname" or even if the user misspells the name or the surname but at least one of the two is correct. def search(request): query = request.GET.get("q", None) qs = DeathAd.objects.all() if query is not None: qs = qs.filter( Q(nome__icontains=query) | Q(cognome__icontains=query) ) context = { "object_list": qs, } template = "search.html" return render(request, template, context) -
websolr/heroku/django: How to set up solr as a separate service
I am trying to deploy my Django app on Heroku that uses calls to solr to field user queries. I added websolr as an addon to Heroku, but the websolr docs only describe how to configure clients like Django-Haystack. Since my app has users searching a static index and not Django models that need to be updated, and I already have schema.xml, solrconfig.xml, etc. and a json file to index that I know works, I don't want to try to recreate this using Django models for no reason. How do I get websolr to run solr based on these files that I provide instead of embedded to my app through a client? -
Can't log into a commandline created superuser using Django but account gets created
I have created a superuser that i can't log into, using the docker-compose.yml commands: sh -c "sleep 5 && #<snip> echo A-fj... create superuser acct... && echo DJANGO_SUPERUSER_PASSWORD=$DJANGO_SUPERUSER_PASSWORD && echo DJANGO_SUPERUSER_EMAIL=$DJANGO_SUPERUSER_EMAIL && echo DJANGO_SUPERUSER_USERNAME=$DJANGO_SUPERUSER_USERNAME && python manage.py createsuperuser --noinput --username $DJANGO_SUPERUSER_USERNAME --email $DJANGO_SUPERUSER_EMAIL && echo Z-fj... create superuser acct... done. && #<snip> sleep 5 " The environment variables display perfectly, and an account gets created that i can see in the db using dBeaver. When i manually add a second user via "$python manage.py createsuperuser" dialog, i end up with an account that i can log into. When i copy the password from User2 to User1, i can then log into User1 using User2 password, so it seems to be a password thing. When i compare the passwords from User1(orig) and User2(new), they look to be different formats... see the screenshot. I'm not sure, but thinking it may be a clue to the problem... Password1 is shorter and has no sections where Password2 is longer... Password1: !GSU8f8hmNOl1oJBfe1Epk7ocJiXXWQQp3G0mh9TC Password2: pbkdf2_sha256$120000$IAkHkB3ME9aB$p0hrZPkLeSWK0IafqVQ1dEtR5kgBol7WnU7QELoo6KE= I've tried a few different passwords, just in case, but no go -
How can we build robust follow system in website by djnago?
Well if you are django user and build follow system on website than please answer that with code for new students who start learning django like me. Many many thanks in advance who will answer this question. -
Trying to load a ML model in Django in order to classify user submitted images
I have made a small image classifier that I want to use in my website. I have it working locally. My view is something a long the lines of from .predict import classify def index(request): if request.method == 'POST': form = MyImageClass(request.POST, request.FILES) if form.is_valid(): cd = form.cleaned_data context = classify(cd) return render(request, 'my_html.html', context) ... Where the problem is in predict.py, I have def classify(cd): loaded_model = tf.keras.model.load_model(filepath=r'C:\Django Projects\my_project\my_app\trained_model') ... return context As I said, the above works, but I would like to be able to load the model with a relative file path instead. I have tried both saving as a SavedModel and as an h5 file as done here. When I run tf.keras.model.load_model('my_model.h5') (say in main.py) in python, I have no problem with the file being in the same directory as the file main.py, but if I have the same code as part of predict.classify, I get OSError: SavedModel file does not exist at my_model.h5/{saved_model.pbtxt|saved_model.pb} while using my website via py manage.py runserver. I'm guessing the issue might have to do with static files? I'm not too sure. Any help would be greatly appreciated. -
Only show in Django Admin the facilities that belong to the customer for which the work order is being created
In myApp I have a Client who owns different ClientFacility. I also have a Project which is done for a Client. In addition I have Orders that belong to a Project (and indirectly to a Client). The Orders for a Project will be performed only on ClientFacility owned by the customer associated to the Project. I was trying to understand the filtering of many to many on this question but I couldn't because I don't know how to get my project_number dynamically In myApp admin section (http://127.0.0.1:8000/admin/myApp/), every time I create an Order, I would like to show only the ClientFacilities associated with the Client of the Project the Order belongs to. How can I do this and on which .py of myApp? Right now the ManyToManyField displays every single ClientFacility on my database which is not adequate. If the way in which I have established the relationships between my models is not correct it is fine, I want to learn. Please provide some guidelines, links, examples, etc instead of saying this is all wrong and it has to be changed. This is my code: class Project(models.Model): project_number = models.IntegerField(unique=True,primary_key=True) project_name = models.CharField(max_length=400) client = models.ForeignKey("Client", on_delete=models.CASCADE,verbose_name = "Customer of … -
Django (Models): Automatically pick and return a value by the choice option
I'm building a simple sys which selects a link by given value. So imagine a user is posting a post and he has to select the type of the post for example (old, new, classic). And this is what I've got right now: MarkerIcons = ( # We can choose between: ('0', _('https://i.imgur.com/U8ddIZs.png')), # POLICE CAR2 (InUse) ('1', _('https://i.imgur.com/ec2VbzA.png')), # POLICE RAID ('2', _('https://i.imgur.com/kM9Ppou.png')), # PASSENGER_CONTROL # Camera's ('3', _('https://i.imgur.com/VDUPhLx.png')), # TRIPOD ('4', _('https://i.imgur.com/MpiJ8st.png')), # SPEED CAMERA & other img - https://i.imgur.com/EbItaVR.png # Extra's- ('5', _('https://i.imgur.com/w00r7kC.png')), # ACCIDENT ('6', _('https://i.imgur.com/fykUX9D.png')), # TRAFFIC JAM ('7', _('https://i.imgur.com/ooZDKug.png')), # CONSTRUCTION_WORK ('8', _('CAR_STOPPED')), # ('9', _('OTHER')), # ('10', _('UNKNOWN')) # ) This is what I'm trying to use to automatically return the link from the choices. marker_icon = models.CharField(choices=MarkerIcons, blank=False, null=False, max_length="40", default='0') What's the correct method to select and insert the link of the choices to the Database? I want to do something like this: If the CharField default or given value is - "2", I set the current model Charfield value to 'https://i.imgur.com/kM9Ppou.png' But this does not work as it should, In the previous attempts I was using IntegerField, but I realized that IntegerField couldn't store link because it's a string. This … -
Mocking returns magicmock object instead of return value python django?
I am trying to mock an external HTTP request but for some reason instead of the return value, it returns a magic mock object.Also,can someone guide me on how I can avoid passing actual headers and pass some mock object for headers. This is what I have tried so far app1/utils/ def send_sms(url,headers,data): response = requests.post(url, headers=headers, data=data) content = response.content return content app1/tests @patch('app1.utils.requests') def test_at_sms(self,mock_obj): data = { 'username': 'sandbox', 'to': '+28292992929', 'message': 'Hello', } fake_data = {'hello':'world'} mock_obj.return_value.content.return_value = fake_data headers = {'apikey': 'aydkdjkfdjdfjf', 'content-type': 'application/x-www-form-urlencoded', 'accept': 'application/json'} r = send_sms('https://api.sandbox.africastalking.com/version1/messaging', headers, data) self.assertEqual(r,fake_data) This is what I receive AssertionError: <MagicMock name='requests.post().content' id='139645974661872'> != {'hello': 'world'} -
ModuleNotFoundError: No module named 'my_app’, app already in INSTALLED_APPS
I’m trying to deploy my Django app through Heroku but I’m getting a ModuleNotFound error after running a production environment with gunicorn wsgi path. My app is included in settings.py and it was working fine while in the development environment. But now I’m getting errors for deployment. I have problems with how my project is structured, thus Procfile does not leave in the same directory as manage.py, and I believe this could be the issue. Any hint or help is more than appreciated. Directory structure >FINALPROJECT(root) > .vscode > project5 > brainSkills > migrations > static > templates apps.py models.py urls.py views.py > project5 _init_.py settings.py wsgi.py _init_.py manage.py > venv .env .gitignore Procfile README.md requirements.txt Procfile web: gunicorn project5.project5.wsgi wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project5.project5.settings') application = get_wsgi_application() setting.py import os from pathlib import Path from dotenv import load_dotenv INSTALLED_APPS = [ 'brainSkills', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] ROOT_URLCONF = 'project5.urls' WSGI_APPLICATION = 'project5.wsgi.application' Error after gunicorn project5.project5.wsgi or Heroku local 5:32:28 PM web.1 | File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module 5:32:28 PM web.1 | return _bootstrap._gcd_import(name[level:], package, level) 5:32:28 PM web.1 | File "<frozen importlib._bootstrap>", line 1014, in _gcd_import 5:32:28 PM web.1 | … -
Requests is not working in one of my DJANGO project
I am having trouble with requests package and I tried my best to resolve this problem. Problem- requests is not working in one of my Django Projects. It returns 403 Forbidden. But the same code is working on my other Django Project (Same laptop with same internet connection, but different virtual environment). So, because of this I am not able to use requests package in one of my existing Django Project. Here is the code: This is the demo code which I will run on two Django Project with two different virtual environment. import requests from bs4 import BeautifulSoup from django.shortcuts import render # from .models import RequestData def home(request): data = [] urls = [ "https://api.github.com/search/repositories", "https://www.dataquest.io", "https://www.python.org", "https://api.github.com/events" ] for url in urls: r = requests.get(url) soup = BeautifulSoup(r.text, 'html.parser') if soup.title: data.append(str(soup.title)) else: data.append("No Title") return render(request, "requester/index.html", {'data': data}) Here is my HTML part: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> {% for dat in data %} <li>{{dat}}</li> {% endfor %} </body> </html> Here are my responses from both the Django project. First (Which have problem) Second(Without any problem) Also, I tried with different versions of … -
How to use TabularInline in Django E-commerce Project
I am trying to show the orderitemsadmin in the orderadmin using TabularInline but I keep getting different errors like the following error. AttributeError: 'OrderItemAdmin' object has no attribute 'urls' and django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'auth.User' that has not been installed This is a Django e-commerce project and I am trying to facilitating the admin viewing the orders and their items. I don't have much experience in using TabularInline that is why I am not able to do it corrrectly or what might be the mistake that I am doing. Here is the admin.py class OrderItemAdmin(admin.TabularInline): list_display = ['item', 'quantity', 'ordered'] model = OrderItem raw_id_fields = ['item'] class OrderAdmin(admin.ModelAdmin): list_display = ['user', 'ordered', 'ordered_date', 'coupon', 'payment', 'shipping_address', 'status', 'refund_requested', 'refund_granted', 'ref_code'] inlines = [ OrderItemAdmin, ] admin.site.register(OrderItem, OrderItemAdmin) admin.site.register(Order, OrderAdmin) Here is the models.py class OrderItem(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) class Order(models.Model): items = models.ManyToManyField(OrderItem) -
How to paginate Django Admin for Order Model
In my E-commerce Project, Everytime I click on the orders model in Django Admin, it takes a while to load, so I thought the reason might be because of the many orders in the page which is not paginated. So my question is how to paginate the order.model in Django Admin, second is this the reason why it is the only page that is taking a while to load or might there be another reason that I should be thinking of? Here is the models.py class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ref_code = models.CharField(max_length=20, unique=True, blank=True, null=True) items = models.ManyToManyField(OrderItem) --------------------------------------- Here is the admin.py class OrderAdmin(admin.ModelAdmin): list_display = ['id', 'user', 'ordered', 'ordered_date', 'coupon', 'payment', 'shipping_address', 'status', 'refund_requested', 'refund_granted', 'ref_code'] list_display_links = [ 'id', ] list_editable = ['status'] list_filter = ['ordered', 'ordered_date', 'refund_requested', 'refund_granted', 'status'] search_fields = [ 'user__username', 'ref_code' ] actions = [make_refund_accepted] -
How to Paginate a Django View inside a loop
I was looking into the pagination offered by Django 3.0, and I was wondering how to implement pagination from inside a loop. For example, take this snippet where I retrieve a collection of images based on some selected categories and display the images. There are ~800 images per category, and 12 categories. What I would like to have is the category name at the top of the page, 20 or so images, the the page indicators. class MyPage(View): def get(self, request): q_dict = request.GET sets = [] # the full data set to display on the page - a list of dictionaries for category in categories: document_ids = list(DocumentMetaData.objects.filter(metadata__has_key=category).values('document_id', flat=True)) images = [] for doc_id in document_ids: image = DocumentImage.objects.get(document=doc_id) params = {'ID': doc_id, 'Category': category} detail_url = encode_urls('details.html', params) urls = {'image_url': image.xsmall_file.url, 'detail_url': detail_url} images.append(urls) # the dictionary contains the data to display on the page sets.append({'header': category.name, 'images': images, }) paginator = Paginator(sets, 20) # 20 images in each page if 'page' in q_dict: page = q_dict['page'] else: page = 1 try: page_obj = paginator.page(page) except PageNotAnInteger: # If page is not an integer deliver the first page page_obj = paginator.page(1) except EmptyPage: # If page is … -
Django | CSRF Verification Failed
I'm building a Django powered blog-like app for practice and learning. I'm working on setting up a form for users to leave comments on posts. I have a Post model that takes in a User foreign key, and a Comment model that takes in a User foreign key and a Post foreign key (to identify the post the comment is tied to). I know the way I have it setup is not yet functional, but I'm just trying to debug a CSRF issue I keep having. Here's my code: models.py class Comment(models.Model): date_posted = models.DateTimeField(default=timezone.now) content = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) views.py @login_required def post_detail(request, post_id): if request.method == 'POST': print("posted") return redirect('Home') else: comment_form = CommentForm() context = { 'post': Post.objects.get(id=post_id), 'comments': Comment.objects.order_by('date_posted'), 'comment_form': comment_form } return render(request, 'feed/postdetail.html', context) template, "postdetail.html" <form method="POST" enctype="text/plain"> <div class=comment-line> {% csrf_token %} {{ comment_form }} <button type="submit">Post</button> </div> </form> And I DO have the following in my middleware 'django.middleware.csrf.CsrfViewMiddleware', I keep getting an error stating, "CSRF verification failed. Request aborted" for the reason "CSRF token missing or incorrect." This only happens when I click the post button. I'm only just learning Django, what am I doing … -
Is there a way to connect a model object with another object?
So i have a problem where I have two models; ORDER and ORDERITEM, as seen before class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) post = models.ForeignKey('blog.Post', on_delete=models.SET_NULL, blank=True, null=True) #post = models.ForeignKey('OrderItem', related_name='oi', on_delete=models.SET_NULL, blank=True, null=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=False) transaction_id = models.CharField(max_length=200, null=True) qr_code = models.ImageField(upload_to='qrcode', blank=True) def __str__(self): return str(self.transaction_id) class OrderItem(models.Model): post = models.ForeignKey('blog.Post', on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.post.title This is how it works, when a user makes an order it goes to the orderitem, when its order is completed, it goes to Order model, now, i want to be able to get the Post the user purchased from Order (not Orderitem) Model, i can get it from OrderItem, because presently with the code abov Order models does not show the particular post purchased, it just shows a list of all the posts. I really need to get the Post purchased from Order because im building a notification system using signals and it has to be from Order (which is created when the user FINISHES the process of making an order). I hope you get me, … -
Docker and Django – keep everything up to date & secure
I am new to Docker and begin to understand how that whole thing works. My final goal is to deploy my Django project (which at the moment is running locally) to Google Code Run or a similar service, but there is still a way to go. Actually, thanks to this book, I already got my project running within a Docker container locally on my Mac, which is great. My Dockerfile starts with FROM python:3.8 and contains COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv && pipenv install --system So every time I build my container, updates wich are available for Linux, Python, Django and other packages I am using are included automatically, I guess (unless I declare otherwise e.g. for packages in my Pipfile). The idea is to develop the app locally and test everything using Docker on my Mac. When it comes to updates, I have to check if everything is still consistent. If everything works fine locally, I (later) can deploy the container to somewhere else and everything should be fine. Am I basically right or did I miss something important? -
URL parameters don't select designated options in select2 drop-down
I have created URL parameters on my site. For example, I have multiple custom widgets including a calendar, toggle switches, and more. My question is when I access a certain URL with my parameters I get the right plot/graph, but the options selected in my drop-down won't get selected? The parameters get applied to all my other widgets, but my select2 drop-down. It definitely takes in the right options selected, but won't display to let the user know the parameters passed were successful. I hope I am making sense, but to sum it all up when I pass my desired parameters my site will load as expected. However, the options will not get selected and display to the user. The URL parameters were created using a GET request. Here's my js file $(document).ready(() => { $.fn.select2.amd.require([ 'select2/utils', 'select2/dropdown', 'select2/dropdown/attachBody' ], function (Utils, Dropdown, AttachBody) { function SelectAll() { } SelectAll.prototype.render = function (decorated) { var $rendered = decorated.call(this); var self = this; //define the buttons inside the menu var $selectAll = $('<input type="checkbox"> Select/Unselect All</input>' ); //append the buttons inside the menu $rendered.find('.select2-dropdown').prepend($selectAll); // Pass in an array to our value to select all. // Check if checkbox has been … -
The 'Access-Control-Allow-Origin' is not included on response header for images
I'm developing a simple web app, using Nuxt for the frontend and Django for the backend. The Django API has 2 endpoints, tag and product, and in the product endpoint there's a image_url value, which contains the link to a JPEG file, stored in a Django server sub-directory called media. Since both apps are being served on different ports (frontend in 3000; backend in 8000), I needed install the CORS headers package for django, and I configured it like this (on settings.py): CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOW_CREDENTIALS = True CSRF_TRUSTED_ORIGINS = ( '<my-host>:3000', '<my-host>', ) CORS_ALLOW_METHODS = ( 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ) CORS_ALLOW_HEADERS = ( 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ) CORS_ORIGIN_WHITELIST = [ 'http://<my-host>:3000', ] Then, on the frontend, I use axios for the HTTP request. The strange thing (at least for me) is that the CORS headers are included in every request made to the API, but not on the images. So, with an HTTP request for http://<my-host>:8000/product/1, the response includes (among other things) this: { "id": 1, "image_url": "http://<my-host>/media/images/1/20200916113917386794.jpg" ... } By examining the Network tab, on Chrome's DevTools, I see the following response headers from http://<my-host>:8000/product/1: Access-Control-Allow-Credentials: true Access-Control-Allow-Origin: http://192.168.33.11:3000 … -
Querying related model-attributes in django
I have the following custom user model arrangement. ``` class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) class StudentProfile(models.Model): student = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) location = models.CharField(max_length=8, blank=False, default='') class TeacherProfile(models.Model): teacher = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) gender = models.CharField(max_length=8, choices=GENDER_CHOICES, default='') ``` I am able to a query the students based on the location of their teacher (current user). Student.objects.filter(location=request.user.teacher.location) I can also query the user model & find all teachers/students User.objects.filter(is_teacher=True) QUESTION: Without relying on the profile models (Student & Teacher) How can I extend the query on abstractuser using profile attributes. [X]-This is wrong but the idea is something like; User.objects.filter(is_teacher=True).filter(is_teacher.location=newyork) -
Python job matching query does not exist with get_previous_by_start_dt
We are seeing the error Job.DoesNotExist: Job matching query does not exist and normally I would know what to do, only this time we are using a native method # get previous job for the same brand def previous_job(self): return self.get_previous_by_start_dt(brand=self.brand, status='finished') or None I was reading this for an asnwer but no success: Django error - matching query does not exist question: how do I implement the same error free logic with try/catch or some other method for get_previous_by_start_dt? File "/var/www/html/shirts/scrapy/sohb2bcrawlers/db_tool/db_app/models.py", line 75, in previous_job return self.get_previous_by_start_dt(brand=self.brand, status='finished') or None File "/usr/lib/python3.6/site-packages/django/db/models/base.py", line 960, in _get_next_or_previous_by_FIELD raise self.DoesNotExist("%s matching query does not exist." % self.class._meta.object_name) db_app.models.Job.DoesNotExist: Job matching query does not exist. -
Django deployment variables
I have a development app running locally. I have a production app running on my server. I would like to keep developing locally and push my changes. However, the dev version uses local postgres and the static and media files reside inside the project. The server version the static and media files are in a static public_html directory served by apache. Can I have a local static and media files as well as different postgres credentials on localhost than on the server? How do I accomplish that?