Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Iterating over table data in Django
I am having issues when iterating over a table data. What I need to achieve is to have a table where I can display the bookings of a reservation system I am developing. I explain what I am trying to achieve: As in the image below, I want to display the reservations based on their booking time. Basically I want to assign a colspan to each td based on the value of the reservation times. The problem I am actually facing is that, when I try to iterate over the logic to recreate this table, I am having an issue that only some cells are displayed. I post an image of my results: Now, I post some code, so maybe someone can understand what I am doing wrong, because I couldn't find the right way of fixing it. models.py class AirportTime(models.Model): aerodrome = models.ForeignKey(Aerodrome, on_delete=models.CASCADE, blank=True, null=True) opening_time = models.TimeField() closing_time = models.TimeField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return str(self.opening_time) + ' ' + str(self.closing_time) class Booking(models.Model): aircraft = models.ForeignKey(Aircraft, on_delete=models.CASCADE) student = models.ForeignKey( Student, on_delete=models.CASCADE, blank=True, null=True) instructor = models.ForeignKey( Instructor, on_delete=models.CASCADE, blank=True, null=True) date = models.DateField() start_time = models.TimeField() end_time = models.TimeField() created_at = models.DateTimeField(auto_now_add=True) … -
Simple use Swagger with Django
I'm a c# developer who recently switched to python/django (company's choice not mine). I'm trying to use swagger/openAPI to document endpoints but I can't find any way to do so without significant effort. Currently most of the out of the box frameworks I've found require me to use the same object in the request and response or need extensive amount of code to specify the schema. I'm looking for something that will allow me to do something like in c# where at most I just need to add an attribute to specify request/response type. Does python not have this? If it doesn't is there a reason for that? Based on my rudimentary knowledge of python I don't understand why this would be so complicated. Thanks -
Django - Error when viewing HTML template with autogenerated URL link to view function
I am listing a bunch of items and within the HTML template it contains a URL link to the individual item (link is auto-generate), but I am getting this error when viewing the page: reverse for 'producer_detail' with arguments '('itemxxx', datetime.datetime(1980, 1, 1, 0, 0, tzinfo=<UTC>))' not found. 1 pattern(s) tried: ['producers/(?P<pk>[^/]+)/\\Z'] The table has a UniqueConstraint as there are multiple items with the same owner_name. owner_name = models.CharField(max_length=12, primary_key=True) logo_svg = models.CharField(max_length=100, blank=True, null=True) account_name = models.CharField(max_length=12, blank=True, null=True) metasnapshot_date = models.DateTimeField(blank=True, null=True) constraints = [ models.UniqueConstraint( fields=['owner_name', 'metasnapshot_date'], name="producer_idx", ) ] urlpatterns = [ path("", views.producer_index, name="producer_index"), path("<str:pk>/", views.producer_detail, name="producer_detail"), ] My views def producer_index(request): producers = Producer.objects.all() context = { 'producers': producers } print(producers) return render(request, 'producer_index.html', context) def producer_detail(request, pk, metasnapshot_date): producer = Producer.objects.filter(pk=pk,metasnapshot_date=metasnapshot_date) context = { 'producer': producer } return render(request, 'producer_detail.html', context) My HTML template to view all items {% extends "base.html" %} {% load static %} {% block page_content %} <h1>Producers</h1> <div class="row"> {% for producer in producers %} <div class="col-md-4"> <div class="card mb-2"> <img class="card-img-top" src="{{ producer.logo_svg }}"> <div class="card-body"> <h5 class="card-title">{{ producer.owner_name }}</h5> <p class="card-text">{{ producer.url }}</p> <a href="{% url 'producer_detail' producer.pk producer.metasnapshot_date %}" class="btn btn-primary"> Read More </a> </div> </div> … -
search filtering using react and django
I want to do a search filtering using React and django From Django side it works, but in the frontend Just I type any word immediately I get on [object, object] inside the bar Can anyone guide me thanks in Articles.js export const Articles = () => { const [blogs, setAppState] = useState([]); let navigate = useNavigate(); const [data, setData] = useState({ search: '' }); const goSearch = (e) => { navigate.push({ pathname: '/search/', search: '?search=' + data.search, }); window.location.reload(); }; return ( <div className="wrap mb-4"> <div className="search"> <input type="text" className="searchTerm" placeholder="What are you looking for?" value={data.search} onChange={(newValue) => setData({ search: newValue })} onSubmit={() => goSearch(data.search)}/> <button type="submit" className="searchButton"> <i className="fa fa-search"></i> </button> </div> </div>) in Search.js export const Search = () => { const search = 'search'; const [appState, setAppState] = useState({ search: '', posts: [], }); useEffect(() => { axiosInstance.get(search + '/' + window.location.search).then((res) => { const allPosts = res.data; setAppState({ posts: allPosts }); console.log(res.data); }); }, [setAppState]);return ( <div className="card"> {appState.posts.map((post) => ( <div key={appState.id}> <div className="card-body p-3"> <h5 className="mb-3">{appState.title.substr(0, 35)}...</h5> <h6 className="mb-3">By: {appState.author}</h6> <strong>At</strong><span className="text-dark">{appState.published}</span> <p >{appState.content.substr(0, 100)}...</p> <Link to={`/blog/${appState.slug}`}>Go to the Article</Link> </div> </div> ))}; </div> ); }; -
Install TAILWIND CSS in DJANGO
I'm trying to install and use Tailwinds CSS in my Django project but I can't seems to succeed. This is what I'm doing right now I've create my project, app and added this in settings STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR/'static_root' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') this in urls if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Create a static folder with inside a tailwind folder run while inside the tailwind folder this: npm install -D tailwindcss npx tailwindcss init edit tailwind.config.js like this module.exports = { future: { removeDeprecatedGapUtilities: true, purgeLayersByDefault: true, }, purge: { enabled: false, //true for production build content: [ '../**/templates/*.html', '../**/templates/**/*.html', '../**/templates/**/**/*.html' ] }, theme: { extend: {}, }, variants: {}, plugins: [], } -create a src folder with inside a style css with this code @tailwind base; @tailwind components; @tailwind utilities; -create a dist folder -run this code npx tailwindcss -i ./src/style.css -o ./dist/style.css --watch And I get this warning that I don't understand how to avoid: warn - No utility classes were detected in your source files. If this is unexpected, double-check the `content` option in your Tailwind CSS configuration. warn - https://tailwindcss.com/docs/content-configuration … -
Can't access ManyToMany Relationship in Django
I am having a problem accessing data in a M2M relationship in Django Here are the Models. class Country(models.Model): basic_country = models.ForeignKey( 'datalake.BasicCountry', on_delete=models.PROTECT, null=True, blank=True ) name = models.CharField( max_length=100, unique=True ) two_letter_code = models.CharField( max_length=2, null=True, blank=True, unique=True ) three_letter_code = models.CharField( max_length=3, null=True, blank=True, unique=True ) class State(models.Model): name = models.CharField(max_length=100) country = models.ForeignKey( Country, on_delete=models.PROTECT, null=True, blank=True, related_name='state' ) class CategoricalFilter(models.Model): countries = models.ManyToManyField( 'geolocation.Country', related_name='filtered_countries', blank=True, ) states = models.ManyToManyField( 'geolocation.State', related_name='filtered_states', blank=True, ) industries = models.ManyToManyField( Industry, related_name='filtered_industries', blank=True, ) Now, I can see in my CategoricalFilter model that I have all the fields right, and the needed information. If I do cat_filters = CategoricalFilter.objects.filter("here goes the right filter") and then cat_filter.countries.all() (Individual object) I get the right filtered countries. But when I do cat_filter.states.all(), it brings me nothing, and I can see that I have them in my site admin. Any idea of what I am doing wrong? -
Django Templates: Passing a django value into default_if_none in templates
I am trying to pass two values into django templates. I want value two to be displayed when value one is None. {{ gl.name|default_if_none: gl.name_two }} Someone Help me on how i should handle this. Thanks -
Django cache returns error when using cache.keys()
I have the following code snippet which I am running import os from django.core.cache import cache os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings' cache.keys("q*") but it returns an error. Traceback (most recent call last): File "test_script.py", line 7, in <module> cache.keys("q*") File "/home/vagrant/.virtualenvs/proj/lib/python3.8/site-packages/django_redis/cache.py", line 31, in _decorator return method(self, *args, **kwargs) File "/home/vagrant/.virtualenvs/proj/lib/python3.8/site-packages/django_redis/cache.py", line 141, in keys return self.client.keys(*args, **kwargs) File "/home/vagrant/.virtualenvs/proj/lib/python3.8/site-packages/django_redis/client/default.py", line 700, in keys pattern = self.make_pattern(search, version=version) File "/home/vagrant/.virtualenvs/proj/lib/python3.8/site-packages/django_redis/client/default.py", line 728, in make_pattern prefix = glob_escape(prefix) File "/home/vagrant/.virtualenvs/proj/lib/python3.8/site-packages/django_redis/client/default.py", line 25, in glob_escape return special_re.sub(r"[\1]", s) TypeError: expected string or bytes-like object I am using Django version - 3.2.4 and django-redis version - 5.2.0, Python 3.8.10 -
ModuleNotFoundError: No module named 'app' Heroku
When deoploying my website with Heroku, I run into the following issue: ModuleNotFoundError: No module named 'qr_code' so the website doesn't deploy This is the log tail: My requirements.txt contains the following: asgiref==3.5.0 Django==4.0.3 django-qr-code==3.0.0 gunicorn==20.1.0 qrcode==7.3.1 segno==1.4.1 sqlparse==0.4.2 My Procfile: web: gunicorn qrcode.wsgi qrcode is the name of the folder containing the settings and wsgi file. I have tried: adding qr_code to the requirements reinstalling the qr_code module rewriting the requirements.txt via pip freeze > requirements.txt and then committing -
django admin list_display not a callable
class branch(models.Model): name = models.CharField(max_length=10, unique=True) class company_group(models.Model): branch = models.ForeignKey(branch, on_delete=CASCADE) segment = models.ForeignKey(segment, on_delete=CASCADE) class position_control(models.Model): company_group = models.ForeignKey(company_group, on_delete=CASCADE) position = models.ForeignKey(position, on_delete=CASCADE) rank = models.SmallIntegerField() valid = models.BooleanField(default=True) class PositionControlAdmin(admin.ModelAdmin): list_display = ('company_group__branch', 'position', 'rank', 'valid') list_filter = ('company_group__branch',) I got error <class 'information.admin.PositionControlAdmin'>: (admin.E108) The value of 'list_display[0]' refers to 'company_group__branch', which is not a callable, an attribute of 'PositionControlAdmin', or an attribute or method on 'information.position_control'. With list_filter company_group__branch is working fine. But got error in list_display. How can I fix that? -
Large text storing best practrice in django
I'm developing some api's for a book mobile app. So I have got some huge large text. For this api response is slow. Is there any best way or any 3rd party solution to store large texts ? -
Django Sum annotated field
I'm trying to sum an annotated field in Python First, class InvoiceItems(models): units = FloatField(...) price = FloatField(...) sku = CharField(...) So I want to annotate the units * price then Sum() them all up for a given sku but qs = InvoiceItems.annotate( amount=Sum(F('units')*F('price'), output_field=models.FloatField()) ) isn't working. My actual code is more complicated amount=Sum( ((F('order__orderitem__order_quantity') - F('order__orderitem__cancel_quantity')) * F( 'order__orderitem__unit_price')) - F('order__orderitem__discount_amount'), output_field=models.FloatField() ), If my table is sku | unit | price AA | 2 | 1.00 AA | 3 | 2.00 BB | 4 | 1.00 I want the result sku | amount AA | 8 BB | 4 Any advice would be appreciated! Thanks! -
Django: Median of Subquery result (possibly aka Joining with a Subquery)
Been racking my brains over this for a while now, alas (always the case before I resort to a well-crafted question). But it deserves a careful introduction and problem presentation. I have very carefully taken a rather heavily context-laden problem and extracted from it a classic Django tutorial-style example. In no small part, as part of my own problem exploration (that is, I do recast them in a Django Tutorial project with stripped down book author style models). The Problem Space Imagine scientists publishing papers in journals. They collaborate with other scientists and publish many papers in teams with other scientists, and they publish in a range of journals in a range of teams. Now I want to build a lazy queryset that returns a table of stats about all the scientists publication records. The Sample Space Here is my book/author style recast of my own deeply context laden problem. To wit, no reflection on the sensibility of the models is needed, as they are in fact already only analogues for another problem space in which these kinds of relationships exist. And I've gone to some length to recast it into the tutorial space specifically to test my queries and … -
Use django model in another application
I have two different apps for homepage(main) and events(events) In the models.py of I have a class "Event". In the events/views.py def all_events(request): events_list = Event.objects.all() return render(request, 'event-listing.html', {'events_list': events_list}) which worked just fine. But I want to do the following in the homepage(main) application's views.py def all_events(request): events_list = Event.objects.all() return render(request, 'index.html', {'events_list': events_list}) I imported the following: from BV.events.models import Event but it says : ModuleNotFoundError: No module named 'BV.events' My goal is to show the events in the homepage. -
Not able to connect Azure MySql database in Django Project directly
* I was trying to connect Azure Mysql database in django using db_name, post, username, password, and host name.* ** File "C:\Users\somesh.hiremath\Desktop\Django\Somesh\dj-Somesh\lib\site-packages\MySQLdb_init_.py", line 123, in Connect return Connection(*args, **kwargs) File "C:\Users\somesh.hiremath\Desktop\Django\Somesh\dj-Somesh\lib\site-packages\MySQLdb\connections.py", line 185, in init super().init(*args, kwargs2) django.db.utils.OperationalError: (1045, "Access denied for user 'NewUswe123'@'localhost' (using password: YES)") C:\Users\somesh.hiremath\Desktop\Django\Somesh\TestDjango\TestDjango\settings.py changed, reloading. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'My_db', 'USER': 'NewUswe123', 'PASSWORD': 'Something@123', 'HOST': 'something_name.nothings.cloudapp.azure.com', 'PORT': '3389', 'OPTIONS': { 'read_default_file': '/path/to/my.cnf', }, } } -
Django: How to POST div element to views.py without reloading the page?
I have been struggling with this problem for more than days. I have looked at many documentations but nothing helped me. I am working on Django web application development. The problem is that I have to get the contents(i.e. text inside) of a div element through a form submit (submitted using a button). The catch is that the content inside div element is not fixed. It is initially empty, it changes and shows the info of the actions performed in the page. I am trying to save those info into a list on the server side one-by-one. The ideal solution will be "everytime I click save-info button and the info gets added to a list of info present in views.py (webpage not refreshed on button click)" I researched about posting div elements to server using JQuery and tried myself but could not be successful. Can someone please suggest how do I ach My effort: <form method="POST" id = 'notes_form' action="##" > {% csrf_token %} <div id="notes" cols="5" rows="2"></div> <input type="submit" id="note_btn_id" value="save info"> </form> <script> $(document).ready(function(){ $('#notes_form').submit(function(event){ event.preventDefault(); var notesForm = $(this); var posting = $.post(notesForm.attr('action'),notesForm.serialize()); posting.done(function(data){ console.log("SUCCESS"); }); posting.fail(function(data){ console.log("Try again"); }) }); }); </script> Server side: data_pos =[] … -
django: I accidentally deleted the admin.py file. how to recover it?
I deleted the admin.py file with the rm command. The project is working now. But it will not work after restarting Nginx. Who can help me? -
How to conditionally enable and disable Cursor Pagination on Django Rest Framework?
I have a specific usecase where I need to make available same queryset endpoint for the frontend with and without pagination. I need to use CursorPagination and currently I'm just setting pagination_class = CursorPagination on my *ViewSet class. Is there an easy way to achieve this requirement? -
Comparing between two user models
I have two models. UsersOne and UsersTwo. Both these databases looks like this: class UsersOne(models.Model): username = models.CharField(max_length=255, unique=True) firstname = models.CharField(max_length=255, blank=True, null=True) lastname = models.CharField(max_length=255, blank=True, null=True) password = models.CharField(max_length=255) email = models.CharField(max_length=255, blank=True, null=True) I am tyring to find every user with matching email in the UsersTwo model that. So if there are 10 users in UsersOne and 5 of them have matching email UsersTwo i want to write them out in a csv file. So for example if user John, Doe, ***, jondoe@gmail.com also is a user in UserTwo model i want to make a query to get him. So i have tried this. import both models... users_one = UsersOne.objects.all() matching = [] for i in users_one: matching.append(UsersTwo.object.filter(email=users_one[i].email)) And i get this error: QuerySet indices must be integers or slices, not User.` -
CustomUser Migration Failed Django
I tried making my migrations but can these error messages: ERRORS: accounts.CustomUser.groups: (fields.E304) Reverse accessor for 'accounts.CustomUser.groups' clashes with reverse accessor for 'auth.User.groups'. HINT: Add or change a related_name argument to the definition for 'accounts.CustomUser.groups' or 'auth.User.groups'. accounts.CustomUser.user_permissions: (fields.E304) Reverse accessor for 'accounts.CustomUser.user_permissions' clashes with reverse accessor for 'auth.User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'accounts.CustomUser.user_permissions' or 'auth.User.user_permissions'. auth.User.groups: (fields.E304) Reverse accessor for 'auth.User.groups' clashes with reverse accessor for 'accounts.CustomUser.groups'. HINT: Add or change a related_name argument to the definition for 'auth.User.groups' or 'accounts.CustomUser.groups'. auth.User.user_permissions: (fields.E304) Reverse accessor for 'auth.User.user_permissions' clashes with reverse accessor for 'accounts.CustomUser.user_permissions'. HINT: Add or change a related_name argument to the definition for 'auth.User.user_permissions' or 'accounts.CustomUser.user_permissions'. Here is my CustomUserManager: class CustomUserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): if not email: raise ValueError("User must have an email") email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password=None, **extra_fields): user = self.create_user(email, password=password, **extra_fields) user.is_active = True user.is_staff = True user.is_admin = True user.save(using=self._db) return user Let me know by making a comment if i should also upload my model. -
Code goes to except block only (not Try block) [closed]
I have written following code in django for forgot password, my views code as under, def forgot_password(request): if request.method=="POST": try: user=User.objects.get(email=request.POST['email']) subject='OTP for new password' otp=random.randint(1000,9999) message = 'OTP for forgot password is '+str(otp) email_from = settings.EMAIL_HOST_USER recipient_list=[user.email,] send_mail( subject,message,email_from,recipient_list ) return render(request,'otp.html',{'email':user.email,'otp':otp}) except: msg="Email Does Not Exists" return render(request,'forgot_password.html',{'msg':msg}) else: return render(request,'forgot_password.html') now whenever i try to get forgot password it says email id already exists. It does not go to OTP page. my urls is as under, path('forgot_password/',views.forgot_password,name='forgot_password'), path('varify_otp/',views.varify_otp,name='varify_otp'), path('new_password/',views.new_password,name='new_password'), pls help -
How to use email as username for Django registration
I am new to django and creating registration form using django's UserRegistrationForm, which requires username and password . I want to use email instead of username. How I can do this? def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request,f'Account Created For {username} !') return redirect('starting-page') else: form = UserRegisterForm() return render(request,'users/register.html',{'form': form}) -
Как получить id объекта при POST запросе от пользователя
Как мне получить id объекта Payment при отправке Post запроса пользователем? Если указать явно Payment.objects.get(pk=13), всё срабатывает КОд ошибки : stellaj_manager.models.Payment.DoesNotExist: Payment matching query does not exist. class MakePay(CreateAPIView): """Совершение покупки""" serializer_class = MakePaySerializer permission_classes = [permissions.IsAuthenticated] def perform_create(self, serializer): # Достаём объект пользователя для сохранения user = User.objects.get(user_id=self.request.user) obj = self.request.data.__getattribute__('id') serializer.save(user_id=user) p = Payment.objects.get(pk=obj) p.buy_item() class Payment(models.Model): """История покупок""" user_id = models.ForeignKey(to=User, verbose_name='Пользователь', on_delete=models.PROTECT) product_id = models.ForeignKey(to=Product, related_name='payments', verbose_name='Продукт', on_delete=models.PROTECT) total = models.PositiveSmallIntegerField(verbose_name='Итоговая сумма',default=0) date = models.DateTimeField(auto_now_add=True, verbose_name='Время покупки') quantity = models.IntegerField(verbose_name='Проданно штук', default=1) class Meta: verbose_name = 'История' verbose_name_plural = 'Истории' ordering = ['-date'] def __str__(self): return f'Покупка от: {self.date}' # Метод покупки товара пользователем @transaction.atomic() def buy_item(self): try: product = self.product_id product.quantity -= self.quantity product.save() self.total = product.price * self.quantity self.save() user_count = self.user_id user_count.balance -= self.total user_count.save() return 'Successeed' except: raise Exception('Something goes wrong, try later') -
I want custom pagination in this ListApiview but cannot resolve it
class ItemLedgerView(generics.ListAPIView): permission_classes = [ItemLedgerPermission] queryset = PurchaseDetail.objects.all() pagination_class= CustomPagination paginate_by = 10 def get(self, request): query_dict = { } for k, vals in request.GET.lists(): if vals[0] != '': k = str(k) query_dict[k] = vals[0] query_filter = {} if "date_after" in query_dict: query_filter['created_date_ad__date__gte'] = query_dict['date_after'] if "date_before" in query_dict: query_filter['created_date_ad__date__lte'] = query_dict['date_before'] page = self.paginate_queryset(self.queryset) data = get_item_ledger(query_dict) return self.get_paginated_response(data)enter code here I wrote this code when tried to go to next page. I got error like Cannot resolve keyword 'page' into field. -
django tests: client request an empty string instead of an WSGIRequest object
I am working on a django project for which I created an app that is used in other projects. The app and the project have their own repository and folder. I want to write tests that are specific to the app of that form: from django.test import TestCase from django.urls import reverse class SignUpTest(TestCase): def test_my_signup_get2(self): response = self.client.get(reverse('signup')) self.assertEqual(response.status_code, 200) When I run such tests from the folder of my app, the request object generated is an empty string, which will cause the test to fail. Within the logic of the project, the request.user is being accessed, which does not exist on a string. When i run the exact same tests from the project folder where this app is used, the request object is a WSGIRequest object and the test succeeds, as the request.user is present. How can I make sure that the request is always a WSGIRequest?