Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I access attributes of a model in admin.TabularInline that is at the end of a manytomany relationship with defined through model
I am facing the following scenario; #models.py class A(models.Model): dog = models.CharField(...) cat_values = models.ManyToManyField(B, through='AtoB') class AtoB(models.Model): one = models.ForeignKey(A) two = models.ForeignKey(B) class B(models.Model): cat = models.CharField(...) #admin.py class BForm(forms.ModelForm): cat = forms.TextInput() class Meta: model = A.cat_values.through exclude = [] class BInline(admin.TabularInline): model = B.cat_values.through form = BForm fields = ['cat', ] readonly_fields = ['cat', ] @admin.register(A) class AAdmin(admin.ModelAdmin): inlines = [BInline,] When I try to run server, I get the following error message; <class 'agregator.admin.AAdmin.BInline'>: (admin.E035) The value of 'readonly_fields[0]' is not a callable, an attribute of 'BInline', or an attribute of 'agregator.AtoB'. No other forms of access really work like A.cat_values or A.cat_values.two I partially understand where is the problem coming from. It does not let me access the B's attributes, only AtoB's attributes. I have tried to work around it but unsuccessfully. Have read the documentation but there is nothing about accessing the attributes in this case scenario, only without a defined through model. eg https://docs.djangoproject.com/en/3.1/topics/db/examples/many_to_many/ or https://docs.djangoproject.com/en/3.1/topics/db/models/ I need to display the cat attribute in the inline in the A's admin. Any help would be much appreciated. -
Django - Updating forms when chagning login from username, to email
I have changed my django project, to use email addresses instead of passwords when logging in. To do this, i create a custom user model as so: class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user and class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email Now in my views, im using django's built in views for the user account lifecycle, path('accounts/', include("django.contrib.auth.urls")). But now, my register and login forms are incorrect. They ask for usernames, not email. (interestingly, the login form with username still works, not really sure why). My question is, how do I update these forms to reflect email addresses, and not username? Thanks, -
Why can't I create an instance of a class inside an abstract class
I am using django-parler for language translation in an abstract class model but I get this error: raise TypeError("Can't create TranslatedFieldsModel for abstract class {0}".format(shared_model.__name__)) TypeError: Can't create TranslatedFieldsModel for abstract class MyClass I want to know why I can't create an instance of this TranslatedFieldsModel in an abstract class. Are there some instance or some type of classes/objects that cannot be instantiated in an abstract class? I really don't know much about abstract classes, please explain to me why this TranslatedFieldsModel cannot be created and how to go about it -
How to check request.FILES is black or not in Djnago?
I am using Djnago.i Have html Form such as below, <form method="POST" action="{% url 'someaction' %}" enctype="multipart/form-data"> <input type="file" name="image" id="image"> </form> How to check request.FILES['image'] is Selected or not in djnago view file? -
Django don't refrash page and menu in during work in admin-side
We met very strange behavior of DjangoCMS. Desctiption of problem After adding any page, sotimes it disappear, sometimes appear. Refrash page througth CTRL+F5 item of menu also sometimes appear and disappear. What is problem? Example on video: https://yadi.sk/i/366VZBjy7xrChg We are using Nginx 1.19.0, Django CMS 3.7.1 на Django 2.2 and Postgres 12.3 Thanks a lot for any help! -
Django (GET) - Is it posible to pass multiple values in only one parameter, instead of multiple parameters called the same
I'm developing an web app with Django to query and download data from multiple weather stations. It's almost everything good but something that I don't like it's that when I filter by stations, the form passes them to the URL like this: https://my-server/stations?station_name=1&station_name=2&station_name=3 And since the number of selected stations can reach more than 250 (this added to the fact that spatial data are also passed in the URL as coordinates, polygons...), I would like to know if there is any way to obtain the "station_name" parameter in a list format like this or similar, for me to later divide it in my views.py: https://my-server/stations?station_name=1%3B2%3B3 On the other hand, I'm not sure if there are any contraindications when generating too long URLs, if not I have no problem maintaining the current format, but otherwise I would like to find a solution. Thanks in advance -
How to get object by name in views.py django
How to get object in views.py using name not by id. def StockSummaryPage(request, title): stocks_data = get_object_or_404(Stock, string=title) return render(request, 'stocks/stock_summary_page.html', {'stocks_data':stocks_data}) This is my views.py and in stocks_data = get_object_or_404(Stock, string=title) we use pk= stock_id but i want to do it by title. So help me -
Cant send a message to a Django channel
I want to send a message over a channel using Django Channels. This is how I'm doing. I create a consumer first. I'm able to echo back the received messages. However, not able to send messages to a specific channel/group. class Consumer(AsyncJsonWebsocketConsumer): """Consumer.""" def _get_connection_id(self): return ''.join(e for e in self.channel_name if e.isalnum()) async def connect(self): scope = self.scope user_id = str(scope['user'].user_id) connection_id = self._get_connection_id() # Adding connection to DB. obj = UserConnection.add(connection_id=connection_id, user_id=user_id) # Accept the connection await self.accept() # Adding current to group. await self.channel_layer.group_add( user_id, connection_id, ) async def disconnect(self, close_code): """Remove the connection and decrement connection_count in DB.""" connection_id = self._get_connection_id() user_id = str(self.scope['user'].user_id) UserConnection.drop(connection_id=connection_id) # Dropping from group. await self.channel_layer.group_discard( user_id, connection_id, ) async def receive_json(self, data, **kwargs): """Receive messages over socket.""" resp = data # I'm able to echo back the received message after some processing. await self.send(json.dumps(resp, default=str)) # This does not works. def send_to_connection(connection_id, data): """Send the data to the connected socket id.""" return get_channel_layer().group_send(connection_id, data) Now when I try to send a message, the connected socket does not receives the message. >>> connection_id = UserConnection.objects.get(user_id=user_id).connection_id >>> send_to_connection(connection_id, {'a':1}) # returns <coroutine object RedisChannelLayer.group_send at 0x109576d40> What's the issue in the code? -
How to override post method of generics.ListCreateAPIView?
guys. I'm writing backend for application that allow voting for best pizza. I have Pizza model (id, name, price), built-in User model, Vote model(id, author [models.ForeignKey], pizza[models.ForeignKey]). In my project I implement view class VoteList(generics.ListCreateAPIView): queryset = Vote.objects.all() serializer_class = VoteSerializer And now I want to implement check if authenticated user posts vote with his id. If it is True, I want to save it into the datebase, else I don't want to save it and return HTTP with error if request.user.pk == self.serializer_class.Meta.model.author: So could you, please, help me to implement this functionality -
Wagtail not indexing body field
I'm trying to search. It can find words from the 'title' but not from the 'body' text. I have no further settings only defaults. Any ideas? class StandardPage(Page): body = RichTextField(features=['h2', 'bold', 'italic', 'link', 'ol', 'ul', 'document-link', 'image', 'embed']) sidebar_image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) # Search index configuration search_fields = Page.search_fields + [ # Inherit search_fields from Page index.SearchField('body'), ] and this is my view.py def search(request): search_query = request.GET.get('query', None) page = request.GET.get('page', 1) # Search if search_query: search_results = Page.objects.live().search(search_query) query = Query.get(search_query) # Record hit query.add_hit() else: search_results = Page.objects.none() return render(request, 'search/search.html', { 'search_query': search_query, 'search_results': search_results, }) -
elasticsearch.exceptions.ConnectionError: Failed to establish a new connection:
When I run python src/manage.py search_index --rebuild -f I get the following error elasticsearch.exceptions.ConnectionError: ConnectionError(<urllib3.connection.HTTPConnection object at 0x7f4bd08259e8>: Failed to establish a new connection: [Errno -2] Name or service not known) caused by: NewConnectionError(<urllib3.connection.HTTPConnection object at 0x7f4bd08259e8>: Failed to establish a new connection: [Errno -2] Name or service not known) I am not familiar with elastic search. in my settings/base.py, I have ELASTICSEARCH_DSL={ 'default': { 'hosts': '127.0.0.1:9260' }, } and my docker-compose.yml elastic: image: docker.elastic.co/elasticsearch/elasticsearch:7.5.1 ports: - 9260:9200 environment: http.host: 0.0.0.0 transport.host: 127.0.0.1 volumes: - ./config/elastic/elasticsearch.yml:/usr/share/elasticsearch/config/elasticsearch.yml - elasticsearch:/usr/share/elasticsearch/data Please let me know if any other information needed. Thank you in advance -
'NoneType' object has no attribute '_prefetch_related_lookups' in Django Form
I am having a form and I am using chained dropdown in it .... I'm following this tutorial and created two htmls for showing the dropdown and appending it with Ajax call https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html but I am unable to edit it .... It showing an error like this " 'NoneType' object has no attribute '_prefetch_related_lookups'" class PlaceLoadForm(forms.Form): state = forms.ModelChoiceField(queryset=None, required=True) city = forms.ModelChoiceField(queryset=None, required=True) def __init__(self, query=None, city=None, * args, **kwargs): super().__init__(*args, **kwargs) if query: try: self.fields['city'].queryset = City.objects.filter( id=query) except (ValueError, TypeError): pass if query and city: if project: self.fields['state'].initial = query if task: self.fields['city'].initial = city in my views.py def create_time_entry(request, list_id=None): form = DetailEntry(request.POST or None, instance=query, user=request.user or None) module_from = ProjectLoadForm() if request.method == 'GET': if query: city = City.objects.filter(id=query.city) data['form'] = form data['placeload_form'] = PlaceLoadForm(query, city) data['query'] = query return render(request, 'time_sheet/NewFormTimeSheet.html', data) In my html When I am calling like this {{ placeload_form.city|add_class:'form-control full-width' }} It throwing one error 'NoneType' object has no attribute '_prefetch_related_lookups' -
How to combine Q condition in Django
Say there're some query condition as below: from django.db.models import Q or_conditions = [ {"a": 1}, {"b": 2}, {"c": 3}, ] single_or_condition = {"d": 4} and_condition = {"e": 5} # I want get condition like (a or b or c) and (e) or (d) # And I've tried with below, but failed group_Q = Q() for condition_model in or_conditions: group_Q.add(Q(**(condition_model)), conn_type=Q.OR) final_Q = group_Q.add(Q(**single_or_condition), conn_type=Q.OR).\ add(Q(**and_condition), conn_type=Q.AND) I want to get something like (a or b or c) and (e) or (d) And tried with codes above, but unexpected result returned. It seemd that my Q query condition didn't work. How can I make it right? Thanks -
How to redirect django search from main page to another local page?
Ok I spent over two weeks trying to resolve this but I can't find a clear answer. I am new to django so I am trying to figure my way out. So here is my problem: I have a website with several products on it and I recently created search.html file that works when I go to "http://127.0.0.1:8000/search/" but I want to make it when the user types something in the search bar on the main page "http://127.0.0.1:8000" and clicks search Django will redirect the user with the input value to "http://127.0.0.1:8000/search/". ####-------------------------------------------------------### In my view.py def searchproduct(request, *args, **kwargs): if request.method == 'GET': query=request.GET.get('q') submitbutton= request.GET.get('submit') if query is not None: lookups = Q(name__icontains=query)| Q(description__icontains=query) | Q(detailed_description__icontains=query) | Q(PN__icontains=query) | Q(image__icontains=query) results= Product.objects.filter(lookups).distinct() context={'results':results,'submitbutton': submitbutton} return render(request, 'search.html', context) else: return render(request, 'search.html') else: return render(request, 'search.html') ####-------------------------------------------------------### In my base.html <div id="search_head"> <br/> <form action="" method="GET" value="{{request.GET.q}}" > Search <input type="text" name="q" value="{{request.GET.q}}" placeholder="Search products"/> <input type="submit" name="submit" value="Search" /> </form> </div> ####-------------------------------------------------------### in my url.py: urlpatterns = [ path('', home_view, name='Home'), path('search/', searchproduct, name='Search'),] -
How to configure Lambda function (django) outside VPC to access Amazon ElastiCache inside a VPC?
How to configure Lambda function (django) outside VPC to access Amazon ElastiCache inside a VPC?? The suggestions from everywhere is its possible only if its in same VPC, but my lambda function is outside VPC and Amazon ElastiCache inside a VPC. How do I configure? Thanks in advance -
Changing SQLite to PostgreSQL in Django cause Error 'cannot cast type bytea to boolean'
I had a project in Django that use SQLite as database and it works well. Now i want change my database from SQLite to PostgreSQL. i changed settings.py file and installed psycopg2. the problem is that when i want run python manage.py migrate i had error in CMD that says: ... django.db.utils.ProgrammingError: cannot cast type bytea to boolean LINE 1: ...ansactionType" TYPE boolean USING "TransactionType"::boolean and at django debug mode in browser shows this error: ProgrammingError at /home operator does not exist: bytea = boolean LINE 1: ...ction" WHERE ("web_transaction"."TransactionType" = true AND... this is my model in django class Transaction(models.Model): Amount = models.BigIntegerField() TransactionType = models.BooleanField() in my home view i use this query that error django debug mode indicates: def homePage(request): this_user=request.user income = Transaction.objects.filter(user=this_user, TransactionType=True).aggregate(Sum('amount')) i can't find out why this happen when use PostgreSQL but works well in SQLite. -
Django: save an instance and use it later in another form (two forms processed in one views.py function)
I have two forms in one html page. The first form has a button generate and the second form has the button save. For context, I have to save the object that is displayed when I click the generate button. In the views.py, these forms are contained in one function as shown below: def index(request): q = Quote.objects.all() if request.method == 'POST' and 'generate' in request.POST: form = EmotionForm(request.POST) if form.is_valid(): emotion = form.cleaned_data['emotion'] quote = choice(q.filter(tag__name=emotion)) # <–- use this instance... context = { 'emotion': emotion, 'quote':quote, } return render(request, 'main/index.html', context) if request.method == 'POST' and 'save' in request.POST: quote = SavedQuote(user=request.user, quote=quote) # <–- ...here quote.save() return redirect('account') else: form = EmotionForm() context = { 'form': form, } return render(request, 'main/index.html', context) My problem is that I want to use the instance quote = choice(q.filter(tag__name=emotion)) in the line quote = SavedQuote(user=request.user, quote=quote). I've already tested my code if everything works fine by hard coding the instance, e.g., quote = SavedQuote(user=request.user, quote=choice(q.filter(tag__name=happiness))) and it does work. Even if I try to assign a variable outside the if statements, it won’t work as the page reloads and runs the function again. What are good ways to save the instance … -
module 'django.db.models' has no attribute 'FieldDoesNotExist'
I am having issues with my django admin area while adding data and selecting theenter image description here author which comes from relation from another class it gives the error written in title the relation is enter image description here anyone with the answer will be helpfull thanks -
How to show validation error in my form instead of getting IntegrityError?
I am creating a portfolio app, in which there are two models: class Portfoller(AbstractUser): career_options = [('Developer','Developer'), ('Artist', 'Artist'), ('Writer','Writer')] gender_options = [('Male', 'Male'), ('Female', 'Female'), ('Other', 'Other')] first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) gender = models.CharField(max_length=6, choices=gender_options, default='Male') birthdate = models.DateField('birthdate') country_of_birth = CountryField() career = models.CharField(max_length=20, choices=career_options) email = models.EmailField(max_length=254, unique=True) profile_picture = models.ImageField(upload_to=profile_picture_path, default='generic_user.png') biography = models.TextField(max_length=1000, null=True, blank=True) def get_age(self): now = timezone.now() return now.year - self.birthdate.year - ((now.month, now.day) < (self.birthdate.month, self.birthdate.day)) class Project(models.Model): user = models.ForeignKey(Portfoller, on_delete=models.CASCADE) project_name = models.CharField(max_length=50) project_description = models.TextField(max_length=1024) class Meta: unique_together = ('project_name', 'user') And now I am making a view to add a Project to a Portfoller: class AddProject(View): def get(self, request, username): form = AddProjectForm() form.instance.user = get_object_or_404(Portfoller, username=username) return render(request, 'portfolio/add_project.html', {'form': form}) def post(self, request, username): form = AddProjectForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('portfolio:profile', kwargs={'username': username})) The problem is that when I get a project_name equals to an existent project project_name I want to get a form error in the form page, but instead, I'm getting a: IntegrityError at /users/admin/add-project/ null value in column "user_id" violates not-null constraint How to solve it? urls.py: from django.urls import path, include from . import views app_name = 'portfolio' … -
How can I locking list when async task running for another task?
I have a task that needs to run every 1 minute. I want the orders in the order list I sent to this task not to be in the next task even if it is not completed. How should I make a development? async_row_process = kwargs.get("async_row_process", True) #when next task is running task must leave previous 'previous order list' for order in orders: if async_row_process: row_method.delay(row=order, lock_name=lock_name, now='%s' % now, *args, **kwargs) Am I should develop a decorator ? Or can I use order queue for all tasks can see ? -
Unable to pass a view function with two arguments in Django resulting in No Reverse Match Error
I am unable to understand why am I getting this error. If someone can please explain me why and how I can fix it, I am hoping that it will correct the underlying misconceptions that I probably have about Django views and urls. django.urls.exceptions.NoReverseMatch: Reverse for 'download' with keyword arguments '{'name': 'Dr. XYZ', 'date': '14 July 2020'}' not found. 1 pattern(s) tried: ['download/$'] I have a function called download in my views.py which takes two arguments: name and date Views.py def download (request, name, date): x = date.split(" ") date = f"29 {x[3]} {x[4]}" image = Image.open("certificates\static\certificates\Certificate_0001.jpg") font_type = ImageFont.truetype('arial.ttf', 70) font_type_2 = ImageFont.truetype('arial.ttf', 35) draw = ImageDraw.Draw(image) draw.text(xy=(810, 740), text=name, fill=(0,102,0), font=font_type) draw.text (xy=(330, 1230), text=date, fill=(0,102,0), font=font_type_2) image.save(f"certificates\static\certificates\{name}.pdf", "PDF", resolution=100.0) return HttpResponse ("works") I am calling this function upon a link click in my html file. <a class="nav-link active" href="{% url 'certificates:download' name=name date=program %}" download>Download Certificate</a> The url configuration is: urls.py from django.urls import path from . import views app_name = "certificates" urlpatterns = [ path("", views.index, name="index"), path("download", views.download, name="download") ] It is confirmed that there is no syntax or other logical error in my function. If I remove the two arguments in my html file … -
Django ModuleNotFoundError: No module named 'sql_server' With Docker
I am getting an error in console while trying to install lib django-pyodbc , django-pyodbc-azure and pyodbc With docker. How to fix this. PS C:\Users\TestPIXS\Desktop\Test\Testadmin\master> docker-compose build Building web Step 1/7 : FROM python:3 ---> 28a4c88cdbbf Step 2/7 : ENV PYTHONUNBUFFERED l ---> Using cache ---> aa30b1083d6a Step 3/7 : RUN mkdir /app ---> Using cache ---> 1a205fb68d9f Step 4/7 : WORKDIR /app ---> Using cache ---> 6f532c2f7d6b Step 5/7 : COPY requirements.txt /app/ ---> 1e900bfa67a1 Step 6/7 : RUN pip install -r requirements.txt ---> Running in 08071da8e89b Collecting Django==3.1.1 Downloading Django-3.1.1-py3-none-any.whl (7.8 MB) Collecting django-pyodbc==1.1.3 Downloading django_pyodbc-1.1.3-py2.py3-none-any.whl (51 kB) Collecting django-pyodbc-azure==2.1.0.0 Downloading django_pyodbc_azure-2.1.0.0-py3-none-any.whl (39 kB) Collecting pyodbc Downloading pyodbc-4.0.30.tar.gz (266 kB) Collecting pytz Downloading pytz-2020.1-py2.py3-none-any.whl (510 kB) Collecting asgiref~=3.2.10 Downloading asgiref-3.2.10-py3-none-any.whl (19 kB) Collecting sqlparse>=0.2.2 Downloading sqlparse-0.3.1-py2.py3-none-any.whl (40 kB) Building wheels for collected packages: pyodbc Building wheel for pyodbc (setup.py): started Building wheel for pyodbc (setup.py): finished with status 'error' ERROR: Command errored out with exit status 1: command: /usr/local/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-kfqrr62v/pyodbc/setup.py'"'"'; __file__='"'"'/tmp/pip-install-kfqrr62v/pyodbc/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-tiofv2rv cwd: /tmp/pip-install-kfqrr62v/pyodbc/ Complete output (14 lines): running bdist_wheel running build running build_ext building 'pyodbc' extension creating build creating build/temp.linux-x86_64-3.8 creating build/temp.linux-x86_64-3.8/src … -
Django: Dynamically generate ChoiceField values from another model object
I want to implement a Django form with dynamically generated ChoiceField options. In my forms.py I have extended the Django forms as follows: class OptionForm(forms.Form): choicefield= forms.ChoiceField(choices= []) def __init__(self, *args, **kwargs): super(OptionForm, self).__init__(*args, **kwargs) self.fields['choicefield'].choices = forms.ChoiceField(choices= get_choice()) In my views.py I have defined the following (relevant) methods: from .forms import OptionForm def get_choice(): return # like this [(q.optionA, q.optionA), (q.optionB, q.optionB), (q.optionC, q.optionC), (q.optionD, q.optionD)] # how can I pass q to this __init__ method class OptionForm(forms.Form): options= forms.ChoiceField(choices= []) def __init__(self, *args, **kwargs): super(OptionForm, self).__init__(*args, **kwargs) self.fields['options'].choices = get_choice() def viewtest(request, test_pk): # get the test object containing all the questions # each question contains four options using which I want to generate ChoiceField options corresponding to each question # each option is available as q.optionA, q.optionB q.optionC & q.optionD test= get_object_or_404(Test, pk= test_pk) options= [] for q in test.questions.all(): opform= OptionForm() # how do I pass q.optionA, q.optionB q.optionC & q.optionD here to dynamically provide ChoiceField options? options.append(opform) return render(request, 'tests/test.html', {'test': test, 'options': options}) -
match everyhting after domain name in url django
I want to write a pattern matching for URL in django to match everything after the domain name. I've been on it for hours now but couldn't find the solution. For eg: https://example.com/dsfdsfsdf , output : dsfdsfsdf https://example.com/b?node=162250&pf_rd_r=SYPPX3PERB7N , output : b?node=162250&pf_rd_r=SYPPX3PERB7N Domain Name can also be localhost:8000(for testing on local system) https://localhost:8000/dsfdsfsdf , output : dsfdsfsdf https://localhost:8000/b?node=162250&pf_rd_r=SYPPX3PERB7N , output : b?node=162250&pf_rd_r=SYPPX3PERB7N It doesnt matter what is given after the domain name. I want to match everything that comes after domain in urls.py and execute my view function. I am able to solve this using findall, but unable to do the same in Django urls.py file. -
Passing django variable into php and JavaScript files [closed]
I know that I can type: <h1> result is: {{res}}</h1> But how to use {{res}} in php?? Can I type: echo {{res}} ? How can i use {{res}} in JavaScript function alert () as well? Is there any modification required in view and url pages??? Thank you very much in advance.