Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
OperationalError at /users/friend-request/accept/6/ no such table: main.users_profile__old
I'm unable to accept the friend request, delete request and send request is working fine users/views.py @login_required def send_friend_request(request, id): user = get_object_or_404(User, id=id) frequest, created = FriendRequest.objects.get_or_create( from_user=request.user, to_user=user) return HttpResponseRedirect('/users/{}'.format(user.profile.slug)) @login_required def accept_friend_request(request, id): from_user = get_object_or_404(User, id=id) frequest = FriendRequest.objects.filter(from_user=from_user, to_user=request.user).first() user1 = frequest.to_user user2 = from_user user1.profile.friends.add(user2.profile) user2.profile.friends.add(user1.profile) if FriendRequest.objects.filter(from_user=request.user, to_user=from_user).first(): request_rev = FriendRequest.objects.filter(from_user=request.user, to_user=from_user).first() request_rev.delete() frequest.delete() return HttpResponseRedirect('/users/{}'.format(request.user.profile.slug)) if any more code is required, please comment below -
How to add a button in a django list to add List's data to a HTML TextField?
I'm looking for the best implementation of adding data to view from the Django model in a list rendered in a template with the help of a button that sits along with other data on every row. To be specific, I want a person's phone number to be selected and be initiated to view on form submission which then sends SMS to those numbers via API. models.py class Patient(models.Model): patient_serial = models.IntegerField(null=True, blank=True) customer = models.CharField(max_length=100) phone_regex = RegexValidator( regex=r'^\+?1?\d{9,10}$', message="Phone number must be entered in the format: '98xxxxxxxx'. Up to 10 digits allowed.") customer_phone = models.CharField( validators=[phone_regex], max_length=10, blank=True) GENDER_CHOICES = ( ('O', 'Others'), ('M', 'Male'), ('F', 'Female'), ) gender = models.CharField( max_length=10, choices=GENDER_CHOICES, default='None') date_of_birth = models.DateField() age = models.IntegerField(null=True, blank=True) billing_address = models.CharField(max_length=100, null=True, blank=True) date = models.DateField()blank=True) issue_detail = models.TextField( max_length=250, null=True, default="", blank=True) treatment_plan = models.ForeignKey( TreatmentPlan, on_delete=models.CASCADE, null=True, blank=True) total_amount = models.ForeignKey( Invoice, on_delete=models.CASCADE, blank=True, null=True) status = models.BooleanField(default=False) def __str__(self): return str(self.customer) def get_status(self): return self.status def get_absolute_url(self): return reverse('patients') def num(self): return self.customer_phone views.py def composeSMS(request): text = request.POST.get('smsArea', False) recipients = request.POST.get('contacts', False) sms = requests.post( "<api-endpoint>", data={'token': '<api-key>', 'from': 'Company', 'to': recipients, 'text': text}) sms_status_code = sms.status_code sms_response = sms.text … -
Django Rest-Framework with simpleJWT returns Anonymous User when sending request from Postman
I am trying to use SimplejWT along with Django Rest-Framework to do the authentication. When I go to the endpoint through the browser, I get this response: But when I use postman, I get back an anonymous user. This is my postman config: My SimpleJWT config is: SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(days=30), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'ROTATE_REFRESH_TOKENS': False, 'BLACKLIST_AFTER_ROTATION': False, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, 'JWK_URL': None, 'LEEWAY': 0, 'AUTH_HEADER_TYPES': ('Bearer',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), } The code for the endpoint is: @api_view(['GET']) def get_user_profile(request): print(request.user) user= request.user serializer= UserSerializer(user, many= False) return Response(serializer.data) The user serializer is coded this way: class UserSerializer(serializers.ModelSerializer): class Meta: model= User fields= ['id', 'username', 'email'] -
Filter based on whether a user is part of a project's team
I have two models Project and User. A project's team is a many to many field with with the User model. models.py # Create your models here. class Project(models.Model): title = CharField(max_length=30) description = TextField() due_date = DateField() team = ManyToManyField(settings.AUTH_USER_MODEL) INACTIVE = 0 ACTIVE = 1 STATUS = ( (INACTIVE, ('Inactive')), (ACTIVE, ('Active')), ) active = models.IntegerField(default=1, choices=STATUS) def __str__(self) -> str: return f'{self.title}' views.py @login_required def index(request): user = request.user tickets = Ticket.objects.filter(assigned_to=user) ticket_count = len(tickets) projects = Project.objects.filter(team__in = user) project_count = len(projects) context = { 'tickets':tickets, 'ticket_count':ticket_count, 'projects':projects, 'project_count':project_count, } return render(request, 'bugtracker_app/index.html', context) I am trying to use the Query set API to return the projects a the currently logged on user has been assigned to. However I've been getting the following error: TypeError: 'User' object is not iterable How can I resolve this error and get a query set of the projects a user is working on? -
Is there a standard practice for storing flat data files that are used for testing in a Django project?
I'm unit testing the way that my Django application loads and processes various flat files and I'm having trouble deciding where to store the files that contain the data for these tests. Is there a standard practice or location for this? Would it make more sense to store these files in one of the STATICFILES_DIRS or in a subdirectory of MEDIA_ROOT, or some other directory? If some other directory, how might that be configured in the settings module? For example: from pathlib import Path from django.core.files.uploadedfile import SimpleUploadedFile from django.test import TestCase def simulate_uploaded_file(data_path: Path, filename: str) content_type = get_content_type(filename) filepath = data_path / filename content = open(filepath, 'rb').read() data_file = SimpleUploadedFile(data_file_path, content, content_type) class TestFileHandler(TestCase): @classmethod def setUpTestData(cls): test_data_path: Path = settings.TEST_DATA_DIR # <- IS THERE A STANDARD LOCATION FOR THIS? cls.valid_csv: SimpleUploadedFile = simulate_uploaded_data(test_data_path, 'filename.csv') -
INSERT, REPLACE, UPDATE not working in Python and SQLite with Django Framework
What I am using I am using python codes to access a database with multiple tables in SQLite. All this is done in Linux's Ubuntu OS The Problem The problem is that I am unable to UPDATE, INSERT, REPLACE data in one of the tables through python codes but DELETE works just fine, meaning I am able to delete a specific row in the table. For reference, when using the same commands for another table, it works fine. What I have done I have used .commit() in python, but the codes do not commit. To see if these commands work in the database itself, in case there were unknown permissions set, I used DB Browser for SQLite and they do work when done directly through the database. Any idea if there might be any explicit permissions set to each command in SQLite or is there any other cause for this? And are there any suggestions as to what I should do to check? -
Django - Test to ping DRF Swagger
I have these urls under my urls.py SWAGGER_URLS = [url(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'), url(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='swagger')] then I have this test SwaggerTest.py from django.test import TestCase from django.urls import reverse from rest_framework import status class SwaggerTest(TestCase): def test_successful_swagger_pint(self): response = self.client.get(reverse('swagger')) self.assertEqual(response.status_code, status.HTTP_200_OK) I'm getting the exception django.urls.exceptions.NoReverseMatch: Reverse for 'swagger' not found. 'swagger' is not a valid view function or pattern name. when I run this test. When I ping the url myself it works fine. I'm using django-rest-swagger==2.2.0. -
DoesNotExist at /nuevo/ Profile matching query does not exist
sorry I'm quite new to Django and Python, doing a school project, I was doing a default login with python, it creates the users and makes a login, so far so good. When I log in with the admin I can enter "html.html" without problems and the view runs and makes the queries in the database, the problem is when I log in with a different profile than the admin, I get this message DoesNotExist at /nuevo/ Profile matching query does not exist. Request Method: GET I think the problem is with this query query = Profile.objects.get(pk=request.user.pk) What I wanted was for the user who is logged in to send me to work on their database, I don't know what else to do :( these are my models from django.db import models from django.contrib.auth.models import User from django.utils import timezone # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='batman.png') equip = models.CharField(max_length=1500,default=0) pokemon1 = models.CharField(max_length=1500,default=0) pokemon2 = models.CharField(max_length=1500,default=0) pokemon3 = models.CharField(max_length=1500,default=0) pokemon4 = models.CharField(max_length=1500,default=0) pokemon5 = models.CharField(max_length=1500,default=0) pokemon6 = models.CharField(max_length=1500,default=0) def __str__(self) -> str: return f'Perfil de {self.user.username}' class Post(models.Model): user=models.ForeignKey(User, on_delete=models.CASCADE,related_name='posts') timestamp = models.DateTimeField(default=timezone.now) content = models.TextField() class Meta: ordering = ['-timestamp'] def __str__(self): … -
Django UpdateView didn't update page
My form: class TestCaseUpdateForm(forms.ModelForm): class Meta: model = TestCase fields = ( 'name', 'executable', 'parameter_list', 'executable_type', 'test_type' , 'project_name', 'created_by') My views: class EditCaseView(UpdateView): model = TestCase form_class = TestCaseUpdateForm template_name_suffix = '_update_form' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) pk = self.kwargs.get(self.pk_url_kwarg) queryset = self.get_queryset().filter(pk=pk) case = queryset.get() context['my_case'] = case context['my_exetype'] = TestCase.EXECUTABLE_TYPE_CHOICES context['my_ttype'] = TestCase.TEST_TYPE_CHOICES context['projnames'] = PROJNAME_CHOICES return context def get_success_url(self): print("get_success_url") return reverse("integratedTest:testCase") My model: PROJNAME_CHOICES = ( ('Name1', 'Name1'), ('Name2','Name2'), ('Name3','Name3') ) class TestCase(models.Model): EXECUTABLE_TYPE_CHOICES = ( ('e_type1', 'e_type1'), ('e_type2', 'e_type2'), ('e_type3', 'e_type3'), ) TEST_TYPE_CHOICES = ( ('t_type1', 't_type1'), ('t_type2','t_type2'), ('others', 'others'), ) name = models.CharField(max_length=200, unique=True) executable = models.CharField(max_length=1023) parameter_list = models.TextField(blank=True, default = "") project_name = models.CharField(max_length=200, choices = PROJNAME_CHOICES, default="Name1") executable_type = models.CharField(max_length=200, choices = EXECUTABLE_TYPE_CHOICES, default = "e_type1") test_type = models.CharField(max_length=200, choices = TEST_TYPE_CHOICES, default = "t_type1") created_by = models.CharField(max_length=200, default = "sb") create_datetime = models.DateTimeField("testcase created on", auto_now = True) My template: <form method="post">{% csrf_token %} <h1 >Edit Test Case:</h1> <table> <tr> <th>Name:</th> <th>executable:</th> <th>parameter_list:</th> </tr> <tr> <td><input type="text" id="id_name" name="name" value = "{{my_case.name}}" placeholder="short_unique_string" required> </td> <td> <input type="text" id="id_executable" name="executable" value = "{{my_case.executable}}" placeholder="FilenameWithoutPath.py" required> </td> <td><textarea id="id_parameter_list" name="parameter_list" value = "{{my_case.parameter_list}}" placeholder="Copy your parameter string here directly"></textarea> … -
Join 2 tables over 2 columns in django
I have a database imported from mysql in models.py like : class Sig(models.Model): id = models.IntegerField(db_column='Id', primary_key=True) proportion = models.FloatField(db_column='Prop', blank=True, null=True) marine_area = models.CharField(db_column='Marine_Area', max_length=255, blank=True, null=True) habitat = models.CharField(db_column='Habitat', max_length=255, blank=True, null=True) This one doesn't have any coordinates associated. The coordinates are in another table : class Coord(models.Model): id = models.IntegerField(db_column='Id', primary_key=True) marine_area = models.CharField(db_column='Marine_Area', max_length=255, blank=True, null=True) habitat = models.CharField(db_column='Habitat', max_length=255, blank=True, null=True) latitude = models.FloatField(db_column='Latitude', blank=True, null=True) longitude = models.FloatField(db_column='Longitude', blank=True, null=True) I want to visualized my proportions according to their coordinates (latitude and longitude). However, each localisation is define with a marine area and an habitat (each marine area has 3 habitats) for ex So how can I create a new column with the concatenation of marine area and habitat to be able to join my two tables ? or is there any other solution to join my two tables ? Thanks ! -
some css code wont work on django project
I'm having this unusual issue with my CSS file and Django, some of my CSS code will work but some wont and to make it work I have to make a style section on my head tag while the rest of the CSS code is in my style.css file this is really bizarre and only happens with any new code I add to the CSS file. is anyone having the same issue, I have my settings file good and all STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) it is so funny well I'll leave this one odd issue to the pros lol. -
Django Ckeditor Automatically Save Data to Server / Backend
How would I go about automatically saving data from frontend ckeditor to the backend without reloading the page. I tried using ajax to make this work, but I am unable to send the updated content to the backend. Additionally, the javascript on change method is triggering 2x per single input. For example if I type "A" for a new input in ckeditor, it'll trigger twice for some unknown reason. Approach 1 - HTML / JS (Click "submit" button when change is detected) <form class="pt-2" action="#" method="POST" id="designer-form"> {% csrf_token %} {{ form.media }} {% for field in form %} {{ field }} {% endfor %} <div class="mt-4 flex justify-end space-x-4"> <button type="submit" id="submit"> Save Changes </button> </div> </form> <script> CKEDITOR.on('instanceCreated', function(event) { let editor = event.editor; editor.on('change', function() { setTimeout(function () { document.getElementById("submit").click(); }, 2500); }); }); </script> Approach 2 - HTML / JS (Serialize Data) <form class="pt-2" action="#" method="POST" id="designer-form"> {% csrf_token %} {{ form.media }} {% for field in form %} {{ field }} {% endfor %} <div class="mt-4 flex justify-end space-x-4"> <button type="submit" id="submit"> Save Changes </button> </div> </form> <script> CKEDITOR.on('instanceCreated', function(event) { let editor = event.editor; editor.on('change', function() { let data = editor.getData(); setTimeout(function (){ $.ajax({ … -
Check user doesn't already have this object before displaying CreateView - Prevent them from creating multiples
I've been slowly learning Django over the past few weeks, and applying it to a work prototype. I have a simple profile model called Applicant. This stores personal fields for the a customer. It contains a OnetoOne field linking to the Django Auth User model, as I'm using this to require login and control access to data. I'm struggling to figure out how to perform checks within View Classes (seemed easier within View Functions), I need a way to check if a user already has an Applicant entry before presenting them with the CreateView form. Previously to display this Applicant profile data (created via admin page), I used the get_object_or_404 within the DetailView.get_object to catch Http404 and return None if they didn't have a profile. This would then provide a link to the Create page. I need to implement the reversed logic on the CreateView, to protect them from creating multiple Applicant entries. Any suggestions would be great, even just to point me in the right direction. Code I used for DetailView: class ApplicantProfileDetailView(LoginRequiredMixin, generic.DetailView): model = Applicant template_name ='profile.html' def get_object(self, queryset=None): try: return get_object_or_404(Applicant, user=self.request.user) except Http404: return None <h1>Applicant Profile</h1> {% if applicant %} ... {% else … -
Letting the user Select a Font-Family in Django Web Application
I am in the process of building a Django Web Application that lets a user customize different CSS options for their webpage in the Django Admin Web Interface. Currently, the admin user has the option to change the color, background-color, and font-family. I used Django forms to create a Color Selector Widget so the user doesn't have to type in a hex color value and type in the name of a font. I am trying to create a widget to let the user select a font from a list of font-familys. I've looked into tkinter and listboxes but it appears it is best for GUIs. Should I just create a list of choices and populate it with a bunch of fonts? I have been having a hard time coming up with a viable efficient option. forms.py class cssForm(ModelForm): class Meta: model = styleEditor fields = "__all__" widgets = { "Link_Color": TextInput(attrs={"type": "color"}), "Link_Background_Color": TextInput(attrs={"type": "color"}), } models.py class styleEditor(models.Model): Link_Color = models.CharField(max_length=7, default="#000000") Link_Font_Style = models.CharField(max_length=15, default="Brush Script MT") Link_Background_Color = models.CharField(max_length=7, default="#F5F5F5") admin.py @admin.register(styleEditor) class styleEditor(admin.ModelAdmin): form = cssForm -
Django how to compere calculated fields in query
Is it possible to get data from another table in a query by comparing calculated values? Like for example, by calculating using the minimum and maximum price values and getting Url's to them from another table. My models look like this: class Product(models.Model): id = models.CharField(..) price = models.FloatField(..) url = models.CharField(..) ..... class ProductHistory(models.Model): ProductID = models.ForeignKey(Product, on_delete=models.CASCADE, to_field='ProductID', db_column='ProductID') price = models.FloatField(..) date = models.DateTimeField(..) My request looks like this query = HistoryPrice.objects.filter(ProductID=products).filter(query_price) \ .annotate(dt=Trunc('StartDate', frequency)) \ .values('dt') \ .annotate(max_price=Max('Price'), min_price=Min('Price')) \ .order_by('dt') But i want to get Url from Product table for each max_price for given period. How can i achieve it -
How can I solve ValueError in django. Exception Value: ModelForm has no model class specified
This is my code; django.models. my model.py file from django.db import models class Product(models.Model):title = models.CharField(max_length=150) description = models.TextField(blank=True, null=True) price = models.DecimalField(decimal_places=2, max_digits=100000) summary = models.TextField(blank=True, null=False) featured = models.BooleanField(default=False) forms.py That's my full form.py file from django import forms from .models import Product class ProductForm(forms.ModelForm): class Meta: model = Product fields = [ 'title', 'description', 'price', ] class RawProductForm(forms.ModelForm): title = forms.CharField() description = forms.CharField() price = forms.DecimalField() **django.views** my django.views file from django.shortcuts import render from .models import Product from .forms import ProductForm, RawProductForm def product_create_view(request): my_form = RawProductForm() if request.method == 'POST': my_form = RawProductForm(request.POST) if my_form.is_valid(): print(my_form.cleaned_data) Product.objects.create(**my_form.cleaned_data) else: print(my_form.errors) context = {'form': my_form} return render(request, "products/product_create.html", context) **products_create.html** #this is my html file {% extends 'base.html' %} {% block content %} <form action="." method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Save" /> </form> {% endblock %} In his code I'm trying to make a form but when I run python manage.py runserver at http://127.0.0.1:8000/create/ I'm getting ValueError This is a screenshot of my full error messagae -
where is the data saved during Django stack development
Maybe this is a super silly question. I am new with Django stack web app development. I am following Django tutorial on MDN. I entered information to the backend database via the admin page. But some error happened later so I had to uninstall pyenv and restart. I wonder if I can find all the information I entered which is not on any project documents. Thanks. -
Django Debug Toolbar causes 404 error in DEBUG mode
After installing Django Debug Toolbar and adding all setting, I'm getting 404 error. I did command collectstatic, but that did not help. Here is my files: settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) .... INSTALLED_APPS = [ ... 'debug_toolbar', ... ] MIDDLEWARE = [ ... 'debug_toolbar.middleware.DebugToolbarMiddleware', ] ... STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'spare_part/static') ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('mileage.urls')), ] if settings.DEBUG: import debug_toolbar urlpatterns = [ path('__debug__/', include(debug_toolbar.urls)), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) What to do? -
how to present donut type percentages using django and chart.js
how to present donut type percentages using django and chart.js. with the code below I just got the text of the title. The percentages being calculated and displayed in the terminal when I add the print instruction, for example print(data1). i use filter and count for the percentage of evens by type. Voici mon code views.py a #Views.py def even_percentage_chart(request): labels = ["Science", "Sport", "Other"] data1 = [] data2 = [] data3 = [] data = Even.objects.all().count() dat1 = Even.objects.filter(typ__contains='Science').count()* 100/data data2 = Even.objects.filter(typ__contains='Sportif').count()* 100/data data3 = Even.objects.filter(typ__contains='Other').count()* 100/data try: return JsonResponse(data={ 'labels': labels, 'data1': data1, 'data2': data2, 'data3': data3, }) except (ValueError, ZeroDivisionError): return "" #script.js <script> $(document).ready(function(){ $.ajax({ url: "{% url 'even:even_percentage_chart' %}", dataType:"json", type:"GET", contentType:"application/json", success: function(response){ if(response){ var config = { type: 'doughnut', data: { //labels: ["Science", "Sport", "Other"], datasets: [{ data: response['data1'], backgroundColor: ['#4e73df'], hoverBackgroundColor: ['#2e59d9'], hoverBorderColor: "rgba(234, 236, 244, 1)", }, { data: response['data2'], backgroundColor: ['#1cc88a'], hoverBackgroundColor: ['#17a673'], hoverBorderColor: "rgba(234, 236, 244, 1)", }, { data: response['data3'], backgroundColor: ['#36b9cc'], hoverBackgroundColor: ['#2c9faf'], hoverBorderColor: "rgba(234, 236, 244, 1)", }], }, options: { title: { display: true, text:'Percentage of evens by type:science,sport,...' }, maintainAspectRatio: false, tooltips: { backgroundColor: "rgb(255,255,255)", bodyFontColor: "#858796", borderColor: '#dddfeb', borderWidth: 1, xPadding: 15, … -
Django with Heroku
Having problems trying to set a secret key inside an .env instead of the settings.py file When I run the heroku config I get the secret key (portfolio) PS C:\Users\arund\Desktop\Code\Django\portfolio-project> heroku config:get SECRET_KEY value When I run the following I get errors. (portfolio) PS C:\Users\arund\Desktop\Code\Django\portfolio-project> heroku local [OKAY] Loaded ENV .env File as KEY=VALUE Format 1:53:57 PM web.1 | Traceback (most recent call last): 1:53:57 PM web.1 | File "C:\Users\arund\Desktop\Code\Django\portfolio-project\manage.py", line 22, in <module> 1:53:57 PM web.1 | main() 1:53:57 PM web.1 | File "C:\Users\arund\Desktop\Code\Django\portfolio-project\manage.py", line 18, in main 1:53:57 PM web.1 | execute_from_command_line(sys.argv) 1:53:57 PM web.1 | File "C:\Users\arund\Desktop\Code\Django\portfolio-project\venv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line 1:53:57 PM web.1 | utility.execute() 1:53:57 PM web.1 | File "C:\Users\arund\Desktop\Code\Django\portfolio-project\venv\lib\site-packages\django\core\management\__init__.py", line 395, in execute 1:53:57 PM web.1 | django.setup() 1:53:57 PM web.1 | File "C:\Users\arund\Desktop\Code\Django\portfolio-project\venv\lib\site-packages\django\__init__.py", line 24, in setup 1:53:57 PM web.1 | apps.populate(settings.INSTALLED_APPS) 1:53:57 PM web.1 | File "C:\Users\arund\Desktop\Code\Django\portfolio-project\venv\lib\site-packages\django\apps\registry.py", line 122, in populate 1:53:57 PM web.1 | app_config.ready() 1:53:57 PM web.1 | File "C:\Users\arund\Desktop\Code\Django\portfolio-project\venv\lib\site-packages\django\contrib\admin\apps.py", line 27, in ready 1:53:57 PM web.1 | self.module.autodiscover() 1:53:57 PM web.1 | File "C:\Users\arund\Desktop\Code\Django\portfolio-project\venv\lib\site-packages\django\contrib\admin\__init__.py", line 24, in autodiscover 1:53:57 PM web.1 | autodiscover_modules('admin', register_to=site) 1:53:57 PM web.1 | File "C:\Users\arund\Desktop\Code\Django\portfolio-project\venv\lib\site-packages\django\utils\module_loading.py", line 47, in autodiscover_modules 1:53:57 PM web.1 | import_module('%s.%s' … -
I want to make a button in django interactive when a product is free or premium
I want to make a button in django interactive in a case where a product category is free, i want the button to show “download” but if the product is premium, let the button be “Subscribe”. I don’t really know how to hook thing up yet using the ORM, any help would be appreciated Let me show some code models.py class Package_Category(models.Model): title = models.CharField(max_length=10000, verbose_name="Title") slug = models.SlugField(max_length=1000, unique=True) def get_absolute_url(self): return reverse("package-categories", args=[self.slug]) def __str__(self): return self.title class Vectors(models.Model): title = models.CharField(max_length=10000, null=True, blank=True, verbose_name="Title") slug = models.SlugField(unique=True) image = models.ImageField(upload_to="vectors-images/%Y/%m/%d/", default="default.jpg", verbose_name="Image Cover") vec_file = models.FileField(upload_to='vector-uploads/%Y/%m/%d/', null=True, blank=True, verbose_name="Upload File") category = models.ForeignKey(Category, on_delete=models.DO_NOTHING, verbose_name="Category") package_category = models.ForeignKey(Package_Category, on_delete=models.DO_NOTHING, verbose_name="Package Category") file_format = models.ForeignKey(Format, on_delete=models.SET_NULL, null=True, blank=True) tags = models.ForeignKey(Tag, on_delete=models.DO_NOTHING, verbose_name="Tag") status = models.CharField(choices=STATUS_CHOICE, default="published", max_length=150, verbose_name='Status') creator = models.ForeignKey(User, on_delete=models.DO_NOTHING, verbose_name="Creator") # creator_image = models.ImageField(upload_to="creators-images/%Y/%m/%d/", default="default.jpg", verbose_name="Creator Image") # creator_bio = models.CharField(max_length=10000, null=True, blank=True, verbose_name="Creator Bio", default="Graphics Designer") created = models.DateTimeField(auto_now_add=True, verbose_name="Created") class Meta: verbose_name = "Vector" verbose_name_plural = "Vectors" def get_absolute_url(self): return reverse("elements:vector-details", args=[self.slug]) def __str__(self): return self.title views.py if needed def VectorDetails(request, vectors_slug): vector = get_object_or_404(Vectors, slug=vectors_slug) vectors = Vectors.objects.filter(status='published').order_by('?')[:6] creators = Profile.objects.filter(creator=True) categories = Category.objects.all() info = Announcements.objects.all() # creator = Profile.get_object_or_404(pk=pk) … -
Uploading fixtures to django running within docker container in an AWS EC2 instance
So I have a a few operations I need to perform on a running instance - kind of a one-off thing. That involves uploading fixtures to it. The structure is an aws ec2 instance, on which runs a few docker container, including a django container. This the docker container in which I need to upload fixtures. This is all part of a ci/cd pipeline, with a postgres RDS database, nginx proxy, and the django container. I can scp the fixtures into the AWS EC2 instance. Then I can SSH into the EC2 instance, and from there log into the running container (using docker exec). That's all fine, but.... How can I access the fixtures that I uploaded to the ec2 instance (the docker host) from within the docker-container? Note: I'm aware I could commit the fixtures to git, then they would find their way into the docker image and be readily available there. I possible I'd rather scp them directly to ec2 & manage them in command lines (because small changes might be needed to the fixtures, which then means I have to run the whole pipeline and wait a few minutes each time...) -
Django Rest Framework Copeapi LinkLookupError
I am getting a LinkLookupError when trying to get a endpoint served by Django Rest Framework. This error only occurs after a single successfully request. My DRF view.py looks like: class RecordViewSet(viewsets.ReadOnlyModelViewSet): """ API endpoint that allows Records to be viewed or edited. """ filter_backends = (SimpleRecordFilterBackend,) serializer_class = RecordSerializer permission_classes = (IsAuthenticated,) @action(detail=False, url_path='tagsum/(?P<account>[^/.]+)/(?P<tag>[^/.]+)') def tagsum(self, request, account, tag): if not account or not tag: return Response({'status': "need accoutn and tag"}) sum = Records.objects.filter(linkedaccount_id=account).filter(user_project=tag).aggregate(total=Sum('unblendedcost')) return Response({'sum': sum['total']}) def get_queryset(self): q = Q() linkedaccount_id = self.request.query_params.get("linkedaccount_id") or '' user_project = self.request.query_params.get("user_project") or '' if linkedaccount_id: q &= Q(linkedaccount_id=linkedaccount_id) if user_project: q &= Q(user_project=user_project) return Records.objects.filter(q).annotate(Sum('unblendedcost')) After modifying the view file, I call $coreapi get http://localhost:8000/api/docs/ and see: ... records: { list([page], [linkedaccount_id], [productname], [user_project]) tagsum(account, tag) read(id, [linkedaccount_id], [productname], [user_project]) } ... and after one page load that calls that endpoint, when I run the same command I see this output: ... records: { tagsum: { read(account, tag) } list([page], [linkedaccount_id], [productname], [user_project]) read(id, [linkedaccount_id], [productname], [user_project]) } ... Note that the tagsum method now has the read method nested. Calls to the endpoint now return the following error. errors.js:10 Uncaught LinkLookupError: Invalid link lookup: ["records","tagsum"] at new LinkLookupError (errors.js:10) … -
How put css on django?
I have a big problem.Django dont see my css files.PHG My css file is located in polls.But django dont see it. My home.html <link rel="stylesheet" type="text/css" href="home.css"> <title>121212</title> <body> <div id="1212"> <li class="fafa">12112</li> </div> </body> my settings.py STATIC_URL = '/static/' STATIC_DIRS = [os.path.join(BASE_DIR, "static"),] STATIC_ROOT = os.path.join(BASE_DIR, 'static')``` -
Optimizing queries with Django ORM
I am using debug-toolbar to see the number of overall queries. The problem is that when I reload the page, I see different number of overall queries, given the same code and very short period of page reload intervals. I understand this is somehow related to caching. The question is, is there any shortcut to make Django at least in the debug mode always run all the queries so that I can see the real impact of my changes in the code ?