Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Multi container application
I have to create a dockerized web application. In my idea, I would like to create 3 containers: A Python Django container that can query a container that contains an R-script. An R container A Postgres database container. My question is this: how can I query the R container from the Django container? Thank you for your support. -
Set Unique Constrait only under the direct parents (Django MPTT)
I created "Category" model with Django MPTT: from django.db import models from mptt.models import MPTTModel, TreeForeignKey class Category(MPTTModel): name = models.CharField(max_length=50) parent = TreeForeignKey("self", on_delete=models.CASCADE, null=True, blank=True, related_name="children") But, with this "Category" model, I could add the duplicated data "3F" and "4F" under "Building B"(Direct Parent) as shown below: USA New York Building A 3F 4F Building B 3F // Here 3F // Here 4F // Here 4F // Here So I added "unique=True" to "name" field in the model "Category": from django.db import models from mptt.models import MPTTModel, TreeForeignKey class Category(MPTTModel): // Here name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey("self", on_delete=models.CASCADE, null=True, blank=True, related_name="children") But with this "Category" model, I couldn't add the data "3F" and "4F" under "Building B" anymore because "3F" and "4F" already exist under "Building A" in "Category". I found adding "unique=True" to "name" field in "Category" model sets Unique Constrait in whole "Category" model about "name" field. So if there are the same "name" values such as "F3" and "F4" anywhere in "Category", we cannot add the same "name" values such as "F3" and "F4" anywhere in "Category". In short, if "3F" and "4F" already exist anywhere in "Category", we cannot add "3F" and … -
SMTPConnectError (421, b'Server busy, too many connections')SMTPConnectError (421, b'Server busy, too many connections')
I have checked every single solution on other questions but they are of zero help,using bulk email services also require having a domain name already meanwhile my django website is still in development but i also want to send actual mails not mail on django console.I have allowed access to less secure apps,used app password and re capcha all to no avail,i even changed my email host to yahoo mail still the same thing,the fact that email verification is a core part of authentication and there's little to no support or help is very annoying,already looked through all youtube videos it worked for them but non worked for me my settings file: EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'mymail@gmail.com' EMAIL_HOST_PASSWORD = 'password' EMAIL_USE_TLS = True EMAIL_USE_SSL = False the error mesage: SMTPConnectError (421, b'Server busy, too many connections') -
Make the filter from class method or get the queryset from class method
What I want to do finally is like this using is_special MyObjectForm = forms.ModelChoiceField( queryset=MyObj.objects.filter(is_special=False),required=False) However is_special is not the member of the model but method. class MyObj(models.Model): key = m.CharField(max_length=20,null=False,unique=False) class Meta: db_table = 'myobj' def is_special(self): return SpecialMember.is_key_exist(self.key) So, I come to two ideas. Using method as filter variable Geting the queryset by object method. Is it possible? -
I get this error when i want to run my django app :
ImportError: cannot import name 'froms' from 'django' -
AWS ElasticBeanstalk instance protection for leader_only node
I have a django application running on EBS. My application runs celery beat on 1 of the instances by using the ebextension container command: 03_celery_tasks: command: "cat .ebextensions/files/celery_configuration.txt > /opt/elasticbeanstalk/hooks/appdeploy/post/run_supervised_celeryd.sh && chmod 744 /opt/elasticbeanstalk/hooks/appdeploy/post/run_supervised_celeryd.sh" leader_only: true 04_celery_tasks_run: command: "/opt/elasticbeanstalk/hooks/appdeploy/post/run_supervised_celeryd.sh" leader_only: true During auto-scaling/or routine cleanup EBS might remove the leader_only node which cause celery scheduled task to stop running. I know there is the ability to protect instances during scale-in/out moments However I am not sure how to enable instance protection for my leader node specifically (the one running celery beat) -
django graphene pytest mock query not working
I have a simple test case like: @patch('helpers.queries.Query.resolve_profile_lookup') def test_profile_lookup(mock_resolve_profile_lookup, client, client_query): mock_resolve_profile_lookup.return_value = [ {"name": "First name"}, {"address": "First address"}, ] response = client_query( """ query profileLookup($search: String!){ profileLookup(search: $search) { name address } } """, variables={"search": "jack"}, ) content = json.loads(response.content) assert mock_resolve_profile_lookup.called Here, I want to mock the resolve_profile_lookup query that I have in Query. From my understanding the function I patch is mocked while running test case, but its not working here. Anything that I am missing here ? -
how do increment all column values in db table after certain integer values in that column (django)?
Suppose I have created "X" database table in Django which has column id(autofiled), name(charfield) and occurrence(integerfield), now suppose 3 rows are already available in it id name occurrence 1 ABC 1 2 BCD 2 3 CDE 3 I want to get data based on (ordering) the occurance number, I am facing a problem that, I want to add a row with an occurrence number 2 (already present), and all the rows with occurrence numbers greater than 2 update and increment automatically. (Basically, It is a inserting data on index number, where value is name and index is occurrence ignore id). For Example- id name occurrence 1 ABC 1 2 BCD 3 3 CDE 4 4 XYZ 2 Thanks in advance. -
Can you import the BUILD_ID of a cloud build into your Cloud Run python container?
We want to use django's redis cache feature that allows us to specify version numbers which will effectively invalidate cache values of a previous build (before the code changed). GCP's Cloud build has a default $BUILD_ID value available to the build yaml files, but is there a way for a deployed container to access this BUILD_ID value? If we could, we could us it (or a modulo value of it) to be our unique cache version. See https://cloud.google.com/build/docs/configuring-builds/substitute-variable-values for GCP build variables See https://docs.djangoproject.com/en/4.0/topics/cache/#cache-arguments for django cache documentation -
Override response in a Class Based View Django
I have a view that I'd also like to export data from as a CSV also with search parameters & filters. I want the exported data to be exactly the same queryset as this view, so what I have currently is inefficient. Note: The code below may look pretty silly & some sections pointless, but I'm just being careful with my NDA so omitted down to an anonymous reproduction. class ModelListView(LoginRequiredMixin, ListView): model = Model template_name = 'list.html' paginate_by = 15 def get_queryset(self): if not self.request.user.is_staff: queryset = Model.objects.filter() queryset = Model.objects.filter() search = self.request.GET.get("search", None) if search: queryset = queryset.filter( Q(type__icontains=search) | Q(status__icontains=search) | Q(prefix__icontains=search) | Q(created__icontains=search) | Q(message__icontains=search) ) # Save most recent queryset to session for # use with exporting & retrieval on other pages. self.request.session["queryset"] = serializers.serialize('json', queryset) return queryset Currently towards the end there I save the queryset to request.session & then use it in a separate ExportView, which works, but comes with a can of worms. I'm wondering where I might override the response for a Class-Based View so I could instead set a query param like ?format=csv & have the same view return a CSV response instead. I'm sure this is possible, but … -
Cannot resolve keyword annotated field django
this is my model class ExchangeReportTime(models.Model): creator = models.ForeignKey('accounts.Account', on_delete=models.CASCADE, null=True, verbose_name=_('Creator')) create_time = models.DateTimeField(default=timezone.now) exchange = models.ForeignKey(BorseExchange, on_delete=models.SET_NULL, null=True, related_name='report_times') actual_fiscal_month = models.CharField(max_length=255, null=True, blank=True) fiscal_month = models.CharField(max_length=5, null=True, blank=True) fiscal_year = models.CharField(max_length=255, null=True, blank=True) is_fiscal_year_changed = models.BooleanField(null=True, blank=True) period_ending_date = models.CharField(max_length=15, null=True, blank=True) statement_key = models.IntegerField(null=True, blank=True) statement_type = models.CharField(max_length=50, null=True, blank=True) ... fiscal_month and fiscal_year are string so i change types and query as below exchange = BorseExchange.objects.get(tse_code=exchange_number) last_12_season = exchange.report_times.filter( statement_type='InterimIncomeStatement', period_type='seasonally' ).annotate( fiscal_month_number=Cast('fiscal_month',IntegerField()), fiscal_year_number=Cast('fiscal_year',IntegerField()), ).order_by( '-fiscal_year_number', '-fiscal_month_number' ).distinct( 'fiscal_month_number', 'fiscal_year_number' )[:records_count] but i give error: django.core.exceptions.FieldError: Cannot resolve keyword 'fiscal_month_number' into field. Choices are: actual_fiscal_month, attachment_url, auditing, company_key, create_time, creator, creator_id, currency, exchange, exchange_id, fiscal_month, fiscal_year, html_url, id, is_empty, is_fiscal_year_changed, period_ending_date, period_type, publish_date, publish_time, report_items, scenario, statement_key, statement_type where is the problem? python3.6 and django 2.2.* -
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?