Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Serialize two models [Django]
I have got three models like: class A(models.Model): title = models.CharField(max_length=30) class B(A): height = models.IntegerField() class C(A): width = models.IntegerField() view: class AList(generics.ListAPIView): serializer_class = ASerializer queryset = A.objects.all() and serializer: class ASerializer(serializers.ModelSerializer): class Meta: model = A fields = '__all__' When I create C class object I have to input title and width (I do it in admin panel), but when I make GET method to the AList view, this object has only title property. I know that it is because of the declared model in serializer, so is there any way to make something like that: model = B or C in ASerializer? I want to get all B and C class objects in one view. I'm open for all suggestions on how to approach this issue. -
django UpdateView get_success_url not returning to profile page
I am still new to django and have encountered this issue, the situation is like this, i have a profile model, on which i have 2 views ViewProfile and EditProfile inheriting from DetailView and UpdateView respectively. when i edit the profile page, it doesn't get me to the profile page instead it gave the error: Reverse for 'profile' with keyword arguments '{'id': 9}' not found. 1 pattern(s) tried: ['profile/(?P<pk>[^/]+)/\\Z'] even though i have checked in the python shell, the profile with id:9 is indeed profile with name muham see below >>> Profile.objects.all() <QuerySet [<Profile: huzaifa>, <Profile: another1>, <Profile: muham>]> >>> p1 = Profile.objects.get(name='muham') >>> p1.id 9 >>> but still its not showing, i have overridden the get_success_url to get me to the profile page: class EditProfile(LoginRequiredMixin, UpdateView): model = Profile fields = ('name', 'address', 'phone_no',) template_name = 'blog_app/edit_profile.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['user'] = self.request.user return context def get_success_url(self): id = self.request.user.profile.id return reverse_lazy('profile', kwargs={'id': id}) my model is below: class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=60, blank=True, null=True) address = models.CharField(max_length=400, null=True, blank=True) # image phone_no = models.CharField(max_length=40, null=True, blank=True) def __str__(self): return str(self.user) -
Saving a JSON-Field with popped keys
I'm trying to delete all occurences of a certain key in a JSON-Field when a certain key is deleted. What I've been trying is just popping all occurences of the given key in the json-field. However, saving a JSONField with a popped key doesn't seem to work - the data isn't changed on the Element-objects. Is there a way to do this? class Element(models.Model): data = models.JSONField(default=dict, blank=True) class Key(moedls.Model): [...] def delete(self, *args, **kwargs): to_update = Element.objects.filter(data__has_key=self.slug) for element in to_update: element.data.pop(self.slug) GraphElement.objects.bulk_update(to_update, ["data"]) super().delete(*args, **kwargs) -
How to change url on reload if database object changed?
There's a field name landingpage. if the admin changes the landing page user gets that redirected page, and also if the user refreshes the page so the user is redirected to that changed redirected page. def coustomLandingPage(req): show = liveEvents.objects.get() return redirect(show.landingPage) urls.py from django.contrib import admin from django.urls import path from icai import views urlpatterns = [ path('', views.coustomLandingPage, name='coustlanding'), path('registration', views.home, name='registration'), path('login', views.login, name='login'), path('sessionover', views.over, name='over'), path('golive', views.sessionlive, name='live_session'), path('ques', views.qus_send, name='auestionsent') ] -
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