Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get filter param as part of the queryset for Django
Context I want the parameters I am filtering on to be present in the queryset e.g. my_list = ["abx", "xyz" ...] Foo.objects.filter(some__name__icontains=my_list) I want "abx" to be part of the queryset object foo.some_param == "abx" or foo1.some_param == "xyz" Essentially I want the matching param to be present in the output queryset Is there an easy way to do that? Any help is highly appreciated -
How to display json details in a webpage using Django?
I have created a Django project which scrape data from a website and stores data in a JSON file, I want to create a Search bar in a webpage which searches and display Whole contents of data from Json file in a table. For ex: My JSON file looks like this. [ {"course_speed": "325.9\u00b0 / 9.3 kn", "current_draught": "5.3 m", "navigation_status": "Under way", "position_received": "0 min ago ", "imo": "9423841 / 246346000", "call_sign": "PBPQ", "flag": "Netherlands", "length_beam": "100 / 16 m"} ]. What I need is if I enter IMO number in Search bar, this json details should be displayed on a table. Thanks. -
How to create a ChoiceField for user email from EmailAddress model of allauth in django restframework?
I am using django allauth and restframework in backend for API. My question is how can i create a ChoiceField in my serializer with the email addresses of the logged in user as values so that instead of a textfield the form will create a Select field for email field. so far I have created a AuthUserSerializer serializer for my user API. users/serializers.py from rest_framework import serializers from users.models import * emails = [(email.email, email.email) for email in EmailAddress.objects.all()] class AuthUserSerializer(serializers.ModelSerializer): email = serializers.ChoiceField(choices=emails) class Meta: model = User fields = ('id', 'username', 'first_name', 'last_name', 'email', 'avatar', 'bio', 'country', 'is_staff', 'is_active', 'is_superuser', 'last_login', 'date_joined') extra_kwargs = { 'is_staff': { 'read_only': True }, 'is_superuser': { 'read_only': True }, 'last_login': { 'read_only': True }, 'date_joined': { 'read_only': True } } I have initialized the email field as a ChoiceField in the above code and the choices are the emails got from the EmailAddress model. But I want to get the emails created by the requested user. I don't know how to do it. I tried creating a CustomChoiceField like below, but still it does not work. class CustomChoiceField(serializers.ChoiceField): def __init__(self, **kwargs): user = self.context.get('request').user emails = [(email.email, email.email) for email in EmailAddress.objects.filter(user=user)] … -
Problem with downloading and saving excel file with django
I have a 3 problems, cannot figure it out, maybe there are connected. Problem 1.1: file is exported in django documentation and it works, but when I try to rename it, it has some error. I want to be like this with pd.ExcelWriter(newdoc + 'output.xlsx') as writer: in order to every file has a "new" name. Problem 1.2: How to add path where to save? Problem 2: I get to download file but it is empty, and name of document is Donwload.xlsx. I want to be like this, but this got many errors... filename = newdoc + '_calculated.xlsx' response = HttpResponse(output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename=%s' % filename return response This is views.py def my_view(request): if request.method == "POST": form = DocumentForm(request.POST, request.FILES) if form.is_valid(): output = io.BytesIO() newdoc = request.FILES['docfile'] dfs = pd.read_excel(newdoc, sheet_name=None, index_col=[0]) with pd.ExcelWriter('output.xlsx') as writer: #problem 1 for name, df in dfs.items(): #pandas code for uploaded excel file out.to_excel(writer, sheet_name=name) output.seek(0) response = HttpResponse(output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename=%s.xlsx' % 'Download' #problem 2 return response else: form = DocumentForm() return render(request, 'list.html', {'form': form}) -
Getting a bad request when pointing domain to vps
Hey everyone after deploying my Django App I tried to point my domain name to my VPS via A records and for some reason it just takes me to a bad request (400). I checked and the dns is resolving for the A records so I'm stuck on what the problem could be. http://31.220.62.130/ this is the IP address of the website and it works when I put this into the URL. Hustlestriking.com is the domain name that gives me the bad request. Im using hostinger for the VPS and the domain name. -
Gantt Charts In Django
I have been trying to make gant charts in Django but not being able to so. In python I have tried this: import plotly.figure_factory as ff df = [dict(Task="Job-1", Start='2017-01-01', Finish='2017-02-02', Resource='Complete'), dict(Task="Job-1", Start='2017-02-15', Finish='2017-03-15', Resource='Incomplete'), dict(Task="Job-2", Start='2017-01-17', Finish='2017-02-17', Resource='Not Started'), dict(Task="Job-2", Start='2017-01-17', Finish='2017-02-17', Resource='Complete'), dict(Task="Job-3", Start='2017-03-10', Finish='2017-03-20', Resource='Not Started'), dict(Task="Job-3", Start='2017-04-01', Finish='2017-04-20', Resource='Not Started'), dict(Task="Job-3", Start='2017-05-18', Finish='2017-06-18', Resource='Not Started'), dict(Task="Job-4", Start='2017-01-14', Finish='2017-03-14', Resource='Complete')] colors = {'Not Started': 'rgb(220, 0, 0)', 'Incomplete': (1, 0.9, 0.16), 'Complete': 'rgb(0, 255, 100)'} fig = ff.create_gantt(df, colors=colors, index_col='Resource', show_colorbar=True, group_tasks=True) fig.show() but I want the same to run in Django. Thanks. -
How to create a custom API views in Django Rest Framework
I want to create a custom API view based on existing data. models.py class Practice(models.Model): practice_id = models.BigAutoField(primary_key=True) score = models.SmallIntegerField(null=True) correct = models.SmallIntegerField(null=True) wrong = models.SmallIntegerField(null=True) not_answered = models.SmallIntegerField(null=True) class Meta: managed = True db_table = 'practice' def __str__(self): return str(self.practice_id) serializers.py class PracticeSerializer(serializers.ModelSerializer): class Meta: model = Practice fields = ('practice_id', 'score', 'correct', 'wrong', 'not_answered', ) views.py @api_view(['GET']) def practice_detail(request, pk): try: practice = Practice.objects.get(pk=pk) except Practice.DoesNotExist: return JsonResponse({'message': 'The practice does not exist'}, status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': exercises_serializer = PracticeSerializer(practice) return JsonResponse(exercises_serializer.data) With the code above I get the results of the API view as below using practice id 485 : /api/practice/485 { practice_id: 485, score: 10, correct: 2, wrong: 3, not_answered: 0, } Now I want to create a custom API view with the result as below : { labels: ["Practice"], datasets: [ { label: "Correct", data: [2], }, { label: "Wrong", data: [3], }, { label: "Not_answered", data: [0], } ] } How to do that? Is possible to achieve that without create new models? -
'InMemoryUploadedFile' object has no attribute 'to_excel' - Django
I got a problem, I got this script in python pandas and it working perfectly, I needed to do like this in order to process pandas in whole document, but now when I'm trying to put in django I got this error... Any ideas? Error AttributeError at / 'InMemoryUploadedFile' object has no attribute 'to_excel' Request Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 3.2.6 Exception Type: AttributeError Exception Value: 'InMemoryUploadedFile' object has no attribute 'to_excel' Exception Location: /home/user/django-pandas/myapp/views.py, line 50, in my_view Python Executable: /usr/bin/python Python Version: 3.9.6 This is views.py def my_view(request): if request.method == "POST": form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = request.FILES['docfile' dfs = pd.read_excel(newdoc, sheet_name=None, index_col=[0]) with pd.ExcelWriter('output_.xlsx') as writer: for name, df in dfs.items(): #pandas code # after pandas code output = io.BytesIO() writer = pd.ExcelWriter(output, engine='xlsxwriter') newdoc.to_excel(writer, index=False) #error (this is line 50) writer.save() output.seek(0) response = HttpResponse(output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename=%s.xlsx' % 'Download' return response else: form = DocumentForm() return render(request, 'list.html', {'form': form}) Thanks in advance! -
Django - Going back to a directory at a upper level from the template with href in django
trying to keep the question simple! I am currently in the directory which has a template cart.html: 8000/shop/cart/6/M/user and I want to go to the directory: 8000/shop/shirts So I just wrote in the cart.html: <a href="{% url 'shop' 'shirts' %}"> Which gives me an error: Reverse for 'shop' not found. 'shop' is not a valid view function or pattern name. So, I believe that its because I am trying to go from a lower directory back into a higher directory in the hierarchy so is there a way I can edit the href in cart.html in order to go to the shirts directory? Thanks in advance, -
How to iterate in subitems of a object in a django template
views.py: from django.views import generic from .models import Servico class ServicoView(generic.DetailView): model = Servico context_object_name = 'servico' template_name = 'servico.html' models.py: from djongo import models class PublicoAlvo(models.Model): def __str__(self): return '' alvo1 = models.CharField(max_length = 126) alvo2 = models.CharField(max_length = 126, blank = True, default = '') class Meta: abstract = True class Servico(models.Model): t_id = models.CharField(primary_key = True, unique = True, max_length = 252) alvos = models.EmbeddedField( model_container = PublicoAlvo ) urls.py: from django.urls import path from . import views urlpatterns = [ path('servicos/<slug:pk>/', views.ServicoView.as_view(), name = 'servico') ] I think these are the relevant files in my Django app folder. Back to the question, how can I iterate over the values that are going to be stored in servico.alvos in my template? If I want to show t_id, I just use {{ servico.t_id }} and it works fine. I could write something like: {{ servico.alvos.alvo1 }} {{ servico.alvos.alvo2 }} And that would show the values that I want, but that would make things uglier and more limited (imagine if I decide to change the model and add more 6 values in the PublicoAlvo class). I tried the following: {% for alvo in servico.alvos.all %} {{ alvo }} {% … -
no module named blog.eg found django
I'm facing this challenge! File "C:\Program Files\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\Users\user\demoDjango\blog\eg\urls.py", line 1, in <module> from blog.eg.views import home ModuleNotFoundError: No module named 'blog.eg' below is my djangoDemo/blog/eg/urls file: ''' from django.urls import path from . import views urlpatterns =[ path('', views.home, name="home"), ] ''' And here is my eg/views file: ''' from django.shortcuts import render from django.http import HttpResponse def home(request): return HttpResponse("Hello, Django! ") ''' And finally demodjango/blog/urls mapping file: ''' from django.contrib import admin from django.urls import path, include urlpatterns = [ path("", include("eg.urls")) , path('admin/', admin.site.urls), ] ''' ` -
AttributeError: 'NoneType' object has no attribute '_get_qnames_to_try'
I am trying to create a webapp which diplays IP Address of a hostname which should be input from user in textField. But I keep getting this error.I cant see to get reponse in url. I am new to this please help. view.py from django.shortcuts import render import dnspython as dns import dns.resolver def index(request): search = request.POST.get('search') # print(search) ip_address = dns.resolver.Resolver.resolve(search, "A") # ip_address = dns.resolver.Resolver() # answers = ip_address.resolve(search, "A").rrset[0].to_text() # try: # ip_address = dns.resolver.resolve(search, 'A').rrset[0].to_text() # except dns.resolver.NoAnswer: # ip_address = 'No answer' context = {"ip_address": ip_address} return render(request, 'index.html', context) This is the html Please have a look and check. Thanks in advance. index.html {% extends 'base.html' %} {% block title %} IP Finder {% endblock %} {% block body %} <div class="container"> <br> <br> <center> <h1 style="font-family:'Courier New'">Django NSLookup</h1> <br> <br> <form action="{% url 'index' %}" method="post"> {% csrf_token %} <div class="form-group"> <label> <input type="text" class="form-control" name="search" placeholder="Enter website"> </label> </div> <input type="submit" class="btn btn-primary" value="Search"> <p></p> <p>Click on the "Choose File" button to upload a file:</p> <form action="/action_page.php"> <input type="file" id="myFile" name="filename"> <input type="submit"> </form> </form> </center> <br> <br> <p>IP Address is : {{ip_address}}</p> </div> {% endblock %} Traceback: Traceback (most recent … -
Invalid file path or buffer object type: <class 'bool'>
I got an error and I don't know what is a problem. I upload file and when I run it I got this error. I thing that my file is not forwarded but don't know why, any ideas? I got this error in browser... ValueError at / Invalid file path or buffer object type: <class 'bool'> Request Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 3.2.6 Exception Type: ValueError Exception Value: Invalid file path or buffer object type: <class 'bool'> Exception Location: /home/user/.local/lib/python3.9/site-packages/pandas/io/common.py, line 395, in _get_filepath_or_buffer Python Executable: /usr/bin/python Python Version: 3.9.6 This is views.py def my_view(request): if request.method == "POST": form = DocumentForm(request.POST, request.FILES) if form.is_valid(): if 'file' in request.POST: newdoc = request.POST['file'] else: newdoc = False dfs = pd.read_excel(newdoc, sheet_name=None, index_col=[0]) #error with pd.ExcelWriter('output_' + newdoc + '.xlsx') as writer: #output #pandas code output.to_excel(writer, sheet_name=name) # after pandas code output = io.BytesIO() writer = pd.ExcelWriter(output, engine='xlsxwriter') newdoc.to_excel(writer, index=False) writer.save() output.seek(0) response = HttpResponse(output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename=%s.xlsx' % 'Download' return response else: form = DocumentForm() return render(request, 'list.html', {'form': form}) Thanks in advance! -
Readonly Django ModelAdmin form field with id attribute
When you make a form field in a ModelAdmin form read only, Django doesn't give it an id attribute. I have a select field which is editable in the ADD form but read only in the UPDATE form. Is there a way to have Django add the id attribute so that I can target it with JavaScript? -
Attribute Error: Generic Detail View must be called with either an object pk or a slug in the URLconf in tests
I've spent a lot of time today reviewing other posts that reference this issue both here and throughout Google. I cannot, however, find a solution when this occurs in a test. I am using pytest in my project and get this error on one of my detail views only when testing the view. The view itself works on my actual site. Here's my code: views.py class CarrierDetailView(LoginRequiredMixin, DetailView): model = Carrier def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) quotes = self.object.quotes.all() context['quotes'] = quotes return context models.py class Carrier(models.Model): TYPE_CHOICES = [ ('WYO', 'WYO'), ('PRIVATE', 'Private') ] carrier_name = models.CharField(max_length=50) carrier_type = models.CharField(max_length=7, choices=TYPE_CHOICES) def __str__(self): return self.carrier_name urls.py path('carrier/<int:pk>/', views.CarrierDetailView.as_view(), name='carrier-detail'), and test_views.py class CarrierDetailViewTest(TestCase): def test_carrier_detail_view(self): self.factory = RequestFactory() self.carrier = models.Carrier.objects.create(carrier_name='NatGen', carrier_type='WYO', id=2) path = reverse('quote-checklist:carrier-detail', kwargs={'pk':2}) request = RequestFactory().get(path) request.user = User.objects.create_user(username='ryan', email='ryan@email.com', password='password') response = views.CarrierDetailView.as_view()(request, kwargs={'pk':2}) assert response.status_code == 200 def test_carrier_detail_template(self): assert('carrier_detail.html') Please note in the tests I've received this error both with the kwargs in the response/path and without. I've also successfully tested the url for this view using the following test code: def test_carrier_detail_view_url(self): path = reverse('quote-checklist:carrier-detail', kwargs={'pk':1}) assert resolve(path).view_name == 'quote-checklist:carrier-detail' I appreciate in advance any insight others may have to … -
how to Write model manager for model in django and return result In format of quryset
we have 3 models in models.py: class Benefactor(models.Model): user = models.OneToOneField(User , on_delete=models.CASCADE) choice = [ (0,'Beginner'), (1,'medium'), (2,'Expert'), ] experience = models.SmallIntegerField(default=0, choices=choice) free_time_per_week = models.PositiveSmallIntegerField(default=0) and class Charity(models.Model): user = models.OneToOneField(User , on_delete=models.CASCADE) name = models.CharField(max_length=50) reg_number = models.CharField(max_length=10) and class Task(models.Model): assigned_benefactor = models.ForeignKey(Benefactor , null=True , on_delete=models.CASCADE) charity = models.ForeignKey(Charity , on_delete=models.CASCADE) age_limit_from = models.IntegerField(blank=True , null=True) age_limit_to = models.IntegerField(blank=True ,null=True) date = models.DateField(blank=True ,null=True) description =models.TextField(blank=True , null=True) choices = [ ('M' , 'Male'), ('F' , 'Female'), ] gender_limit = models.CharField(max_length=1 , choices=choices) StateChoices = [ ('P' ,'Pending'), ('W' , 'Waiting'), ('A' ,'Assigned'), ('D' , 'Done'), ] state = models.CharField(max_length=1 , choices=StateChoices , default='P') title = models.CharField(max_length=60) objects =TaskManager() i need Write for Task model with model manager To do return quryset of users in benfactor or in charity or state in Task = 'P' but this code dosent work: class TaskManager(models.Manager): def all_related_tasks_to_user(self, user): return self.get_queryset.filter(Charity.user = user or Benefactor.user = user or Task.state = 'P') plase help me for Problem solving -
Can we manage the deployment of each django app within a single Django project independently?
Lets say we have one django project that has two apps - FooApp & BarApp. Each app talks to its own database. Meaning they both manage their own set of models. Is it possible to manage the deployments of these apps independently? It's okay for them to be deployed on same server within the same nginx process as long as I am able to make changes to the apps without bringing down the other as well. I understand that these can very well be separate projects and they can communicate with each other using RESTful APIs. For my needs, I want to avoid that REST interaction for the time being. The django documentation [here][1] describes a django project and django app as follows Django project: The term project describes a Django web application. Django App: The term application describes a Python package that provides some set of features. So if the app is simply a python package, and the django project is really the one that defines how these apps are managed via the settings module, then I suppose there is no straight forward way of accomplishing what I want. Or is there anything I can do? TIA [1]: https://docs.djangoproject.com/en/dev/ref/applications/ -
Limit django path slug to a list
I currently have a path like such path('<slug:slug>/', ToSlugPage.as_view()), Is there any way to limit the results slug can be for this path, and if so how? So for example, if I have a list of slugs slugs = ['page1', 'page2', 'page3'] Is there any way I can have slug check that, if not continue to other paths/return 404? -
AttributeError at / 'NoneType' object has no attribute '_get_qnames_to_try'
I have been working at a project where I need to print Ip address of a hostname inputed by user in a textfield on html page. I am using Django kinda new at it. I am getting this error no qnames found. Please Help! Heres Views.py from django.shortcuts import render import dns.resolver def index(request): search = request.POST.get('search') # print('search='+search) ip_address = dns.resolver.Resolver.resolve(search, "A") context = {"ip_address": ip_address} return render(request, 'index.html', context) index.html {% extends 'base.html' %} {% block title %} IP Finder {% endblock %} {% block body %} <div class="container"> <br> <br> <center> <h1 style="font-family:'Courier New'">Django NSLookup</h1> <br> <br> <form action="{% url 'index' %}" method="post"> {% csrf_token %} <div class="form-group"> <label> <input type="text" class="form-control" name="search" placeholder="Enter website"> </label> </div> <input type="submit" class="btn btn-primary" value="Search"> <p></p> <p>Click on the "Choose File" button to upload a file:</p> <form action="/action_page.php"> <input type="file" id="myFile" name="filename"> <input type="submit"> </form> </form> </center> <br> <br> <p>IP Address is : {{ip_address}}</p> </div> {% endblock %} Traceback of error: Traceback (most recent call last): File "C:\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\vassu\PycharmProjects\IPFinderA\IPApp\views.py", line 20, in index ip_address = dns.resolver.Resolver.resolve(search, "A") File "C:\Python39\lib\site-packages\dns\resolver.py", line 1159, … -
Create Django model object with foreign key
I tried so many different ways but can't seem to get it. I have 'TeamName' as a foreign key to 'MLBGame'. I have been trying to create new MLBGame objects but cant get it to work because of the foreign key. What is the correct way to do it? I have tried querying the foreign key like: team = TeamName.objects.get(name=whatevername) and I tried with (name__name=whatevername) and then inserting the team var in the new object to create but no go. I really appreciate any help you can offer, I have been working on this for awhile and the Django docs just have me going around in circles. Models class TeamName(models.Model): name = models.CharField(max_length=100, null=False, blank=False) abbreviation = models.CharField(max_length=100, null=False, blank=False) twitter_id = models.CharField(max_length=100, default=name) def __str__(self): return self.name class MLBGame(models.Model): gameID = models.IntegerField(null=True, blank=True) name = models.ForeignKey('TeamName', null=False, blank=False, on_delete=models.CASCADE) other stuff team = TeamName.objects.get(name=game.away_team) MLBGame.objects.update_or_create( gameID=gameID, defaults={ 'name': team.name, Other Stuff} ) -
OperationalError: no such table but database and migrations folder were deleted
Very similar to this question: I have a script that: dumps all data to json, deletes the database.sqlite3 file and the migrations folder executes: python makemigrations app python manage.py migrate app python manage.py makemigrations python manage.py migrate loads all data from json I use it a lot when developing stuff and restarting very often. Now even the makemigrations app command fails with the OperationalError: no such table. Funny thing is, when I comment out all appearances of this table (but the model is still in models.py), everything works fine. If I then delete the comments everything works. What did I miss? Traceback: PS ..\projectname> python manage.py migrate appname Traceback (most recent call last): File "..\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "..\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: appname_unmigrateablemodel The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "..\venv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "..\venv\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "..\venv\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "..\venv\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File … -
How to get a Queryset from Django to use in a Template
I have the following 2 Django models. I have a Game model where multiple officials will be assigned to a game. I have the Referee_Assignment model where I keep track of game assignments and whether the official accepted the assignment. I want to query the two tables for all games and assignments and display in a table. I have tried several different ways, but don't seem able to get all fields. I am very new to Django. class Game(models.Model): home = models.ForeignKey(Team, on_delete=models.DO_NOTHING) visitor = models.ForeignKey(Team, related_name='visit_team', on_delete=models.DO_NOTHING) gdate = models.DateTimeField(default=timezone.now) gender = models.ForeignKey(Gender, on_delete=models.DO_NOTHING) level = models.ForeignKey(Game_Level, on_delete=models.DO_NOTHING) billing = models.IntegerField() location = models.ForeignKey(Location, on_delete=models.DO_NOTHING) num_refs = models.ForeignKey(Num_Referee, on_delete=models.DO_NOTHING) enter_date = models.DateTimeField(auto_now=True) update_date = models.DateTimeField(default=timezone.now) game_status = models.ForeignKey(Game_Status, on_delete=models.DO_NOTHING) season = models.IntegerField() class Referee_Assignments(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) game = models.ForeignKey(Game, on_delete=models.CASCADE,related_name='ref_assignments') position = models.ForeignKey(Referee_Position, on_delete=models.CASCADE) status = models.ForeignKey(Ref_Assign_Status, on_delete=models.CASCADE) update_time = models.DateTimeField(auto_now=True) create_time = models.DateTimeField(auto_now_add=True) class Meta: unique_together = ['game', 'position'] Here is the query: try: games = Game.objects.prefetch_related('ref_assignments') context = {'games': games} return render(request, 'assign/index.html', context) except: print('No Assignments') -
Python error when using count in conditional
I am new to python and I'm trying to count rows in a pandas dataframe and use the result in an if function, I keep receiving an error 'NoneType' object is not subscriptable, I have tried everything I can think of without success. Can someone explain why I am receiving this error and a possible solution. pre = pd[pd['epic']==record.pair.epic] c = len(pre) if(c == 0): print('test complete') Thanks -
django.core.exceptions.FieldDoesNotExist: Raw query must include the primary key
I am trying to do a raw query in django and it dosenot seems to be working . It is working when i execute the same query in table plus (IDE for databases) . This is my Django code: class AllCustomerOwnerTransactionView(APIView): permission_classes = [IsAuthenticated] authentication_classes = [JWTAuthentication] def get(self, request): query = f""" SELECT u_c.name, sum(CASE WHEN h_te.to_pay_to_customer > h_te.pay_from_customer THEN h_te.to_pay_to_customer - h_te.pay_from_customer WHEN h_te.pay_from_customer > h_te.to_pay_to_customer THEN h_te.pay_from_customer - h_te.to_pay_to_customer ELSE 0 end) as Total, u_c.owner_id FROM home_transactionentries h_te INNER JOIN home_transaction h_t ON h_te.transaction_id = h_t.id INNER JOIN users_customer u_c ON u_c.id = h_t.customer_id WHERE u_c.owner_id = {request.user.id} GROUP BY u_c.name, u_c.owner_id; """ query_set = TransactionEntries.objects.raw(query) This is the Traceback that i got: Traceback (most recent call last): File "/home/__neeraj__/.local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/__neeraj__/.local/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/__neeraj__/.local/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/__neeraj__/.local/lib/python3.9/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/home/__neeraj__/.local/lib/python3.9/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/home/__neeraj__/.local/lib/python3.9/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/home/__neeraj__/.local/lib/python3.9/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/home/__neeraj__/.local/lib/python3.9/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/home/__neeraj__/Documents/programming/merokarobarClone/AccountsBackend/home/views.py", line 73, in … -
Can't load Visual Studio project due to missing Microsoft.PythonTools.Django.Targets file
I've cloned my project from a GitHub repository and have been receiving the following error upon opening the project in Visual Studio: C:\path\to\project\test.pyproj : error : The imported project "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Microsoft\VisualStudio\v16.0\Python Tools\Microsoft.PythonTools.Django.targets" was not found. Also, tried to find "Microsoft\VisualStudio\v16.0\Python Tools\Microsoft.PythonTools.Django.targets" in the fallback search path(s) for $(MSBuildExtensionsPath32) - "C:\Program Files (x86)\MSBuild" . These search paths are defined in "C:\Users\me\AppData\Local\Microsoft\VisualStudio\16.0_e9ead341\devenv.exe.config". Confirm that the path in the <Import> declaration is correct, and that the file exists on disk in one of the search paths. C:\path\to\project\test.pyproj I've tried changing the declaration and have tried verifying that I have all of the proper Visual Studio workloads installed, but the problem persists. The project is a web application running Python using Django on the back end and JavaScript on the front end.