Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Does neo4j desktop includes a usable neo4j database
I have installed neo4j desktop and I am able to use neo4j database from it. The problem is when I try to connect to neo4j database from a Django project. I have configured my settings.py with config.DATABASE_URL = 'bolt://neo4j:neo4j@localhost:7687', but when I run neomodel_install-labels, I get this error: Connecting to bolt://neo4j:neo4j@localhost:7687 Traceback (most recent call last): File "/Users/hugovillalobos/Documents/Code/AttractoraProject/AttractoraVenv/lib/python3.6/site-packages/neo4j/bolt/connection.py", line 578, in _connect s.connect(resolved_address) ConnectionRefusedError: [Errno 61] Connection refused During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/hugovillalobos/Documents/Code/AttractoraProject/AttractoraVenv/bin/neomodel_install_labels", line 67, in <module> main() File "/Users/hugovillalobos/Documents/Code/AttractoraProject/AttractoraVenv/bin/neomodel_install_labels", line 62, in main db.set_connection(bolt_url) File "/Users/hugovillalobos/Documents/Code/AttractoraProject/AttractoraVenv/lib/python3.6/site-packages/neomodel/util.py", line 65, in set_connection max_pool_size=config.MAX_POOL_SIZE) File "/Users/hugovillalobos/Documents/Code/AttractoraProject/AttractoraVenv/lib/python3.6/site-packages/neo4j/v1/api.py", line 94, in driver return Driver(uri, **config) File "/Users/hugovillalobos/Documents/Code/AttractoraProject/AttractoraVenv/lib/python3.6/site-packages/neo4j/v1/api.py", line 133, in __new__ return subclass(uri, **config) File "/Users/hugovillalobos/Documents/Code/AttractoraProject/AttractoraVenv/lib/python3.6/site-packages/neo4j/v1/direct.py", line 7 3, in __new__ pool.release(pool.acquire()) File "/Users/hugovillalobos/Documents/Code/AttractoraProject/AttractoraVenv/lib/python3.6/site-packages/neo4j/v1/direct.py", line 4 4, in acquire return self.acquire_direct(self.address) File "/Users/hugovillalobos/Documents/Code/AttractoraProject/AttractoraVenv/lib/python3.6/site-packages/neo4j/bolt/connection.py", line 453, in acquire_direct connection = self.connector(address, self.connection_error_handler) File "/Users/hugovillalobos/Documents/Code/AttractoraProject/AttractoraVenv/lib/python3.6/site-packages/neo4j/v1/direct.py", line 7 0, in connector return connect(address, security_plan.ssl_context, error_handler, **config) File "/Users/hugovillalobos/Documents/Code/AttractoraProject/AttractoraVenv/lib/python3.6/site-packages/neo4j/bolt/connection.py", line 707, in connect raise last_error File "/Users/hugovillalobos/Documents/Code/AttractoraProject/AttractoraVenv/lib/python3.6/site-packages/neo4j/bolt/connection.py", line 697, in connect s = _connect(resolved_address, **config) File "/Users/hugovillalobos/Documents/Code/AttractoraProject/AttractoraVenv/lib/python3.6/site-packages/neo4j/bolt/connection.py", line 587, in _connect raise ServiceUnavailable("Failed to establish connection to {!r} (reason {})".format(resolved_address, error.errno)) neo4j.exceptions.ServiceUnavailable: Failed to establish connection to … -
Django button in html templace creates error that I cant solve
my code is simple but I admit I have taken it from the internet. I want to update a model with a button click. Which model, it is chosen by the variable. So I have this html code: <form action="{% url 'reception:update_status' slug=name %}" method="POST"> {% csrf_token %} <input type="submit" value="has arrived"> </form> This code is in url.py path('update_status/(?P<slug>[-a-zA-Z0-9_]+)$', views.update_status, name='update_status'), and in views.py def update_status(request, slug): if request.method == 'POST': p = MyModel.objects.filter(name=slug) p.status = 'is waiting' p.update() return redirect(request, 'home') Now with the code like this it comes back with the following error when I click on the button! Reverse for '<WSGIRequest: POST '/update_status/(%3FPName10%5B-a-zA-Z0-9_%5D+)$'>' not found. '<WSGIRequest: POST '/update_status/(%3FPName10%5B-a-zA-Z0-9_%5D+)$'>' is not a valid view function or pattern name. and I have no clue what this means. Please help? Thanks -
Creating dependent extjs grids
I just started to study extjs 6. How it is possible to implement dependent grids when the main displays data from the table, when clicked on, in the second grid, the dependent entries from the second table are displayed. What I realized at the moment: I created a grid, I get the records from the "Operation" table, I call it using the CRUD. In the "Operation" table, all entries are associated with the second table (numoperation) in the code field. It is required to me that at pressing on record of the main grid which is already created, to receive dependent records from the table numoperation in the second grid. How can this be implemented in general? I would be glad if you share useful links, tips or examples. Thank you in advance. Below is the code for the client part of the application: Ext.onReady(function () { Ext.define('Operation', { extend: 'Ext.data.Model', idProperty: 'id', fields: [ { name: 'id', type: 'int' }, 'date_op', 'code', 'status', 'type' ] }); var urlRoot = 'data?model=Operation&method='; var registrStore = Ext.create('Ext.data.Store', { model: 'Operation', pageSize: 10, proxy: { type: 'jsonp', noCache: false, api: { create: urlRoot + 'Create', read: urlRoot + 'Read', update: urlRoot + 'Update', … -
Permanently Redirect http to https on Google App Engine Flexible with Django
I'm working on a project that uses Google Cloud Platform's App Engine in the Python 3 Flexible Environment using Django, and I'm trying to permanently redirect all requests over http to https for all routes, but so far have not been successful. I can access the site over https, but only if explicitly written in the address bar. I've looked at this post: How to permanently redirect `http://` and `www.` URLs to `https://`? but did not find the answer useful. The app works properly in every sense except for the redirecting. Here is my app.yaml file: # [START runtime] runtime: python env: flex entrypoint: gunicorn -b :$PORT myapp.wsgi handlers: - url: /.* script: myapp.wsgi.application secure: always redirect_http_response_code: 301 runtime_config: python_version: 3 # [END runtime] I've also tried setting script to just myapp.wsgi (same result) and just leaving script out entirely (which produces an error). I haven't changed anything in the default myapp/wsgi.py generated by startproject or done anything explicitly involving that file. Is there something I'm missing or doing wrong to cause the redirect not to happen? -
Django Admin app's contents are not being displayed
For some reason, The contents of the database containing the list of all the Projects is not being displayed on my Projects/Issues page for some reason. I recently added a feature to my software making it such a way that everytime I click on save in the Issues page, an email is sent to the Admin and the Person who is concerned. Ever since I added that feature, my Website stopped displaying the contents but it displays the Number of contents in my List. UPDATE the 1st entry on the Project page doesn't show up. the title of the table doesn't show up either. But when I add the 2nd entry, the 2nd entry shows up, but the 1st doesn't. Im using SQLite. Ill be using MySQL for production. In my Issues/Bugs table None of my entries show up, neither does the title of the table show up. Which means, I cant delete the entries or make any changes to the entires I have made so far. Could someone help me out? Here's my Models.py from django.db import models # Create your models here. from django.contrib.auth.models import User from django.db import models from django.core.mail import EmailMessage # Create your models … -
Django: How display effectively data in my template ?
I save users availability in my database in the form of numbers. 1 user is available, 0 not available. For example if a user is available Monday morning and evening but not during the day, in my database I will have "101" Now I want to show to my users their availabilities. My idea was that for each case, I will create and show them a different image. Unfortunately, there is too much possibilities for 7 days. My question is how can I display effectively this data in my template ? I started to write my views, here it is: if request.user.is_authenticated: try: name = coach.objects.get(user=request.user) except coach.DoesNotExist: name = coach(user=request.user) objs = Lesson.objects.all().filter(mycoach = name) args = {'objs': objs} if name.monday=="111" and name.tuesday=="111" and name.wednesday=="111" and name.thursday=="111" and name.friday=="111" and name.saturday=="111" and name.sunday=="111" : args['image_url'] = static('img/111111111111111111111.pdf') if name.monday=="011" and name.tuesday=="111" and name.wednesday=="111" and name.thursday=="111" and name.friday=="111" and name.saturday=="111" and name.sunday=="111" : args['image_url'] = static('img/011111111111111111111.pdf') messages.add_message(request, messages.INFO, 'Welcome to your profile') return render(request, 'Task.html', args) else: return render(request, 'home.html') -
Django send data to Javascript in template
I want to make a very simple network graph for some links between documents that I've extracted, and display it in an existing Django application. I've looked at a bunch of Bokeh/Django integrations and things along those lines but nothing seems appropriate. Therefore I've decided to go ahead and try D3. I don't know any Javascript. I copied the template provided here: http://bl.ocks.org/mbostock/2706022 and this is fine for my purposes. All I need to do is to provide my own data. I can build up a list of dictionaries in the view and pass these as a context. I can access that context in the template with {{ data }}. However, what I don't know how to do is to then feed that to the javascript. This is the relevant part that I'll need to change: var links = [ {source: "Microsoft", target: "Amazon", type: "licensing"}, {source: "Microsoft", target: "HTC", type: "licensing"}, {source: "Samsung", target: "Apple", type: "suit"}, {source: "Motorola", target: "Apple", type: "suit"}, {source: "Nokia", target: "Apple", type: "resolved"}, ... {source: "Nokia", target: "Qualcomm", type: "suit"} ]; This looks like a list of dictionaries. But I don't know, there's some bare words in there so I'm not sure how … -
Combine two query sets based on shared field
I have two query sets that look like this: product_first = Reports.objects.filter(product='product1', type='week', profile__team=team).select_related('profile') product_second = Reports.objects.filter(product='product2', type='week', profile__team=team).select_related('profile') Each of those share obj.profile.user.username, and have other similiar attributes (obj.total, for instance) - I am trying to end up with a query set based on obj.profile.user.username, but with the obj.total being product_first.total + product_second.total. Example of that table I'm querying: user_id total total_items product type 1 150 15 product1 week 1 180 19 product2 week -
How to change internal Django representation of date?
Now I have this format of time using datetime.datetime or django.utils.timezone. 2018-08-26 I need this and hours, minutes, seconds. Using sqlite and python3.6. Origin of problem is that only days are distinguishable. Need seconds. -
How to effencientively hit the database for a related field in REST serializer?
I have a complex architecture for my database and I'm having troubles writting the corresponding REST API. Context: I am requesting various informations on a public API every hour, including data I want to keep history for. Here's the models I am using class Player(models.Model): name = models.CharField(max_length=255) class PlayerStatsHistory(models.Model): player = models.ForeignKey('Player', null=True, on_delete=models.CASCADE) last_refresh = models.DateTimeField(null=True) ... This way, I can store every change in the stats of each user. I wrote 2 serializers one for Player and one for PlayerStatsHistory. The easiest one works fine class PlayerClanStatsSerializer(HyperlinkedModelSerializer): class Meta: model = PlayerClanStatsHistory fields = (...) But when I need to request the latest stats for one player I'm getting confused : class PlayerSerializer(HyperlinkedModelSerializer): details = SerializerMethodField() def get_details(self, obj): return PlayerClanStatsSerializer(PlayerClanStatsHistory.objects.filter(player=obj).order_by('-last_refresh').first()).data class Meta: model = Player fields = ('tag', 'name', 'last_refresh', 'details') This works fine, but will hit database at each player provided to the PlayerSerializer and I feel like I'm doing it wrong. How can I improve this solution ? -
Django: class 'Project' does not define '_add_', so the '+' operator cannot be used on its instances
In the following code, for some reason, after using the foreign key for the project name, at the def __str__(self): part, on the 2nd like where it says return self.Project + ' (' + self.Situation_Type + ') ' + ' [' + self.Status + '] ' at the self.Project part, it shows me an error saying, class 'Project' does not define '_add_', so the '+' operator cannot be used on its instances This inspection detects names that should resolve but dont. Due to dynamic dispatch and ducttyping, this is possible in a limited but useful number of cases. Top-level and class level items are supported better than instance items. Ever since this error started coming up, My Projects page has been displaying nothing in the list, but it says that there is 1 item. What could be the issue? from django.db import models # Create your models here. from django.contrib.auth.models import User from django.db import models from django.core.mail import EmailMessage # Create your models here. class Project(models.Model): STATUS_CHOICE = ( ('Project Manager', 'Project Manager'), ('Technician', 'Technician'), ('Tester', 'Tester') ) STATUS_CHOICE_1 = ( ('Work Assigned', 'Work Assigned'), ('Work in Progress', 'Work in Progress'), ('Testing', 'Testing'), ('Completed', 'Completed') ) Project_Name = models.CharField(max_length=100) … -
Django: CreateView don't show field and set it to request.user (ForeignKey)
I use a generic CreateView to let logged in users (Creator) add objects of the model Piece. Since creating a Piece is done by the Creator (logged in user) there is no need for the CreateView to either show or manipulate the 'creator' field. Hence I wish to not show it and set it to the logged in user. However, approaches such as overwriting form_valid or using get_form_kwargs seem not to get it done. Using the form_valid method gives a ValueError: Cannot assign "<SimpleLazyObject: <User: patrick1>>": "Piece.creator" must be a "Creator" instance. The solution seems to be just around the corner, I hope. Tried but did not work: form_valid method, form_valid method, get_form_kwargs method My code: models.py class Piece(models.Model): creator = models.ForeignKey('Creator', on_delete=models.SET_NULL, null=True) title = models.CharField(max_length=200) summary = models.TextField(max_length=1000, help_text='Enter a brief description of the Piece') created = models.DateField(null=True, blank=True) ... from django.contrib.auth.models import User class Creator(models.Model): ... user = models.OneToOneField(User, on_delete=models.CASCADE) ... views.py class PieceCreate(LoginRequiredMixin, CreateView): model = Piece fields = ['title', 'summary', 'created'] initial = {'created': datetime.date.today()} def form_valid(self, form): obj = form.save(commit=False) obj.creator = self.request.user return super(PieceCreate, self).form_valid(form) success_url = reverse_lazy('pieces') Any suggestions are highly appreciated! -
passing multiple ids into url Django
Hi I am trying to send the user back to the html file however when I used the following code in my view function: def delete_topic(request, topic_id): """ Delete Topic """ topic = Topic.objects.get(id=topic_id) topic.delete() return HttpResponseRedirect(reverse('blogging_logs:topics')) its giving me a NoReverseMatch error and I can't seem to figure out why. I notice that my view function for topics requires category_id but I am not sure how to pass multiple ids. here is my topics view def topics(request, category_id): """Show all topics for a single category""" category = Category.objects.get(id=category_id) # get category that was requested topics = category.topic_set.all() # get all topics associated with category that was requested context = {'category': category, 'topics': topics} return render(request, 'blogging_logs/category.html', context) Here is the html page for where the delete_topics def is being used. topic.html {% block content %} <h3>{{ topic }}</h3> {% for entry in entries %} <p>{{ entry.text|linebreaks }}</p> {% empty %} <li>No entry entered yet!</li> {% endfor %} <a href="{% url 'blogging_logs:entry' topic.id %}"> Add entry </a> <a href="{% url 'blogging_logs:delete_topic' topic.id %}">Delete Topic</a> {% endblock content %} I tried to add a second id (category.id) to the url (delete_topic) in topic.html but it gave me an error. I am … -
Django read files from directory and save their names in database
I am reading files from a directory and want to store the name of the files to the database table(postgresql). The problem is that the code first create an instance on the table on the first iteration and after that updates that record instead it should create the second instance until all file names are stored. for image in glob.glob(path): if not os.path.isfile('thumbnails/' + os.path.basename(image)): print(image,"=====",number) im = Image.open(image) im.thumbnail((512, 512), Image.ANTIALIAS) im.save("thumbnails/" + os.path.basename(image), "JPEG") photo.name = os.path.basename(image) photo.size = os.path.getsize(image) photo.path = "thumbnails" photo.date = datetime.now() photo.save() number = number + 1 -
How do I write custom create/update methods to serialize Foreign Key fields?
I am trying to rewrite my project using django rest framework. I am stuck at writing the serializer for one of my models that includes foreign keys. A simplified model would look like below: class Status(models.Model): name = models.CharField(max_length=264) icon = models.CharField(max_length=1000) def __str__(self): return self.name class Meta: verbose_name_plural = "status" class Country(models.Model): name = models.CharField(max_length=264) code = models.CharField(max_length=264) flag_icon = models.CharField(max_length=1000) def __str__(self): return self.name class Meta: verbose_name_plural = "countries" ordering = ["name"] class SomeModel(models.Model): date = models.DateField() time = models.TimeField() country = models.ForeignKey(Country, on_delete=models.CASCADE) status = models.ForeignKey(Status, on_delete=models.CASCADE) def __str__(self): return str(self.date) + str(self.time) + self.country A model serializer would look like this: class SomeSerializer(serializers.ModelSerializer): date = serializers.DateField(format="%d/%m/%Y", input_formats=["%d/%m/%Y"]) time = serializers.TimeField(format="%H:%M") class Meta: model = SomeModel fields = ["id", "date", "time", "country", "status"] Using this serializer will return the foreign key fields ids, ex. country =1 and not USA for example. To solve this we can rewrite the above serializer as follows: class SomeSerializer(serializers.ModelSerializer): date = serializers.DateField(format="%d/%m/%Y", input_formats=["%d/%m/%Y"]) time = serializers.TimeField(format="%H:%M") country = serializers.PrimaryKeyRelatedField(queryset=Country.objects.all(), source="country.name") status = serializers.PrimaryKeyRelatedField(queryset=Status.objects.all(), source="status.name") class Meta: model = SomeModel fields = ["id", "date", "time", "country", "status"] Using this serializer, we get what we have defined in the source parameter of each field. … -
Login with Django REST JWT
I have Django project with two apps. First app is simple Login/Register app based on default Django auth mechanism. It has two forms and after successful login or register will be redirected to my second app. So, my second app is it the Single Page Application based on Vue.js. Also I used djangorestframework and djangorestframework-jwt packages. I understood how JWT works but I can't understand how to implement it to my project. For example this is part of code that executing after POST-request from login form in my views: ... username = request.POST['username'] password = request.POST['password'] user = authenticate(request, email=username, password=password) if user is not None: login(request, user) return redirect('spa') ... So, I got next questions: What should I do after successful login (before redirect) in order to make token and will send with response djangorestframework-jwt provides next view to include in urls from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token, verify_jwt_token So, where I should call obtain_jwt_token? In SPA after successful login? In order to use JWT should I to create serializer for User model? -
builtins.TypeError TypeError: 'Meta.fields' contains fields that are not defined on this FilterSet: user_detail
Why am I getting this error? I do not understand. The code is not written by me but by another programmer. I am new to django so please be kind. Here are two files in there entirety. Let me know if I need to post more content. Why am I getting this error? I do not understand. The code is not written by me but by another programmer. I am new to django so please be kind. Here are two files in there entirety. Let me know if I need to post more content. Why am I getting this error? I do not understand. The code is not written by me but by another programmer. I am new to django so please be kind. Here are two files in there entirety. Let me know if I need to post more content. serializers.py ``` from kittytracker.tracker.models import Medication, Litter, Cat, CareLog, FosterAlert, VetVisit from rest_framework import serializers class MedicationSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Medication fields = ( 'name', 'slug', 'manufacturer', 'duration', 'frequency', 'dosage_unit', 'dosage_guidelines', 'notes', 'created', 'modified', 'package_photo_1', 'package_photo_2', 'package_photo_3', ) class LitterSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Litter fields = ( 'name', 'slug', 'foster_manager', 'notes', 'created', 'modified', ) class CatSerializer(serializers.HyperlinkedModelSerializer): class … -
Get User objects from foreign key
I am using the Django Rest Framework. I have two models as shown below: class Following(models.Model): target = models.ForeignKey('User', related_name='followers', on_delete=models.CASCADE, null=True) follower = models.ForeignKey('User', related_name='targets', on_delete=models.CASCADE, null=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return '{} is followed by {}'.format(self.target, self.follower) class User(AbstractBaseUser): username = models.CharField(max_length=15, unique=True) email = models.EmailField(max_length=100, unique=True) What I'd like to have an API that will return all the followers the user has. However, I don't want it to be returned in the Following model format, I'd like for the followers to be returned as users in this format: [ { "username": Bob, "email": example@example.com }, { "username": Charlie, "email": example@example.com } ] Right now, I have something like this: class FollowingAPIView(ListAPIView): serializer_class = FollowingSerializer def get_queryset(self): return Following.objects.filter(target=3) class FollowingSerializer(serializers.ModelSerializer): class Meta: model = Following fields = ('follower', 'target') This only shows the follower and target I don't want this. I want the actual data from User Also, I put target=3 as a placeholder just to test. -
Passing per_page values dynamically for each page in Paginator class
how can I pass per_page_count=[8,10,9,10,10] to Paginator class . I have a sorted_query_list which is passed to Paginator class but for per_page value each query can have different per_page_count. So a list is generated for each query (i.e per_page_count) containing number of rows to be shown in each page in sequential manner So result should have 8 rows for 1st page , 10 rows for 2 , 9 rows for 3 page , 10 rows for 4 page and so on . per_page_count=[8,10,9,10,10] for rows_per_page in per_page_count : result = Paginator(sorted_query_list, rows_per_page ) ^ Obviously this doesn't works ! Note: per_page_count can have different value for different sorted_query_list -
django template language for loops
so i have an html code that is using template variables. For some reason it looks like after i iterate through a template variable, the list is empty? Is it that the pointer need to be reset to the index 0 of the template variable? thanks! The second select has nothing to iterate over and has no option values. Years is an array that is like such [2015,2016,2017,2018] <select data-placeholder="Choose Year 1..." id="yr1"> {% for year in years %} <option value="{{year}}">{{year}}</option> {% endfor %} </select> <h4 style="margin-bottom: 0px; margin-right: 20px; margin-left: 20px">to</h4> <select data-placeholder="Choose Year 2..." id="yr2"> {% for year in years %} <option value="{{year}}">{{year}}</option> {% endfor %} </select> -
Access VM Django Dev Server from Hyper-V VM Host Physical Machine
I am currently using Hyper-V to create a ubuntu 18.04.1 Desktop VM. On this VM I am creating a Django Dev Server using the following: python manage.py runserver 0.0.0.0:8000 When I go to the 0.0.0.0:8000 on the vm I am presented with the Django debug page. However, when I to the url on my desktop I Unable to connect screen. When I run the server with an IP of anything other than 0.0.0.0 or 127.0.0.1, I just Error: That IP address cab't be assigned to. My Hyper-V Virtual Switch is an external network with my physical machines network adapter. I am using Python 3.6.5, and Django 2.1 How do I access the Django Development Server on my VM hosts machine browser. -
Using Subquery to annotate a Count
Please help me I've been stuck on this for way too long :( What I want to do: I have these two models: class Specialization(models.Model): name = models.CharField("name", max_length=64) class Doctor(models.Model): name = models.CharField("name", max_length=128) # ... specialization = models.ForeignKey(Specialization) I would like to annotate all specializations in a queryset with the number of doctors that have this specialization. My Solution so Far: I went through a loop and I made a simple: Doctor.objects.filter(specialization=spec).count() however this proved to be too slow and inefficient. The more I've read the more I realized that it would make sense to use a SubQuery here to filter the doctors for the OuterRef specialization. This is what I came up with: doctors = Doctor.objects.all().filter(specialization=OuterRef("id")) \ .values("specialization_id") \ .order_by() add_doctors_count = doctors.annotate(cnt=Count("specialization_id")).values("cnt")[:1] spec_qs_with_counts = Specialization.objects.all().annotate( num_applicable_doctors=Subquery(add_doctors_count, output_field=IntegerField()) ) The output I get is just 1 for every speciality. The code just annotates every doctor object with its specialization_id and then annotates the count within that group, meaning it will be 1. This doesn't make complete sense to me unfortunately. In my initial attempt I used an aggregate for the count, and while it works on its own it doesn't work as a SubQuery, I get this … -
Django Admin tabular inline foreign keys
I am trying to connect multiple tables in admin panel. My models are: class Team(models.Model): name = models.CharField(max_length=50)... class Player(models.Model): name = models.CharField(max_length=50) team = models.ForeignKey(Team, on_delete=models.CASCADE)... class Game(models.Model): home = models.ForeignKey(Team, related_name='home_team') away = models.ForeignKey(Team, related_name='away_team')... class GameStat(models.Model): player = models.ForeignKey(Player, on_delete=models.CASCADE) game = models.ForeignKey(Game, on_delete=models.CASCADE) minutes = models.PositiveSmallIntegerField() points = models.PositiveSmallIntegerField() rebounds = models.PositiveSmallIntegerField().... In admin panel I can connect everything nicely, except Game admin page. I can connect Game and GameStat table with class GameStatInline(admin.TabularInline): model = models.GameStat but the problem is that after I create game, I can add all the players from every team and I would like to only be able to add players from Home Team and Away Team. Is there a way to make Admin recognize Home and Away teams and list only the players who are from that 2 teams in select field? Ideally the best solution would be to have 2 Game Stats forms bellow Game form, one for home and one for away. Thanks -
query is getting UTC timestamp from the database but local time is stored in the database
For some reason my queryset is returning a UTC time, however in the database the time it is supposed to be getting is local time. Does anyone know why this is happening? Thanks for your help The last_checkin_time method is what gets the user's last checkin timestamp from the database, and right now I just have it posting in my toggle method in the time_delta variable so I can see what value its getting. (once i get this timezone thing figured out the time_delta will be an actual time delta) Heres my model manager class UserActivityManager(models.Manager): def current(self, user): current_obj = self.get_queryset().filter(user=user).order_by('-timestamp').first() return current_obj def last_checkin_time(self, user): last_activity_time = self.get_queryset().order_by('-timestamp').filter(user=user, activity="checkin").first() return last_activity_time def toggle(self, user): last_item = self.current(user) activity = "checkin" time_delta = None last_checkin = self.last_checkin_time(user) if last_item is not None: if last_item.timestamp <= tz.localize(datetime.datetime.now()): pass if last_item.activity == "checkin": activity = "checkout" time_delta = last_checkin.timestamp obj = self.model( user=user, activity=activity, time_delta = time_delta, ) obj.save() return obj And heres what the table in my database looks like (focusing on the time_delta field in the last few rows) -
How to clean a model after the related models inline forms have been saved?
I want to execute a check after the related data from the admin has been saved, but the default clean methods get executed before the formsets are saved. Where could i place my check to have access to a full version of what has been changed on the admin page?