Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problem linking CSS file to HTML file using Django
I had some issues linking a CSS file to HTML file while using Django. Here is my HTML file where I linked a static file name home.css {% load static %} <link rel="stylesheet" href="{% static 'home.css' %}" type="text/css"> My folder is organised as so for my templates folder: \Users\me\Desktop\mysite\templates\base\home.html And for my static folder: \Users\me\Desktop\mysite\static\home.css Doesn't someone know from where does the problem come? -
My website template is aligned to the left side
My code is exceeding the word limit so you can see the code here. This is my template and when I run the server locally, the webpage is kinda aggined to the left side like this. But in fact, it should look like this.. I set the static directory in the settings.py as STATIC_DIRS = (os.path.join(BASE_DIR, "static"),) and I loaded the static on the top of the page as shown. Can't figure out the problem. -
How to apply split function to a specific field in Django's queryset
I am using Django and groupby based on the 'teacher' field. However, there are two or three values in the 'teacher' field as well as one, so I want to split it. However, I get an error saying that 'F' object has no attribute 'split'. If you have any other workaround, please help me! [views.py] counts = Research.objects.values(F('teacher').split('/'))\ .annotate(count=Count('id', distinct=True))\ .values('teacher', 'count') teacher subject Helen math Adam/Jennie science Jennie music The result I want to get is: <Queryset: [{teacher:'Helen', count:'1'}, {teacher:'Adam', count:1}, {teacher:'Jennie', count:2}]> -
403 Forbidden when using Django's PermissionRequiredMixin
I'm trying to restrict access to the view 'GovernmentView' to users whose account has True on the field 'is_government' by implementing the PermissionRequiredMixin argument. But it's not working. Registered users who have True for the field 'is_government' are getting the 403 Forbidden error (and Superusers who have False on that field do not see the error and can access the template). How can I fix this error and restrict access as stated above? Thanks. settings.py: LOGIN_URL = reverse_lazy('users:login') LOGIN_REDIRECT_URL = 'users:home' urls.py: app_name = 'users' urlpatterns = [ path('', views.login_view, name='login'), path('logout/', views.logout_view, name='logout'), path('register/', views.register_view, name='register'), path('activate-user//', views.activate_user, name='activate'), path('home/', views.home, name='home'), path('government/', views.GovernmentView.as_view(), name='government'), models.py: class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) is_active = models.BooleanField(default=True) is_email_verified = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_government = models.BooleanField(default=False, verbose_name="Gov't Official") date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email @staticmethod def get_absolute_url(self): return reverse("users:home") views.py: class GovernmentView(PermissionRequiredMixin, ListView): permission_required = 'CustomUser.is_government' template_name = 'users/government.html' model = List form_class = Form def get_context_data(self, **kwargs): context = super().get_context_data() context["List"] = List.objects.all() return context government.html: {% if request.user.is_government%} <div class="nav"> <a id="government" {% block government %} class="selected" {% endblock %} href="{% url 'users:government' %}"></a> </div> {% endif … -
in this django code when i post some text saveed in the table betwen (' my text i post ',)
view def Apply2 (request): if request.method=="POST": q1 = order.objects.last() if q1 is not None: q1.Course_Selection = request.POST["1221"], q1.save() response = redirect('/apply3') return response return render(request,'Apply_Now2.html') -
Django with aurora, how to use two instances?
I have django script with mysql My settings is below. mysql server is in the local. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', "NAME": config("DB_NAME"), "USER": config("DB_USER"), "PASSWORD": config("DB_PASSWORD"), "HOST": 127.0.0.1, "PORT": config("DB_PORT"), 'OPTIONS': { 'charset': 'utf8mb4', 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'" }, } } Now I want to use amazon AURORA It has two instances reader/writer How can I set the instance to django?? -
'SimpleHistoryAdmin' has no attribute _meta problem
i installed django-simple-history but, it's not working. I tried python manage.py makemigrations i paced below error. like AttributeError: type object 'SimpleHistoryAdmin' has no attribute '_meta' I want to see history in django-admin. what's wrong????? Traceback (most recent call last): class AccountClassificationAdmin(admin.ModelAdmin): File "/root/miniconda3/envs/gdaj/lib/python3.9/site-packages/django/contrib/admin/decorators.py", line 100, in _model_admin_wrapper admin_site.register(models, admin_class=admin_class) File "/root/miniconda3/envs/gdaj/lib/python3.9/site-packages/django/contrib/admin/sites.py", line 113, in register if model._meta.abstract: AttributeError: type object 'SimpleHistoryAdmin' has no attribute '_meta' # settings.py i added 'simple_history', at installed_app 'simple_history.middleware.HistoryRequestMiddleware', at middleware # models.py class PayHistory(TimeStampedModel): package_patient = models.CharField(max_length=10, null=False) package_classification = models.CharField(max_length=10, null=False) history = HistoricalRecords() class PayHistoryChange(TimeStampedModel): payhistory = models.ForeignKey(PayHistory, on_delete=models.CASCADE, null=False) history = HistoricalRecords() # admin.py @admin.register(PayHistory) class AccountCategoryAdmin(SimpleHistoryAdmin): list_display = ( "package_patient", "package_classification" ) -
Cannot get "images" net::ERR_CONNECTION_REFUSED (Gitpod)
On Gitpod, my NextJS frontend is trying to fetch the list of objects which contain "product names", "prices" and "images" from my Django Rest API backend. Then, my NextJS frontend can get the list of objects which contain "product names" and "prices" but not "images" so my NextJS frontend cannot get only "images" as shown below: ("product names" such as "boots 4", "boots 3" ... and "prices" such as "£12.10", "£10.50" ... are displayed but not "images") This is my desired output with "product names", "prices" and "images": On Gitpod, both my NextJS frontend on port 3000 open (private) and my Django Rest API backend on port 8000 open (private) are running: And my NextJS frontend uses this Rest API call with "localhost" as shown below to get the list of objects which contain "product names", "prices" and "images": http://localhost:8000/api And, this is the errors: 3000-gitpodio-templatetypescr-tqzkjl97w1d.ws-us33.gitpod.io/:987 GET http://localhost:8000/media/images/paid.png net::ERR_CONNECTION_REFUSED 3000-gitpodio-templatetypescr-tqzkjl97w1d.ws-us33.gitpod.io/:987 GET http://localhost:8000/media/images/size.png net::ERR_CONNECTION_REFUSED 3000-gitpodio-templatetypescr-tqzkjl97w1d.ws-us33.gitpod.io/:987 GET http://localhost:8000/media/images/download.jpg net::ERR_CONNECTION_REFUSED 3000-gitpodio-templatetypescr-tqzkjl97w1d.ws-us33.gitpod.io/:987 GET http://localhost:8000/media/images/02173_l.jpg net::ERR_CONNECTION_REFUSED Actually, I solved these errors above by using this Rest API call with my Gitpod domain as shown below to get the list of objects: https://8000-gitpodio-templatetypescr-tqzkjl97w1d.ws-us33.gitpod.io/api But other error occurs as shown below: Server Error FetchError: invalid json response … -
Django 2.0 migration breaks django-autocomplete-light unit test with TypeError
I am trying to migrate to Django 2.0 from 1.11 but some unit tests related to django-autocomplete-light (3.5.1) have started failing with a TypeError after calling self.client.get() from TestCase class. (__init__() takes 1 positional argument but 2 were given) Some suggestions I found stated that missing as_view() in the URL view could be the issue but it is already there. I also changed the MIDDLEWARE_CLASSES variable to MIDDLEWARE in the settings. test.py from django.urls import reverse from django.test import TestCase from django.contrib.auth.models import User class AutocompleteTestCase(TestCase): def setUp(self): self.admin_cred = { 'username': 'test', 'password': 'test', } self.user = User.objects.create_superuser('test', 'test@test.com', self.admin_cred['password']) def query_autocomplete_view(self, url_name, query=None): data = {} if query: data['q'] = query self.client.force_login(self.user) response_json = self.client.get(reverse(url_name), data=data).json() return response_json.get('results') Error Traceback Traceback (most recent call last): File "/home/circleci/project/test/apps/dataadmin/tests/test_autocomplete_views.py", line 131, in test_dataadmin_field_autocomplete results = self.query_autocomplete_view('admin:dataadmin_autocomplete_dataadminfield', query='test') File "/home/circleci/project/dataadmin/common/test_utils.py", line 23, in query_autocomplete_view response_json = self.client.get(reverse(url_name), data=data).json() File "/home/circleci/project/venv/lib/python3.6/site-packages/django/test/client.py", line 517, in get response = super().get(path, data=data, secure=secure, **extra) File "/home/circleci/project/venv/lib/python3.6/site-packages/django/test/client.py", line 332, in get return self.generic('GET', path, secure=secure, **r) File "/home/circleci/project/venv/lib/python3.6/site-packages/django/test/client.py", line 404, in generic return self.request(**r) File "/home/circleci/project/venv/lib/python3.6/site-packages/django/test/client.py", line 467, in request response = self.handler(environ) File "/home/circleci/project/venv/lib/python3.6/site-packages/django/test/client.py", line 125, in __call__ self.load_middleware() File "/home/circleci/project/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 39, in load_middleware … -
Django how to add specific query results to model when appending to database
I have a model that holds "title", "area", "price" and "price2". I have a database table that holds "area", and "price2". First I create model object. Then I want to go to database, get average "price2" for the "area" of the model, and then save that into "price2" of the model. How can I accomplish this? Thank you. -
Django postgres full text search error "Unsupported lookup 'search' for CharField"
All similar problems have been solved by adding django.contrib.postgres to INSTALLED_APPS in settings.py, which is also all the docs mention on how to use the lookup. I've already done this and the lookup still isn't working, despite whether I use __search or search= for the filter. Any ideas? Do I need to register the lookup in my model myself? settings.py: INSTALLED_APPS = [ ... 'django.contrib.postgres', # my_project 'my_project.apps.appname', 'my_project.apps.appname', ... error line: x = y.objects.filter(description__search="example") -
Select specific option from dropdown menu DJANGO
I have a page that lists all the items from a table named Stocks for each row there's a clickable ORDER button that leads users to another page where they can enter all their details as well as select what item and how much they wanna buy which would then save all of that data to a table named Orders. This orders table is linked with the Stocks table like this: class Order(models.Model): name = models.CharField(max_length=50, blank=True, null=True) quantity = models.IntegerField(default='0', blank=False, null=True) order_item = models.ForeignKey(Stock, on_delete=models.CASCADE, blank=True) address = models.CharField(max_length=50, blank=True, null=True) city = models.CharField(max_length=50, blank=True, null=True) Depending on what item they clicked the order button for I wanted to automatically select the corressponding item from the dropdown menu on the next page so that they won't have to. def create_order(request, pk): queryset = Stock.objects.get(id=pk) form = CreateOrderForm(request.POST or None, initial={'order_item':queryset.item_name}) if form.is_valid(): form.save() context = { 'form':form } return render(request, 'add_items.html', context) I tried doing this by using the intitial command but for some reason it just won't change from the default blank option. Here's my forms.py just in case class CreateOrderForm(forms.ModelForm): class Meta: model = Order fields = ['name','quantity','order_item','address','city'] -
Cannot import name 'force_text' from partially initialized module 'django.utils.encoding'
My project was working perfectly fine until I tried installing security for Bruteforce for the login system by installing packages like Django-defender & BruteBuster. However, suddenly I was prompted with this error and cannot seem to find the reason why. There are many other similar questions where the answer would say to change the force_text to force_str within the graphene_django folder in my ENV. Therefore, I do not know where to insert or change the text to str as I do not have a graphene_django folder at all. Furthermore, I have checked other Django projects within my device which also shows a similar error even though I have barely done anything. For more description here is the full error: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\DELL7390\AppData\Local\Programs\Python\Python38-32\lib\site- packages\django\core\management\__init__.py", line 425, in execute_from_command_line utility.execute() File "C:\Users\DELL7390\AppData\Local\Programs\Python\Python38-32\lib\site- packages\django\core\management\__init__.py", line 419, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\DELL7390\AppData\Local\Programs\Python\Python38-32\lib\site- packages\django\core\management\__init__.py", line 263, in fetch_command klass = load_command_class(app_name, subcommand) File "C:\Users\DELL7390\AppData\Local\Programs\Python\Python38-32\lib\site- packages\django\core\management\__init__.py", line 39, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "C:\Users\DELL7390\AppData\Local\Programs\Python\Python38- 32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line … -
How to use a model inside django settings?
I need to use one of my models to define Django settings variables. Meaning, the django variables will be dinamically defined by what's on the database. When I use a function that uses one of my models: from util.auth_utils import get_app_auth auth = get_app_auth() It throws an error: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. If I try to use this code inside the settings.py: import django django.setup() Also throws an error: RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. Besides that, I tryed to move the django.setup() part to after the INSTALLED_APPS, but then it wont load settings correctly. Any clues? -
What's the difference beetwen django database engines?
In setting.py file I can that sqlite3 is set by default as db engine. In the docs i read that I can change it to other engines like PostgreSQL MariaDB or MySQL. But here is my question. What for ? Are these engines better/faster than default sqlite3 ? Is there any point of learning how to change database for other than default ? -
Get Value for Specific Select Option in Django Template
I am trying to get the value for a select option in my django template. I can iterate through an object like this: <select id="id_name" name="name"> {% for x, y in form.fields.name.choices %} <option value="{{ x }}">{{ y }}</option> {% endfor %} </select> but is there any way to get a specific value eg; form.fields.name.choices.2? without looping? Thanks! -
Django and Pandas - Create an object from a Foreying Key field
I am trying to create objects importing data from an excel with pandas, than creating objects with django. But i am geting this error message: Asset matching query does not exist. My Models class Asset(models.Model): ticker = models.CharField(max_length=255, unique=True) class Transaction(models.Model): id = models.AutoField(primary_key=True) OrderChoices = ( ('Buy', 'Buy'), ('Sell', 'Sell'), ) date = models.DateField(("Date"), default=date.today) order = models.CharField(max_length = 8, choices = OrderChoices) asset = models.ForeignKey(Asset, on_delete=models.CASCADE, default=1) shares_amount = models.FloatField() share_cost = models.FloatField() And here is my updater file code: class Command(BaseCommand): def handle(self, *args, **options): excel_file = "orders.xlsx" df_2 = pd.read_excel(excel_file) df_2 = df_2[['Date(UTC)','Pair', 'Type', 'Order Amount', 'AvgTrading Price']] df_2.columns = ['date', 'asset', 'order', 'shares_amount','share_cost'] df_2['date'] = df_2['date'].str[:9] df_2['asset'] = df_2['asset'].str.replace('USDT', '') df_2['order'] = df_2['order'].str.replace('BUY', 'Buy') print(df_2['asset']) for index, row in df_2.iterrows(): try: Transaction.objects.create( date = datetime.date.today(), order = df_2['order'] , asset = Asset.objects.get(ticker = df_2['asset']), shares_amount = df_2['shares_amount'], share_cost_brl = df_2['share_cost'], ) except Exception as e: print(f' Key Exception - {e}') pass When i try to print(df_2['asset']), i get as result a list with id(from pandas index) and ticker -
How can we overrider serializer.save() method in django rest framework?
I have update functional view. And i'm update profile instance with serializer.save() method. I want to override that default save method. and want to save that in to profile managers file. Can you tell me how can i do that ? functional view where i'm using that save method. if request.method=="PUT": request.data["update_time"] = timezone.now() serializer = UserProfileSerializer(profile, data=request.data,partial=True) if serializer.is_valid(): serializer.save() trying to move that in managers : def save_me(self,obj): obj = obj.save() return obj -
How to remove username and password2 fields from form errors
I have a problem with these fields in their output to the html template. I need to output only error text without field data in the Messages function. error on website Create messages in views.py messages.error(request, form.errors) -
Django HttpResponseRedirect sends request but doesn't actually render?
I am attempting to redirect a user to http://127.0.0.1:8000/register/Pro/success after a successful registration. This is my URLs code: from accounts import views from django.urls import path,re_path from django.contrib.auth import views as auth_views urlpatterns = [ # path('signup',views.signup_user,name='signup'), path('login', views.login_user, name="login"), path('logout', views.logout_user,name='custom_logout'), re_path(r'^password_reset/$', auth_views.PasswordResetView.as_view(), name='password_reset'), re_path(r'^password-reset/email-sent/$', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('password-reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), re_path(r'^password-reset/complete/$', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), path('register/<str:plan>/', views.register, name="register"), path('register/<str:plan>/success', views.success, name="redirect") ] And this is what I am attempting to redirect it with: return HttpResponseRedirect(f'/register/{plan}/success') This sends a get request, but it only shows up in the networks tab of developer tools, it doesn't actually render in the same way as if you went to the URL manually. How would I achieve this? -
Overriding a Django core class without modifying its import path
Is there a way to override a core Django class without modifying its import path? For example, the class BaseCommand is imported by django.core.management.base. I want to override/modify BaseCommand and still be able to import it from the same path. Is that possible? -
django Rest-framework serialize two tables
i have table "Books" with some fields, and i have table "Prices", each customer have self price, i don't know how get price for definitely client, how i must configure serializer? please, help me, class Book(models.Model): title = models.CharField('Заголовок', max_length=250) code = models.CharField('Код', primary_key=True, max_length=10) isbn = models.CharField('ISBN', max_length=18, null=True, blank=True) ean13 = models.CharField('EAN-13', max_length=13, null=True, blank=True) author = models.ForeignKey(Author, on_delete=models.SET_NULL, null=True, blank=True, verbose_name='Автор') class PricesName(models.Model): name = models.CharField('Вид цены', max_length=20) def __str__(self): return self.name class Price(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE) PricesName = models.ForeignKey(PricesName, on_delete=models.CASCADE) price = models.FloatField() def __str__(self): return self.book.title+" "+self.PricesName.name ######### Serializers.py ########################## class BookSerializer(serializers.ModelSerializer): author = serializers.StringRelatedField() class Meta: model = Book fields = #'__all__' #### API.py #### class BookViewSet(viewsets.ModelViewSet): queryset = Book.objects.all() permission_classes = [ permissions.AllowAny ] serializer_class = BookSerializer filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter) filter_fields = ('title', 'author') search_fields = ('title', 'author') pagination_class = StandardResultsSetPagination -
DJANGO POSTGRES matching query does not exist
Hi i have a seller model that is related one to one field with user in DJANGO. Seller can create a "deal" and to become seller you first have to create a normal account as a user. I dont have any idea how to take to the view deals that are from the specyfic seller MY views. @user_passes_test(is_seller) def seller_page(request): if request.method == "GET": user = request.user _seller = Seller.objects.get(user_id=user) # TODO: doesnt work deals = Deal.objects.get(seller_id=_seller) form = forms.DealModelForm context = {'deals': deals, 'form': form} return render(request, 'seller_page.html', context) My models class Seller(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=255) address = models.CharField(max_length=255) city = models.CharField(max_length=255) post_code = models.CharField(max_length=6) phone = models.CharField(max_length=12) email = models.CharField(max_length=255) bank_account = models.CharField(max_length=255) nip = models.CharField(max_length=255) is_seller_active = models.BooleanField(default=False) sells = models.IntegerField(default=0) class Deal(models.Model): seller = models.ForeignKey(Seller, on_delete=models.CASCADE) title = models.CharField(max_length=255) description = models.TextField() image = models.ImageField() is_deal_on = models.BooleanField(default=True) sell_price = models.DecimalField(default=0, decimal_places=2, max_digits=6, help_text='Cena sprzedaży') origin_price = models.DecimalField(default=0, decimal_places=2, max_digits=6, help_text='Oryginalna cena', blank=True, null=True) time_valid = models.IntegerField(default=12) # ilość miesięcy ile warty jest deal unique_code = models.CharField(max_length=60, null=True, blank=True) quantity = models.IntegerField(default=0) province = models.IntegerField(choices=PROVINCES) ERROR : _seller = Seller.objects.get(user_id=user) -
Create a instance of another model on the basis of a value provided on the request of a view
Problem: I want to create a new instance of the DogAcknowledgement inside the serializer whenever a dog instance is created on the basis of the provided value(which can be true, false, or null) provided on the request. what I have tried: Create a custom_field on the serializer which will hold the value of the provided value. when the post-call is made for the dog on the to_internal_value I would add logic to create a dog_acknowledgement. if certain_value is not None: dog_ack, _ = DogAcknowledgement.objects.get_or_create(dog=???(object)) else: something But how do I access the dog object that is being created in the post request? when I send the object itself I get an error. -
How do I access a server's file manager using cwp simple terminal?
I am currently new to using CWP panel and understand it provides a user friendly file manager. However, I am trying to configure the Apache server to run Django and need to download mod_wsgi package on the server.