Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Plotly - Adjustbale bar plot
I'm creating a graph in Plotly as part of a Django project and the problem I have is that when I have only one value the size of the bar is incredibly big, obviously, as soon as I have more than one item, the bar starts to look nice, but when is only one value is really ugly, does anyone know how to fix this? def get_leads_data(request): c = Profile.objects.get(user=request.user) qs = Leads.objects.filter( agent_id=c,status='Open') df = read_frame(qs) graphs = [] graphs.append(go.Bar( x=df['company'], y=df['expected_revenue'], name='Estimated Revenue' )) layout={ 'title': 'Estimated Revenue by Company', 'xaxis_title':'Company', 'yaxis_title':'Revenue', 'height':500, 'width':640, } plot_div = plot({'data': graphs, 'layout': layout}, output_type='div') return render(request,'account/plot.html',{'plot_div':plot_div}) -
Filter a user data using contains in Django
I have this model that records data in slug. The user has a relation with the award model. What am trying to do is list all login user's awards slug field data in the contain filter so i can use it to filter user's data. NOTE : All the data in save in the SuccessfulTransactionHistory model field award is in slug format and SuccessfulTransactionHistory model has no foreign key relation to award and user models.py class Award(models.Model): admin = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=100) image = models.ImageField(upload_to='award_images') slug = models.SlugField(max_length=150, blank=True, null=True) about_the_award = models.TextField(blank=True, null=True) status = models.CharField(max_length=20, choices=STATUS_PUBLISHED, default='Closed') price = models.DecimalField(max_digits=3, default='0.5', decimal_places=1, blank=True, null=True, validators = [MinValueValidator(0.1)]) bulk_voting = models.CharField(max_length=20, choices=BULK_VOTING, default='Closed') amount = models.DecimalField(default=0.0, max_digits=19, decimal_places=2, blank=True,) results_status = models.CharField(max_length=20, choices=RESULTS_PUBLISHED, default='private') starting_date = models.DateTimeField() ending_date = models.DateTimeField() date = models.DateTimeField(auto_now_add=True) class SuccessfulTransactionHistory(models.Model): nominee_name = models.CharField(max_length=120) transaction_id = models.CharField(max_length=120) award = models.CharField(max_length=120) amount = models.DecimalField(default=0.0, max_digits=19, decimal_places=2) status = models.CharField(max_length=120, null=True, blank=True) phone = models.CharField(max_length=120, null=True, blank=True) date = models.DateTimeField(auto_now_add=True) In my view.py success_list = SuccessfulTransactionHistory.objects.filter(award__contains=request.user.award.slug).order_by('-date') This is my error 'User' object has no attribute 'award' `` -
I need to do a delete and update based on status
I need to do a delete and update based on status. Here are models: class Purchases(TimeStampedModel): APROVADO = "AP" EM_VALIDACAO = "VA" STATUS_CHOICHES = ( (APROVADO, "Aprovado"), (EM_VALIDACAO, "Em validação"), ) values = models.DecimalField(decimal_places=2, max_digits=10, default=0) cpf = BRCPFField("CPF") status = models.CharField(max_length=20, choices=STATUS_CHOICHES, default=EM_VALIDACAO) I'm trying to do like this in my viewset: def get_queryset(self): qs = super().get_queryset() if self.action in ("update", "parcial_update", "delete"): qs.filter(Purchases.status=="VA") return qs However he is still letting edit the orders with the approved status. Can only be deleted or edited purchase with status "In validation" Can someone help me? -
Filter sub-groups in django querysets
Consider the following table: Column_A Column_B Column_C First UserA NULL Second UserB NULL Third UserC 1 Fourth UserA 1 Fifth UserB NULL Sixth UserB 2 Seventh UserC 2 I'd like to return all rows (Column_A, Column_B, Column_C) such that either: Column_C is NULL, or for every unique value in Column_C, return the first row with Column_B == UserA. If no such row exists, return the first row sorted by Column_B.time_created. For e.g. table.objects.magic_queryset(matching_user(UserA)) returns Column_A Column_B (FK) Column_C First UserA NULL Second UserB NULL Fourth UserA 1 Fifth UserB NULL Sixth UserB 2 I'm unable to write a queryset that will do the filtering efficiently in a single query. Appreciate any pointers. -
Django-limit_choices_to With ForeignKey based on different links
I am making a building manager website in Django. I have a page that is a DetailView for each building. On the DetailView page is a link to add a work task for repairs. On creating a work task I would like it to filter only for the building page that I came from. For example, from "building/1" page clicking the work task link would only allow you to see and select rooms in the building with pk = 1. views.py from django.shortcuts import render from .models import Building, Room, Task, Task_Note from django.views.generic.list import ListView from django.views.generic.detail import DetailView from django.views.generic.edit import CreateView # Create your views here. class BuildingList(ListView): model = Building template_name = "dorm/buildings.html" class BuildingDetail(DetailView): model = Building template_name = "dorm/building.html" class TaskAdd(CreateView): model = Task fields = ["time", "room", "work_request_id", "description"] template_name = "dorm/add_task.html" models.py from django.db import models from django.db.models.fields import DateTimeField, IntegerField, CharField, TextField from django.db.models.fields.related import ForeignKey import datetime from django.urls.base import reverse error = "Error" # Create your models here. class Building(models.Model): number = IntegerField(null = True, blank = True) @property def number_of_rooms(self): try: return Room.objects.filter(building = self).count() except: return error @property def number_of_active_tasks(self): x = 0 q = Task.objects.all() for … -
Prevent Delete on Default Image Django
I'm trying to set default image on nullable and blankable image field. I set the default image inside media/category like this: I've successfully set default image and working good by setting default on models.py like these: class Category(models.Model): ... image = models.ImageField(upload_to=upload_location, default='category/category.png', null=True, blank=True) ... def delete(self): if self.image != 'category/category.png': self.image.delete() super().delete() When adding data with blank image, the default image fill the default image field on the table: and it's shown as well like this: The problem comes when I delete the data it self, the image also being deleted. I have tried these code to prevent default image deletion, the data still remain, the default image still being deleted and the image field being blanked, like these: And I realize that these code (on models.py) only prevent data deletion, not the file/image deletion: ... def delete(self): if self.image != 'category/category.png': self.image.delete() super().delete() ... I want the default image still remain event the data being deleted, because it will be used when other someone add another data with blank image. How to prevent this default image deletion? Please help? -
Django Authentication to use both email and username
I've been nearly done with my django-react app with all the models, serializers, and APIs. But now I need to change the authentication method to also use email. class User(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField(unique=True) # Notice there is no username field, because it is included in AbstractUser I've looked through some possible solutions but they involve using AbstractBaseUser while some other write a custom authentication backend that omits the username completely. This might break other views and frontend since we have been mainly using username. I still want to keep the username and use both username and email to authenticate. Is there any simple idea (preferably kept using AbstractUser) that I wouldn't have to make major change? -
How can I require that every checked box in ModelMultipleChoiceField has an integer associated in django?
Im working with a ModelMultipleChoiceField field in a form, and I would like to require that for every box that is checked, an integer is specified somewhere on the form. I other words, that the length of the checked boxes and itegers declared is the same. Is there any way to do this in Django? -
How to access python variables from ajax
In a Django web application, there is a for loop to feed a dropdown menu like below in index.html: <div class="form-control-lg"> <select class="form-control " id="booklist"> <option value="">Please select a book</option> {% for book in booklist %} <option value="{{ book }}"> book['name']</option> {% endfor %} </select> </div> This code simply adds all the books in booklist to a dropdown menu. I need to load the books from booklist but by ajax this time. I tried the below code but it does nothing, and the dropdown is empty. $(document).ready(function() { for(var book in booklist) { $('#booklist').append('<option value=book>'+ book['name'] +'</option>'); } } What is the way to get the result? -
Custom Export URL for export headers function
I have this in my resources: def export(self, queryset=None, *args, **kwargs): data = super().export(queryset, args, kwargs) return tablib.Dataset(headers=data.headers) It exports only the header fields for files. I want to bind it to a button only: but considering the custom export is inside my model resource, it is also applied to the export button. How do I add it only to the template button? Something like a new URL? -
Create model instance consisting of many-to-many field
I am trying to create a model instance using a post request, however one issue that I am having is that the model consists of a field which is of many-to-many. Now I am at a stage where I have got an array consisting of primary keys of the model instances (Modules) I wish to associate with the model I am trying to create (a Student). Please see my code below as I do not know where I am going wrong, after some basic research it seems I need to use a .set() method. The PUT['modules'] corresponds to array that consists of values [1,2,3,5]. def create_student(request): """API for creating a student""" if request.method == "POST": PUT = json.loads(request.body) student = Student(name=PUT['name'], join_date=PUT['join_date'], academic_year=PUT['academic_year'], modules=PUT['modules'] # THIS IS WHERE I NEED HELP ) student.save() return JsonResponse(student.to_dict()) return HttpResponseBadRequest("Invalid method") Thank you for your time. -
Create a list using values_list() in django
I'm trying to get the values of the objects saved in my database in a list and as integer, but the code I'm using is not working: if I try number[1:] I'm just gettin a blank variable in the html page and I keep getting errors telling me I'm still working with queryset and not list. number = list(Week.objects.filter(user=request.user).values_list()) How Can I get a simple list using .values_list()? -
Powershell file .ps1
I am stuck on a problem. I have a python application with a Django server and fronted in React. I run the Django and React server via a .ps1 file On the other hand, when I relaunch my application I open a new CMD window for Django and React I can't find a solution to kill the windows that are already open. code python3 to run file .ps1 {p = subprocess.run('powershell.exe -ExecutionPolicy RemoteSigned -file"entrypoint.ps1"', stdout=subprocess.PIPE, shell=True, timeout=30) } code powershell (.ps1) {Start-Process -FilePath 'venv/Scripts/python.exe' -ArgumentList "./manage.py runserver" Start-Process -FilePath 'venv/Scripts/python.exe' -ArgumentList "main.py" Start-Process 'npm' -ArgumentList "start" -WorkingDirectory "../prg_Frontend"} -
problems making the formset dynamic
I need urgent help. my formset is not visible when I click the '+' button I suspect that my view is badly done, even though the fields are visible, when increasing the extra from views, the change is not seen in the button. The problem is not in javascript since I already did tests. They can help me to check my code. I'm new at this additionally I also want to mention that whenever I put my code in html here in stackoverflow I see some strange spaces on the left side. It doesn't happen to me like this when I put javascript or python presupuestos-forms.html <section> <div> <form method="POST"> {% csrf_token %} <div class="row"> <div class="col-12"> <div class="card"> <div class="card-body"> <h4 class="card-title">Partes</h4> <p class="card-title-desc">Agrega las partes que se incluirán</p> <div class="table-responsive"> <table class="table table-bordered table-nowrap align-middle"> <thead class="table-info"> <tr> <th scope="col">Código</th> <th scope="col">Descripción</th> <th scope="col">Cantidad</th> <th scope="col">Precio Unitario</th> <th scope="col">Precio Total</th> <th scope="col">Libre de Impuestos</th> <th scope="col">Agrega Fila</th> </tr> </thead> <tbody> <tr> <td> {{presupuestosparteform.codigo}} </td> <td> {{presupuestosparteform.descripcion}} </td> <td> {{presupuestosparteform.quantity}} </td> <td> {{presupuestosparteform.unit_price}} </td> <td> {{presupuestosparteform.total_price}} </td> <td> <div> {{presupuestosparteform.tax_free}} </div> </td> <td> <input type="button" class="btn btn-block btn-default" id="add_more" value="+" /> </td> </tr> <tr id="formset"> {{ formset.management_form }} {% … -
Django Elastic Beanstalk 502 Error Gunicorn No module named application
I have a django app and im trying to deploy it into aws elastic beanstalk but im getting 502 error from nginx, I have gunicorn installed and listed on my requirements.txt file. Checking the logs i see the following: Nov 17 20:35:22 ip-172-31-12-36 web: [2021-11-17 20:35:22 +0000] [3510] [INFO] Starting gunicorn 20.1.0 Nov 17 20:35:22 ip-172-31-12-36 web: [2021-11-17 20:35:22 +0000] [3510] [INFO] Listening at: http://127.0.0.1:8000 (3510) Nov 17 20:35:22 ip-172-31-12-36 web: [2021-11-17 20:35:22 +0000] [3510] [INFO] Using worker: gthread Nov 17 20:35:22 ip-172-31-12-36 web: [2021-11-17 20:35:22 +0000] [3516] [INFO] Booting worker with pid: 3516 Nov 17 20:35:22 ip-172-31-12-36 web: [2021-11-17 20:35:22 +0000] [3516] [ERROR] Exception in worker process Nov 17 20:35:22 ip-172-31-12-36 web: Traceback (most recent call last): Nov 17 20:35:22 ip-172-31-12-36 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker Nov 17 20:35:22 ip-172-31-12-36 web: worker.init_process() Nov 17 20:35:22 ip-172-31-12-36 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/workers/gthread.py", line 92, in init_process Nov 17 20:35:22 ip-172-31-12-36 web: super().init_process() Nov 17 20:35:22 ip-172-31-12-36 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/workers/base.py", line 134, in init_process Nov 17 20:35:22 ip-172-31-12-36 web: self.load_wsgi() Nov 17 20:35:22 ip-172-31-12-36 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi Nov 17 20:35:22 ip-172-31-12-36 web: self.wsgi = self.app.wsgi() Nov 17 20:35:22 ip-172-31-12-36 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi Nov … -
How to pass form into template and save it? Django
Hello I have a question how can I pass a form into HTML template and save it in class based view? As you see in views.py I have made Item.objects.create after Post request but is it a good practice if Django provides forms? Form: class itemCreationForm(ModelForm): name = forms.CharField() class Meta: model = Item fields = ['name'] views.py: class Home(ListView): model = Item template_name = 'home/todo.html' form_class = itemCreationForm def post(self, request): item = self.request.POST.get('item') Item.objects.create(name=item) return HttpResponse(f'Post! {item}') -
How to POST and PUT data using fetch api?
Below is the html file with the all the following in <script It receives the value of game_title by getting the element id of the input which is filled out in the form. It correctly receives the information that the user enters in the forms async editGame(game){ var game_title = document.getElementById("edit_game_title").value; var age_rating = document.getElementById("edit_age_rating").value; var genre = document.getElementById("edit_genre").value; var game_release_date = document.getElementById("edit_game_release_date").value; alert(game_title) // ajax request to edit that game let response = await fetch(game.api, { method: "PUT", body: JSON.stringify({ Title : game_title, AgeRating : age_rating, Genre : genre, ReleaseDate : game_release_date, }), headers:{ "Content-Type": "application/json", "X-CSRFToken": document.querySelector("[name=csrfmiddlewaretoken").value, } }); if (response.ok){ game.editing = false; } else{ alert("Failed to edit") } }, async addGame(games) { var game_title = document.getElementById("game_title").value; var age_rating = document.getElementById("age_rating").value; var genre = document.getElementById("genre").value; var game_release_date = document.getElementById("game_release_date").value; // ajax request to add a game if (confirm(`Are you sure you want to add ${game_title}?`)) { let response = await fetch(games.api, { method: "POST", body: JSON.stringify({ Title : game_title, AgeRating : age_rating, Genre : genre, ReleaseDate : game_release_date, }), headers: { "X-CSRFToken": document.querySelector("[name=csrfmiddlewaretoken").value, }, }) if (response.ok){ //this.games = this.games.filter(g => g.id != game.id) // game was added! this.games = this.games alert("added game") } else{ alert("Failed to … -
django in production refuse to show error details written with restframewortk status
I have used django rest framework.status to return some custom error details and it works fine in test mode. but when I lunched my code on server it just return error code 500 internal error. I'm using django, django-rest-framework, react-redux, gunicorn and nginx. Has anyone had the same problem and know how to fix it? I didn't know what part of my code to include but if you need any details just tell me. -
Django DateTimeField ValidationError: value has an invalid format (different question:))
The field is simple: timestamp=DateTimeField(primary_key=True) When I check the value of DATETIME_INPUT_FORMATS, it's standard: ['%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M:%S.%f', '%Y-%m-%d %H:%M', '%m/%d/%Y %H:%M:%S', '%m/%d/%Y %H:%M:%S.%f', '%m/%d/%Y %H:%M', '%m/%d/%y %H:%M:%S', '%m/%d/%y %H:%M:%S.%f', '%m/%d/%y %H:%M'] Regardless of me setting USE_L10N to True or False it outputs the timestamps in this format: "June 12, 2021, 2:40 a.m.". And most interesting, when I try to delete an entry, it gives me this exception: Traceback (most recent call last): File "/home/pooh/venv39/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/pooh/venv39/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/pooh/venv39/lib/python3.9/site-packages/django/contrib/admin/options.py", line 616, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/pooh/venv39/lib/python3.9/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/pooh/venv39/lib/python3.9/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/home/pooh/venv39/lib/python3.9/site-packages/django/contrib/admin/sites.py", line 232, in inner return view(request, *args, **kwargs) File "/home/pooh/venv39/lib/python3.9/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/home/pooh/venv39/lib/python3.9/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/pooh/venv39/lib/python3.9/site-packages/django/contrib/admin/options.py", line 1739, in changelist_view response = self.response_action(request, queryset=cl.get_queryset(request)) File "/home/pooh/venv39/lib/python3.9/site-packages/django/contrib/admin/options.py", line 1406, in response_action queryset = queryset.filter(pk__in=selected) File "/home/pooh/venv39/lib/python3.9/site-packages/django/db/models/query.py", line 941, in filter return self._filter_or_exclude(False, args, kwargs) File "/home/pooh/venv39/lib/python3.9/site-packages/django/db/models/query.py", line 961, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, args, kwargs) File "/home/pooh/venv39/lib/python3.9/site-packages/django/db/models/query.py", line 968, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) … -
Removing field from JSON response
I would like to remove a field from Json response in Django REST framework. I'm trying to do this, but it wont help, because it's basic serializer method field(created in serializer, without models and migrations), and its not inside validated data. if validated_data.get('my_field') and self.context['request'].public_api: validated_data.pop('my_field', None) Any ideas? -
Annotate a Django Queryset Using a 'related_name' Across a ManyToMany Relationship (NO 'Count', 'Avg', 'Max', ...)
I have models in my code similar to the following: class CompanyProject(models.Model): """ This class holds project related information read in from the 'project' custom 'manage.py' command. """ project_number = models.IntegerField(blank=False, null=False, unique=True) project_worktype = models.CharField(blank=True, max_length=255, null=True) created_at = models.DateTimeField(auto_now_add=True, blank=False, null=False) updated_at = models.DateTimeField(auto_now=True, blank=False, null=False) last_seen = models.DateField(blank=False, null=False) def get_project_subtypes(self): subtypes = self.project_subtype.all() return [ subtype.project_subtype for subtype in subtypes ] class Meta: ordering = ['project_number'] class CompanySubType(models.Model): class CompanySubTypeChoices(models.TextChoices): G1A = '1A', _('1A') G1B = '1B', _('1B') G2A = '2A', _('2A') G2B = '2B', _('2B') G3A = '3A', _('3A') G3B = '3B', _('3B') company_project = models.ManyToManyField(CompanyProject, related_name='project_subtype') project_subtype = models.CharField(blank=False, choices=CompanySubTypeChoices.choices, max_length=2, null=False) class ListEntry(models.Model): list_project = models.OneToOneField(CompanyProject, on_delete=models.CASCADE, related_name='list_project') list_reviewer = models.ForeignKey('auth.User', on_delete=models.CASCADE, related_name='+') I would like to return a set of annotated ListEntry objects annotated with a list of ALL of the project subtypes identified with the ListEntry project. Eventually, I need to be able to pass this annotated data to a Django REST Framework serializer but I need to get the annotation working like I want it to first. My problem is that I can annotate just fine doing something like this: list_entry_qs = ListEntry.objects.prefetch_related('list_project', 'list_reviewer').annotate(subtypes=F('list_pmatt__project_subtype__project_subtype')).all() and it works just fine. The … -
Big files and 502s with nginx, uwsgi, and ELB
I'm having difficulty trying to debug why I'm getting 502s on uploading large files. I keep getting errors that the keepalive dies eg When I check the nginx logs: 2021/11/17 19:17:04 [info] 33#33: *82 client 10.0.10.148 closed keepalive connection 2021/11/17 19:15:45 [info] 32#32: *104 client 10.0.20.96 closed keepalive connection When I check the uwsgi/app logs, I don't see much. I get occasional OS errors like Wed Nov 17 17:28:37 2021 - SIGPIPE: writing to a closed pipe/socket/fd (probably the client disconnected) on request but I don't think they're related. I also get worker signal 9 errors but I think some may be memory errors DAMN ! worker 3 (pid: 19) died, killed by signal 9 :( trying respawn ... If these are memory issues on the uswgi workers, how do I go about increasing the memory per process? nginx.conf: http { access_log /dev/stdout; include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] ' '"$request" $status $upstream_addr ' '"$http_referer" "$http_user_agent"'; access_log /var/log/nginx/access.log main; client_max_body_size 900M; proxy_connect_timeout 600; proxy_read_timeout 600; proxy_send_timeout 600; client_header_timeout 1200; client_body_timeout 1200; server { listen 80 default_server; listen [::]:80 default_server; server_name nginx localhost 0.0.0.0 127.0.0.1 18.144.134.122; charset utf-80; root /var/www; index index.html; gzip on; gzip_static on; gzip_types … -
Django and Mysql high CPU. (optimisation)
I have an application that uses the Django rest framework to expose API endpoints, and the application is receiving ±1000 requests per second (not sure about the number). The Django app and MySQL DB were both in shared web hosting, but since the beginning of this week, the server is experiencing high CPU issues, and after TSing found that the python processes are what causing the issue. So I moved the app to a 2 vCPU, 4G Ram, and SSD hard disk VPS. After moving all data and doing the needed configuration, the app is running but another high CPU issue appeared but this time by Mysqld service, and on avg, it is 150%. When checking the mytop command output, the qps is varying between 100 and 200, while in fewer traffic times it is 65 ( and I’m not sure if it should be less during fewer traffic times given that the traffic has significantly dropped) All requests are looking for the same data and checking if there is an update, I was thinking about changing the methodology to webhook based but the data on my server updates every 30 seconds at most so I thought it won’t do … -
Get .csv values without saving it
Right now I am uploading a .csv file via a model form, saving it in a model and then reading/saving all the values from the .csv to another model. The .csv isn't needed after I get all the values into the other model so I have been trying to find a way to just read the .csv and get the values without saving it into the model. Below is the basics of my view. I appreciate any tips. def ncaab_csv(request): form = CsvUpload(request.POST or None, request.FILES or None) if request.method == "POST": if form.is_valid(): form.save() # Get the submitted csv file games_file = Csv.objects.get(games_entered=False) with open(games_file.file_name.path, 'r') as f: reader = csv.reader(f) for i, row in enumerate(reader): if i == 0: pass else: try: game = NCAABGame.objects.get(name__name=row[1], updated=False, date=today) All NCAABGame fields here... game.save() return redirect(reverse('ncaab_games')) else: messages.error(request, "Failed to save file.") else: template = 'management/ncaab/ncaab_csv.html' context = { 'form': form, } return render(request, template, context) -
"ModuleNotFoundError: No module named 'apps.cashpool'; 'apps' is not a package"
I have a bunch of apps in my Django project which worked smoothly to date. I added another app universe via manage.py startapp as always and now it returns ModuleNotFoundError: No module named 'apps.cashpool'; 'apps' is not a package whenever and wherever I try to import modules. I have all apps listed in my settings.py manage.py check doesn't return any errors All apps have an __init__.py There is no trailing comma missing in settings.py Project structure (I didn't change the structure at all):