Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't import file in django
I am learning Django and I am trying to import the "views" file. this doesn't work-> "from . import views". It gives this error->ImportError: attempted relative import with no known parent package. When I use "import views" it gives " Django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings." this error. All the files are in the same place. -
Django admin custom filter by ManyToMany through model
I need to create a filter in Django admin by a Through Model. class Location(models.Model): created_at = models.DateTimeField(editable=False, auto_now_add=True) lat = models.DecimalField(max_digits=13, decimal_places=10, default=None) lon = models.DecimalField(max_digits=13, decimal_places=10, default=None) class Place(models.Model): created_at = models.DateTimeField(editable=False, auto_now_add=True) lat = models.DecimalField(max_digits=13, decimal_places=10, default=None) lon = models.DecimalField(max_digits=13, decimal_places=10, default=None) ways = models.ManyToManyField(location.Location, through='Way') class Way(models.Model): created_at = models.DateTimeField(editable=False, auto_now_add=True) place = models.ForeignKey(Place, on_delete=models.PROTECT,) location = models.ForeignKey(Location, on_delete=models.PROTECT,) drive_distance = models.IntegerField(null=True, default=None,) Way model contains a drive_distance between models Place and Location. In the Django admin list display, I want to create a custom filter to filter out places, which has more that 0 locations where drive distance <= 100. Say, just a simple yes/no filter. How to do it? I can create a custom filter for the model fields, for a model relation, but I can't filter by a through model values. I use Django 3.1. -
How to check a request.user with raw sql in Django
I want to get data about a Student which is currently logged in Here is my code: def profile(request): cursor = connection.cursor() a = request.user.id cursor.execute("SELECT * from Student WHERE ID = a ") data = dictfetchall(cursor) return render(request, 'personal.html', {'data': data}) in table Student attribute ID is connected with attribute id in tha table auth_user Is it even possible to check? I know that with ORM it is easy to do, but I need to use raw sql -
How to increment Django CharField (containing an integer) using Django ORM?
Say I have a model as : class model(models.Model): remark=models.CharField(max_length=25) count=models.CharField(max_length=5) The entity having remark="counter" has count="34". I wish to retrieve entity (having remark="counter") and change its count to "35", i.e. cast to integer, increment it by 1, cast back to string, update. Is there any way I can do this using only Django ORM query(using F or something else) and no Python. -
Django Date Field, where you can go to the next/previous day
In my Django Project, I want to have a field, where the current date is showed. I know how to do that, but I also want two buttons, where you can go to the next day or the previous day. I dont want a Date Picker, where you have to use a calender to pick the date. Can you help me with that? Thanks :) -
Django 3.2 -makemigrations-no changes detected
I've seen all other answers but still keep getting this issue can someone please help -
Reverse for 'category' with arguments '('',)' not found. 1 pattern(s) tried: ['category/(?P<cats>[^/]+)/$']
Tell me please when I add a | slugify in the home.html I get this error if I don't add everything works fine, but also when I enter a category, posts are not displayed in some categories, writes that there is no post in this category, there are also critical errors constantly pop out, perhaps there is a bug somewhere or not the correct code, I still did not find the reason, I solve one second, an error pops out models.py from django.db import models from django.contrib.auth.models import User from django.urls import reverse #from datetime import datetime, date from django.utils import timezone class Category(models.Model): name=models.CharField(max_length=255) def __str__(self): return self.name def get_absolute_url(self): return reverse('home') class Post(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() post_date = models.DateTimeField(auto_now_add=True) category = models.CharField(max_length=200, default='разные') def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): return reverse('article_detail', args=[str(self.id)]) views.py from django.shortcuts import render from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .models import Post, Category from .forms import PostForm, EditForm from django.urls import reverse_lazy #def home(request): # return render(request, 'home.html', {}) class HomeView(ListView): model = Post cats = Category.objects.all() template_name = 'home.html' ordering = ['-post_date'] def get_context_data(self, *args, **kwargs): cat_menu … -
Assign a user to a free trial plan on sign up in django
I've implemented subscription payments to my django app using dj-paddle. The only problem is if a user wants to start a free trial, they have to enter their credit card details.There's no option to disable credit card requirement on paddle. I want to handle free trials outside of paddle locally so users don't have to enter their credit card to try out the app. How do i assign a custom role to a user automatically after registering for example 'free_trial' that switches to another custom role 'trial_expired' after 7 days? This way i can just call the method in my templates e.g {% if user.free_trial %} "Access to app" {% else %} "Your trial has expired" {% endif %} user views.py def register(request): if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created {username}!') new_user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password1'], ) login(request, new_user) return HttpResponseRedirect('/dashboard/') else: form = CustomUserCreationForm() return render(request, 'users/register.html', {'form': form}) This is how i've currently implemented dj-paddle to restrict access to non subscribers in my app. User model class CustomUser(AbstractUser): def has_subscription(self): return self.subscriptions.filter(Q(status='active') | Q(status='trialing')).exists() My templates {% if user.has_subscription %} "Access to app" {% else %} "Payment … -
Apparent Bug with Python Usign Selenium : issue with PosixPath
Good evening, I have started a django project, using python 3.7 and Django 3.1.5 When I launch my unitary tests, they run perfectly. When running selenium, this is what I get: File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/wsgiref/handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "/Users/fabricejaouen/Documents/OC_Parcours_Python/advocacy_project/venv/lib/python3.7/site-packages/django/test/testcases.py", line 1322, in __call__ return super().__call__(environ, start_response) File "/Users/fabricejaouen/Documents/OC_Parcours_Python/advocacy_project/venv/lib/python3.7/site-packages/django/core/handlers/wsgi.py", line 133, in __call__ response = self.get_response(request) File "/Users/fabricejaouen/Documents/OC_Parcours_Python/advocacy_project/venv/lib/python3.7/site-packages/django/test/testcases.py", line 1305, in get_response return self.serve(request) File "/Users/fabricejaouen/Documents/OC_Parcours_Python/advocacy_project/venv/lib/python3.7/site-packages/django/test/testcases.py", line 1317, in serve return serve(request, final_rel_path, document_root=self.get_base_dir()) File "/Users/fabricejaouen/Documents/OC_Parcours_Python/advocacy_project/venv/lib/python3.7/site-packages/django/views/static.py", line 36, in serve fullpath = Path(safe_join(document_root, path)) File "/Users/fabricejaouen/Documents/OC_Parcours_Python/advocacy_project/venv/lib/python3.7/site-packages/django/utils/_os.py", line 17, in safe_join final_path = abspath(join(base, *paths)) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/posixpath.py", line 80, in join a = os.fspath(a) TypeError: expected str, bytes or os.PathLike object, not NoneType The strange part of it is: no Error linked to my project is raised, the Selenium tests pass perfectly and here is my Selenium setup: from django.test import LiveServerTestCase from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver import Firefox import os class CustomUserTest(LiveServerTestCase): fixtures = ['users.json'] @classmethod def setUpClass(cls): super().setUpClass() cls.browser = Firefox() cls.browser.implicitly_wait(10) @classmethod def tearDownClass(cls): cls.browser.quit() super().tearDownClass() def test_plaid_10_authenticate_on_the_website(self): """ The user wants to authenticate in order to have access to the functionalities of the website """ self.browser.get(os.path.join(self.live_server_url, ''))``` Therefore, I can go on with … -
could not connect to server: No such file or directory. PostgreSQL--> CloudSQL connection Error
Is the server running locally and accepting connections on Unix domain socket "/cloudsql/connection-name/.s.PGSQL.5431"? Whenever i deploy and login for superuser, i recieve this error. My app.yaml: runtime: python env: flex entrypoint: gunicorn -b :$PORT core.wsgi automatic_scaling: min_num_instances: 1 max_num_instances: 8 cool_down_period_sec: 180 cpu_utilization: target_utilization: 0.5 target_concurrent_requests: 100 beta_settings: cloud_sql_instances: <connection-name> runtime_config: python_version: 3 My Settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'HOST': config('DB_HOST'), 'PORT': config('DB_PORT'), 'NAME': config('DB_NAME'), 'USER': config('DB_USER'), 'PASSWORD': config('DB_PASSWORD') } } DATABASES['default']['HOST'] = '/cloudsql/<connection-name>' if os.getenv('GAE_INSTANCE'): pass else: DATABASES['default']['HOST'] = '127.0.0.1' STATIC_URL = config('STATIC_URL') STATIC_ROOT='static' AUTH_USER_MODEL = 'users.NewUser' MEDIA_URL='/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') I Run cloud_sql_proxy.exe file as well on port 5431 cloud_sql_proxy.exe -instances="<connection-name>"=tcp:5431 Deployment is successful but database connection is a problem. What is the solution for that. -
Django - Inserting Model field value into JavaScript
Im using the google maps api to show the users location. In order for it to work, it needs lat and long values. The lat and long values for the user are stored in a model which I then access in the html using hidden field since I dont want the user to see this information: <input type="hidden" id="hidden_lat" name="lat" value="{{object.author.profile.detail_lat}}"> Then in the JavaScript I use the following to get the lat/long value and pass it into the google api as a variable. var lat = +document.getElementById('hidden_lat').value Is this the best approach to achieve this or is there a better way. April 10, 2021 -
Fail with Django migrations when switching to MySQL
I might have hit something beyond my comprehension. Background I have dev and prod Django environments. Both of them were on SQLite, then I successfully migrated prod to server-based MySQL. I made a few more changes in my code in dev and decided to migrate it to MySQL as well (created local MySQL server) The problem I run migrations and the error I get - 'there is no table X in database'. I use 'show tables' to see what tables are available and it's not there indeed. This table was introduced in migration_0043. Now I'm much further - migration_0053, so rolling back does not seem like an option. Is there a way to either run that specific migration (I don't understand why it did not run automatically) or safely clean migrations and have a new 'initial' one? The complications are: 1) I have valuable data that I don't want to lose; 2) I will need to bring dev and prod back in sync after it. -
Validation Error not showing in django template
Everything works except for the fact that when there is invalid login, the validation error does not show. Any idea why this is so? views.py class LoginView(FormView): form_class = AccountAuthenticationForm def form_valid(self, form): email = self.request.POST['email'] password = self.request.POST['password'] user = authenticate(email=email, password=password) auth_login(self.request, user) return redirect("HomeFeed:main") if not authenticate(email=email, password=password): raise forms.ValidationError("Invalid login") forms.py class AccountAuthenticationForm(forms.ModelForm): password = forms.CharField(label='Password', widget=forms.PasswordInput) class Meta: model = Account fields = ('email', 'password') def clean(self): if self.is_valid(): email = self.cleaned_data['email'] password = self.cleaned_data['password'] else: raise forms.ValidationError("Invalid login") -
How can I render a highcharts solidgauge with Django?
I would like to display a highcharts solidgauge (https://www.highcharts.com/demo/gauge-solid). For my little app I use Django and Python3.8. But most examples that I found work only for Angular. tldr: I get a red error message from highcharts (No. 17), which states that the requested series type does not exist. The long story: As I did not know any better way I downloaded four js files (https://code.highcharts.com/modules/solid-gauge.js, https://code.highcharts.com/modules/solid-gauge.src.js, https://code.highcharts.com/highcharts-more.js, and https://code.highcharts.com/highcharts-more.src.js). I put them in my Django's static folder and ran manage.py collectstatic. In my views.py I just tried to replicate the example from the highcharts page, but I do not get it to render. The code looks like this. def landingpage(request): chart = { 'chart': { 'type':'solidgauge', }, 'title': {'text':'Example gauge'}, 'pane': { 'center': ['50%', '85%'], 'size': '140%', 'startangle': -90, 'endangle':90, 'background': { 'backgroundcolor': 'Highcharts.defaultOptions.legend.backgroundColor || \'#EE\'', 'innerRadius': '60%', 'outerRadius': '100%', 'shape': 'arc', } }, 'exporting': {'enabled': False}, 'tooltip': {'enabled': True}, 'yAxis':{'stops': [ [0.1, '#55BF3B'], # green [0.5, '#DDDF0D'], # yellow [0.9, '#DF5353'], # red ], 'min':0, 'max':200, 'lineWidth': 0, 'tickWidth': 0, 'minorTickInterval': 'null', 'tickAmount': 2, 'title': { 'y':-70, 'text': 'Speed' }, 'labels': { 'y':16 } }, 'credits': { 'enabled': False }, 'plotOptions': { 'solidgauge': { 'dataLabels': { 'useHTML': True, … -
Why does Django with sqlite not insert unique constraint into the database schema?
I am starting to use Django with sqlite and I want to impose a simple unique constraint on the combination of two fields in a table. To this end, I use Django's UniqueConstraint class. However, to my surprise, the constraint is not inserted in to the tables schema in the database. My Django model looks like follows: from django.db import models class Fruit(models.Model): fruit_id = models.IntegerField(primary_key=True) fruit_type = models.CharField(max_length=64, default='', blank=True, null=False) fruit_name = models.CharField(max_length=128, default='', blank=True, null=False) class Meta: models.UniqueConstraint(fields=['fruit_type', 'fruit_name'], name='unique_fruit_type_name') db_table = 'fruit' After migration, I check the schema in the database by executing: select sql from sqlite_master where type='table'; The result, for the table in question, reads: CREATE TABLE "fruit" ("fruit_id" integer NOT NULL PRIMARY KEY"fruit_type" varchar(64) NOT NULL), "fruit_name" varchar(128) NOT NULL I was expecting to get: CREATE TABLE "fruit" ("fruit_id" integer NOT NULL PRIMARY KEY"fruit_type" varchar(64) NOT NULL), "fruit_name" varchar(128) NOT NULL, UNIQUE (fruit_type, fruit_name) Where did the UNIQUE-clause go? Is it not supposed to be in the schema? -
Django Xero OAuth2
I'm really struggling with applying the xero python SDK examples as they are for flask, and I'm working in Django. Having read the xero pages there's no planned django tutorial. Has anyone here already solved how to apply the settings in a multi tenant app ? -
autocomplete_fields in django admin doesn't work well when the name contain a pipeline(|) in it
i have three simple models : models.py from django.db import models class Name(models.Model): name = models.CharField(max_length=150) def __str__(self): return self.name class Last(models.Model): First = models.ForeignKey(Name, on_delete=models.CASCADE) last = models.CharField(max_length=100) def __str__(self): return '{0} | {1}'.format(self.First, self.last) class Id_cart(models.Model): full = models.ForeignKey(Last, on_delete=models.CASCADE) and as you can see the str method in class "Last" returns a string with a | . and in the admin.py i want to use autocomplete_fields in the "Id_cart" model and for "full" field: admin.py from django.contrib import admin class FullAdmin(autocomplete_all.ModelAdmin): list_display = ['full'] search_fields = ['full'] autocomplete_fields = ['full'] admin.site.register(Id_cart,FullAdmin) But still in the admin page the autocomplete_fields doesn't work correctly and give this message on the search area: The results could not be loaded -
Correct way to use create_or_get with DRF
I have the following models. class Word(models.Model): """Word object""" word = models.CharField(max_length=255, unique=True) def __str__(self): return self.word class Category(models.Model): """Category object""" category = models.CharField(max_length=255, unique=True) def __str__(self): return self.category class Group(models.Model): """Group object""" user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) group = models.CharField(max_length=255) categories = models.ManyToManyField("Category") words = models.ManyToManyField("Word") def __str__(self): return self.group class Puzzle(models.Model): """Puzzle object""" user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) puzzle = models.CharField(max_length=255) groups = models.ManyToManyField("Group") def __str__(self): return self.puzzle The following views class WordViewSet(viewsets.ModelViewSet): """Manage words in the database""" search_fields = ["word"] filter_backends = (filters.SearchFilter,) queryset = Word.objects.all() serializer_class = serializers.WordSerializer http_method_names = ["get", "post"] class CategoryViewSet(viewsets.ModelViewSet): """Manage categories in the database""" search_fields = ["category"] filter_backends = (filters.SearchFilter,) queryset = Category.objects.all() serializer_class = serializers.CategorySerializer http_method_names = ["get", "post"] class GroupViewSet(viewsets.ModelViewSet): """Manage groups in the database""" queryset = Group.objects.all() serializer_class = serializers.GroupSerializer permission_classes = [IsOwner, ] def get_serializer_class(self): """Return appropriate serializer class""" if self.action == "retrieve": return serializers.GroupDetailSerializer return self.serializer_class def perform_create(self, serializer): serializer.save(user=self.request.user) class PuzzleViewSet(viewsets.ModelViewSet): """Manage puzzles in the database""" queryset = Puzzle.objects.all() serializer_class = serializers.PuzzleSerializer permission_classes = [IsOwner, ] def get_queryset(self): queryset = Puzzle.objects.all() user = self.request.query_params.get("user") if user is not None: queryset = Puzzle.objects.filter(user=user) return queryset def get_serializer_class(self): """Return appropriate serializer class""" if self.action == … -
Django query for model with a single DateField used for tracking state changes
I have searched all over StackOverflow / Reddit / etc, but can't seem to find anything like this. Assuming we have the following model (purposely simplified): class X(models.Model): related_object = models.ForeignKey(Y) start_date = models.DateField(unique=True) is_rented = models.BooleanField() Where model X is tracking state changes of an instance of model Y. It could be tracking something like the state of cars at a car rental agency that may be rented out. A new instance of the model is created each time the state of each car changes. The resulting objects might look something like this: {"id" : 1, "related_object" : 2, "start_date" : "2021-03-03", "is_rented" : False}, {"id" : 2, "related_object" : 2, "start_date" : "2021-03-06", "is_rented" : False}, {"id" : 3, "related_object" : 2, "start_date" : "2021-03-10", "is_rented" : True}, {"id" : 4, "related_object" : 2, "start_date" : "2021-03-15", "is_rented" : False}, {"id" : 5, "related_object" : 2, "start_date" : "2021-03-16", "is_rented" : True}, {"id" : 6, "related_object" : 4, "start_date" : "2021-03-16", "is_rented" : False}, {"id" : 7, "related_object" : 2, "start_date" : "2021-03-17", "is_rented" : False}, {"id" : 8, "related_object" : 4, "start_date" : "2021-03-22", "is_rented" : True}, I want to be able to perform the following queries: … -
Updating DateTimeField in Django
I have a DateTimeField() in my models.py. What I am trying to do is to update it, along with some other values in the model. Everything else updates fine apart from my DateTimeField(). the error i get says that AttributeError: module 'datetime' has no attribute 'now' anyone see where I am going wrong with m update? sModel.objects.all().update(sPasses=pass_number_for_graph, sFails=fail_number_for_graph, sNds=p_number_for_graph, sTimestamp=datetime.now()) -
React DRF Select All the Options in the ManytoMany field by default
I am working on a project with React and DRF and currently have my models like this: class Author(models.Model): author_name = models.Charfield(max_length = 15) class Books(models.Model): book_name = models.CharField(max_length = 15) authors = models.ManytoManyField(Author) I have my models setup correctly and am able to send data to backend correctly. However, what I need is - all the options in the ManytoManyfield to be selected by default. Currently, the option is displayed in the ManytoManyfield but it is not selected. I am not sure how to go about it. I have gone through this question but am still not clear on this. Please guide me on how this is done. Thanks for your time in advance. -
Why in Django Rest Framework remove objects is showing on list?
After removing object is is still in response data. /api/premises/premises/4 returns { "detail": "Not found." } but /api/premises/premises/ returns [ { "id": 1, "image": "/product/lb-gallery-main.jpg", "owner": "owner@lebernardin.com", "name": "Le Bernardin", "description": "Le Bernardin to francuska restauracja z owocami morza na Manhattanie w Nowym Jorku. Gilbert Le Coze i jego siostra Maguy Le Coze otworzyli restaurację w Paryżu w 1972 roku, pod nazwą Les Moines de St. Bernardin.", "country": "Poland", "city": "Gdynia", "postcode": "80-209", "address": "Starowiejska 1", "tags": [ 1, 2 ] }, { "id": 4, "image": "naws.com/product/Union-Oksford.jpg", "owner": "admin@admin.com", "name": "dadad", "description": "dada", "country": "dada", "city": "dada", "postcode": "dad", "address": "dadadada", "tags": [] }, { "id": 2, "image": "196290008887877_5616210528952631689_n.jpg", "owner": "admin@admin.com", "name": "Sebastian Wrzałek", "description": "adadada", "country": "dadad", "city": "adada", "postcode": "dada", "address": "dadadadaddd", "tags": [] } ] Weird that it is not displayed on Django Admin. Also I am using Docker, after restart it is updating list and not showing deleted item. When I checked Database table directly data is correntc meaning item is removed correctly. I am thinking where it comes from and why it is cached somehow? docker-compose.yml version: "3" services: redis: image: redis command: redis-server ports: - "6379:6397" app: build: context: . ports: - "8000:8000" volumes: … -
Runing Django tests with Jenkinsfile (with docker)
i have a Django app running inside Docker (also Postgres, Nginx and Jenkins are inside docker), and i want to run tests by creating a Pipeline The problem is that every time i run it with python app/manage.py test (since the jenkisnfile is outside the project folder named "app") ,it just run an empty test.py file (so it return 0 test succesfull) even though i have actual tests. if i ran the test directly from the terminal it work $ docker-compose run web python manage.py test Creating proj1_web_run ... done Creating test database for alias 'default'... System check identified no issues (0 silenced). .......... ---------------------------------------------------------------------- Ran 10 tests in 0.229s OK Destroying test database for alias 'default'.. here is Jenkinsfile pipeline { agent { docker { image 'python:3.9' } } stages { stage('Build') { steps { sh 'pip install -r requirements.txt' } } stage('Test') { steps { sh 'python app/manage.py test' } } stage('Deploy') { steps { sh 'echo not yet...' } } } } message in Jenkins console output + python app/manage.py test System check identified no issues (0 silenced). ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK thank you very much for your help -
Cant get datetime formatting right
I don't know why but I always seem to have trouble formatting dates with strptime. I really can't see where I am going wrong here but this is the error I got... time data '2021-04-10 18:00:00' does not match format '%Y-%m-%d %H:%M:%S.' I appreciate any help you can give. weatherDate = datetime.datetime.strptime(date, '%Y-%m-%d %H:%M:%S') -
How to space bootstrap 5 cards?
So, I have a few cards, and I want them to be on the same line, so I used rows and cols. This works. But there is another problem. The problem is, they seem to squished together. I try to use margin-left or margin-right or all those spacing stuff, but none of them work. So could someone help me space these out. I am using a template for loop in django for this. <div class="row"> {% for jax in u_jaxes %} <div class="col-sm-4"> <div id="card2" class="card"> <div class="card-body"> <a href="{% url 'edit_jax' jax.title %}">{{ jax.title }}</a><br><br> <img src="https://cdn1.iconfinder.com/data/icons/logotypes/32/badge-html-5-128.png" alt="Badge, html, html5, achievement, award, reward, trophy"/ height="17" width="17"> HTML, CSS, JS <span style="float:right"> {{ jax.date_created|timesince }} ago </span> <a href="{% url 'edit_jax' jax.title %}" class="stretched-link"></a> </div> </div> </div> {% endfor %} </div> if anyone needs anything else like what css code I'm using and all, please let me know. Thanks!