Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
How to change a model field based on certain period of time using Django?
I want to make some changes in my model automatically. Here, after a new order is placed I want to update the order status to cancel if isPaid not become true in 1 day of the order placed. how can I do this? class Order(models.Model): PENDING_PAYMENT = 'PENDING_PAYMENT' status_choices = [ ('CANCEL', 'Cancel'), ('PENDING_PAYMENT', 'Pending Payment'), ('ON_HOLD', 'On Hold'), ('WAITING_FOR_PAYMENT', 'Waiting For Payment'), ('PROCESSING', 'Processing'), ('DONE', 'Done'), ] Ordinary = 'Ordinary' customer_choices = [ ('Ordinary', 'Ordinary'), ('Police', 'Police'), ('RAB', 'RAB'), ('DGIF', 'DGIF'), ('CID', 'CID'), ('NAVY', 'NAVY'), ('Air Force', 'Air Force'), ('Army', 'Army'), ('DB', 'DB'), ('Administration', 'Administration'), ] user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) paymentMethod = models.CharField(max_length=200, null=True, blank=True) taxPrice = models.DecimalField(max_digits=11, decimal_places=2, null=True, blank=True) shippingPrice = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) totalPrice = models.DecimalField(max_digits=12, decimal_places=2, null=True, blank=True) isPaid = models.BooleanField(default=False) paidAt = models.DateTimeField(auto_now_add=False, null=True, blank=True) isDelivered = models.BooleanField(default=False) deliverAt = models.DateTimeField(auto_now_add=False, null=True, blank=True) createdAt = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=220, choices=status_choices, default=PENDING_PAYMENT) customerType = models.CharField(max_length=200, blank=True, null=True, choices=customer_choices, default=Ordinary) _id = models.AutoField(primary_key=True, editable=False) def __str__(self): return str(self._id) -
Django: How to get the latest X related-object by criteria, and keep other fields?
I have a case of Authors followed by a User, that I want to sort by their latest published Book, as well as display the book's title and release_date. Authors also have books with a release_date in the future, which I want to keep out of the result-set. I need to return JSON since Django is being used only for backend. After some research the best I've gotten is this: relevant_books = Book.objects.filter(author=OuterRef("pk"), release_date__range=[back_delta, startdate], author__id__in=user_follows).order_by("-release_date") user_authors_with_books = Author.objects.filter(id__in=user_follows) \ .annotate(latest_release_date=Subquery(relevant_books.values("release_date")[:1])) \ .annotate(latest_release_title=Subquery(relevant_books.values("title")[:1])) \ .filter(latest_release_date__isnull=False) \ .order_by(F("latest_release_date").desc(nulls_last=True), "id") \ .values(*fields_to_return, "latest_release_date", "latest_release_title") I'm not a big fan of annotating twice, and have a feeling there's a better way to write this Django ORM code for a quicker/more-efficient (PostgreSQL) query. Am I right? -
Django migration not picking up all the model fields
I created a new Django project on Windows 10, with the latest python and Django. After creating the model with a number of tables/models on one model it skipped some fields. After retrying it would not create a new migration script. I looked at the initial 0001_initial.py and the fields were missing in that file. I later added a single new field and that field migrated property but not the missing fields. All other models were successfully updated in the initial migration. This happens to be a SQLite DB. The model that is missing fields: class articles(models.Model): """ articles""" title = models.CharField (max_length=500) teaser = models.CharField (max_length=500) summary = models.CharField (max_length=1500) byline = models.CharField (max_length=250) category = models.SmallIntegerField articlenote = models.CharField (max_length=1000) author = models.CharField publishedDate = models.DateTimeField articleStatus = models.CharField(max_length=4) articleText = models.TextField last_update= models.DateTimeField def str(self): return self.name The missing fields are : category, author, publishedDate, articleText Interesting after trying to rerun the migration I was getting Missing Defaults errors on a new table I was creating. Since this is a brand new project I can just blow away the database and the migration scripts and try again. I would like to knwo what is potentially causing this … -
"django.core.exceptions.ValidationError: ['“post_id” is not a valid UUID.']" with seemingly valid UUID
This is a simple blog app I am creating. I have a model that creates an article and generates a UUID for each article created. This functions as expected. I am now attempting to create a view variable that contains the "post_id" object from my model "Post" so that I can later insert this variable into my html template. The confusing thing is I know the Post model generates a valid UUID (at least my understand of UUIDs) as I have seen it generated so I am unclear where to start looking to resolve this issue. Other similar issues online do not seem to be related to my issue. myapp/views.py from django.shortcuts import render from django.utils import timezone from .models import Post def blog_list(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') post_uid = Post.objects.get(pk="post_id") context = { "post_uid": post_uid, "posts": posts } return render(request, 'blog/blog_list.html', context) def article(request, post_id): current_article = Post.objects.get(pk=post_id) return render(request, 'blog/article.html', {'current_article':current_article}) myapp/model.py from django.db import models from django.conf import settings from django.utils import timezone import uuid class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) post_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return … -
How to add a line chart for the table visualization and add a drop down in a Django Project?
I have a Django project and I have a model that contains data. Now I want to make a visualization for the data of that model(table) with "line chart"(or other). I also want to add a 'drop down' option so that I can select different options from it and change the line chart automatically. -
Binding specific foreign key to ModelForm
My ModelForm is working but the problem is it currently gives acct_no a dropdown of all customers in the database. this is the workflow currently. So I select a customer profile and add a new job from that profile page. But when the form populates, it is not bound to that customer. I do not want to give them the option to select from a list of customers. Is there a way to automatically bind the form with that specific customer? I'm fairly new to Django and have tried looking at the form docs but I think I'm missing something. models.py class Customers(models.Model): acct_no = models.AutoField(db_column='ACCT_NO', primary_key=True) type = models.CharField(db_column='Type', max_length=45) first_name = models.CharField(db_column='FIRST_NAME', max_length=45, blank=True, null=True) last_name = models.CharField(db_column='LAST_NAME', max_length=45, blank=True, null=True) address = models.CharField(db_column='ADDRESS', max_length=100, blank=True, null=True) class Jobs(models.Model): id = models.IntegerField(db_column='ID', primary_key=True) job_type = models.CharField(db_column='JOB_TYPE', max_length=45, blank=True, null=True) estimatedate = models.CharField(db_column='EstimateDate', max_length=45, blank=True, null=True) estimatetime = models.CharField(db_column='EstimateTime', max_length=45, blank=True, null=True) comments = models.CharField(db_column='COMMENTS', max_length=255, blank=True, null=True) forms.py class JobForm(forms.ModelForm): class Meta: model = Jobs fields = ['acct_no', 'job_type', 'estimatedate', 'estimatetime', 'comments'] widgets = { 'job_type' : forms.Select(choices = JOBS, attrs={'class' : 'form-control form-select'}), 'estimatedate' : widgets.DateInput(attrs={'type' : 'date', 'class' : 'form-control'}), 'estimatetime' : widgets.TimeInput(attrs={'type' : 'time', 'class' … -
Django signal only works when debug=True, DJANGO 3.2.4
I've been lookin everywhere and i coulnd't find any refference about this, my Django model signal only works when the debug=True, but it doesn't work if debug=False, this occur both on localhost and production server. my settings looks like this: settings.py from pathlib import Path import os import environ env = environ.Env() environ.Env.read_env() BASE_DIR = Path(__file__).resolve().parent.parent #production STATIC_ROOT = 'https://d1u356tnw52tcs.cloudfront.net/' SECRET_KEY = env("SECRET_KEY_PROD") DEBUG = True ALLOWED_HOSTS = ['*'] CORS_ORIGIN_ALLOW_ALL = True CORS_ORIGIN_WHITELIST = ( ) # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'django.contrib.postgres', 'sellrapp', 'stock_management', 'corsheaders', 'drf_yasg', 'optimized_image', 'csvexport', 'kronos', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware' ] ROOT_URLCONF = '****.urls' WSGI_APPLICATION = '****.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': env("NAME_PROD"), 'USER': env("USER_PROD"), 'PASSWORD': env("PASSWORD_PROD"), 'HOST': env("HOST_PROD"), 'PORT': env("PORT_PROD"), } } LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Singapore' USE_I18N = True USE_L10N = True USE_TZ = True WEB_BASE_URL = 'https://****.com/' BASE_URL_LIVE_CAMPAIGN = WEB_BASE_URL + "product/" if set to debug=False, the signal wouldn't triggered, and there's no any error trown. signals.py from django.dispatch import receiver from django.db.models.signals import pre_save, post_save, pre_delete from .models import ManualWithdrawals @receiver(pre_delete, sender=ManualWithdrawals) def manual_wd(sender, instance, **kwargs): order = ManualWithdrawals.objects.get(id=instance.id) consumer_order = order.order_id_list.all() sample_order … -
Django - Bypass loading code in the apps.ready function when making migrations or migrating to the database
For starters, I have searched for this before with no luck to find something around this. Background: I have created an inventory application for work to help my team be able to quickly see stats around our IT infrastructure. I have threads kicked off when the application loads to kick off some scraping functions. That code works great, but it happens whenever I create and apply database migrations (manage.py makemigrations & manage.py migrate). Goal: I'd like to only kick off the scraping code when I'm issuing the runserver command (manage.py runserver). This way, I don't have resources competing between the migration activities and the scraping activities. It also often generates lots of errors because sometimes not all of the database models/fields exist in the database yet. Ideas: Modify the code in the django repository to introduce a flag that I can then check against before I have the scraping code run. Not recommended This will get overwritten when I update django, and it won't persist between my dev server and prod server. Find a way to check which command is being run with the manage.py, and introduce a check to only start scraping if that command is run. Recommended This … -
Where to put a background task and how to be able to still debug
I have an almost model-less django app running, that collects infos from some API calls and displays them on a frontend via DRF. At some point I need to start calling this other API after django started and in debugging I face the problem of an unresponsive console, as soon as I activate the server via runserver command. My service so to say vastly looks like this: class APISERVICE(object): def __init__(self): self.time_now = datetime.datetime.now() self.sDATA = ServerAPI("https", settings.API_URL, settings.API_USR, settings.API_PWD) threading.Thread(target = self.worker, kwargs = {"interval": 10, "function": self.pollAPI}).start() def worker(self, interval, function): while True: function() time.sleep(interval) def pollAPI(self): try: self.time_since_last_run = (self.time_now - self.time_old).seconds except Exception as E: self.time_since_last_run = 20 if self.time_since_last_run >= 20: self.time_old = datetime.datetime.now() data = self.sDATA ... Two Questions arise: the serivce should run "forever" and therefore I thought about just calling it from inside the views.py or the apps urls.py. Why is that good/bad? When instantiated the console can not stop the execution any more in debug mode via CTRL + C - I suspect this is due to the sleep command. How can I avoid this without installing something like celary or django-background-tasks? -
JS music player error : "TypeError: 'arguments', 'callee', and 'caller' cannot be accessed in this context"
I have a music player inside a Django app, written in JQuery, the user track files get uploaded into a AWS S3 bucket, I'm then trying to fetch the data from a REST API to get the mp3 link into the music.js code, when the app runs locally it works fine when loading tracks but after deployed to Heroku the tracks don't load, the music player just seems to be stuck on loading. I'm also getting an error in the Array prototype - construction function() in the console : "TypeError: 'arguments', 'callee', and 'caller' cannot be accessed in this context". here is the jquery code for the music player notice the top fetch async function populates the trackUrl array with the mp3 link, it also fetches the track name and artist name, How can I fix this?: music.js $(function () { async function getUserTracks() { try { await fetch("https://sound-city.herokuapp.com/music/music_all/?format=json") .then(res => res.json()) .then(data => { for (item of data) trackNames.push(item['title']), trackUrl.push(item['track']), albums.push(item['artist_name']) console.log(trackNames, trackUrl, albums) }) } catch(error) { console.error(error) } } getUserTracks(); function createAlbumId() { setTimeout(function () { let number = 0; for (let i = 0; i < trackUrl.length; i++) { number++; albumArtworks.push(`_${number}`); // console.log(albumArtworks); } }, 100) …