Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
change account authenticate method from username to email
I want to change login method from username to email. urls.py from rest_framework_jwt.views import obtain_jwt_token,refresh_jwt_token urlpatterns = [ url(r'^login/$', obtain_jwt_token), url(r'^tokenRefresh/', refresh_jwt_token) ] setting.py ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False I have used above solution but not working for me. can you please help!! -
replace spaces with % in django or python app
im having a hard time fixing this one. i have a search function that will look for campaign name or campaign launcher name. for example if a user look for all campaigns launched by john doe. i want to enclose all spaces with '%' (%john%doe%) expected. campaigns = Campaign.objects.filter(title(re.sub('/\s/g ', '%', search)) | launcher(re.sub('/\s/g ', '%', search))) i also tried campaigns = Campaign.objects.filter(title(re.sub(' ', '%', search)) | launcher(re.sub(' ', '%', search))) but my code is not doing the right thing. im getting `camp`.`name` LIKE '%john doe%' OR `user`.`name` LIKE '%john doe%' and if i did the search.replace(" ", "%") im getting `camp`.`name` LIKE '%john\\%doe%' OR `user`.`name` LIKE '%john\\%doe%' any help will be much appreciated. -
Django: QuerySet with group of same entries
My goal is to show for a specific survey the Top 10 "Entities" per question ordered from high to low by salience. A survey has several questions. And each question has several answers. Each answer can have several entities (sometimes the same name (CharField), sometimes different names). I thought the following final result makes sense: [ 5: # question.pk [ { 'name': 'Leonardo Di Caprio', 'count': 4, # E.g. answer__pk = 1, answer__pk = 1, answer__pk = 2, answer__pk = 3. Leonardo Di Caprio was mentioned twice in answer_pk 1 and therefore has entries. 'salience': 3.434 # Sum of all 4 entities }, { 'name': 'titanic', 'count': 5, 'salience': 1.12 }, { 'name': 'music', 'count': 3, 'salience': 1.12 } ], 3: # question.pk [ { 'name': 'Leonardo Di Caprio', 'count': 5, 'salience': 1.5 }, { 'name': 'titanic', 'count': 4, 'salience': 1.12 }, { 'name': 'music', 'count': 2, 'salience': 1.12 } ], ] Now I am struggling to write the right QuerySet for my desired outcome. Anyone here who can help me with it? I came to the point that I probably have to use .values() and .annotate(). But my results are quite far away from what my goal ist. Here … -
how to write views for models and display in templates
I am new Django. created models and i want to display those models in html.please help me in writing views and templates this is the models class Author(models.Model): author_name=models.CharField(max_length=300) def __str__(self): return self.author_name class Events(models.Model): event_author=models.ManyToManyField(Author) event_title=models.CharField(max_length=300) event_title_image = models.ImageField(upload_to='images/', blank=True, null=False) event_description=models.TextField(blank = True) event_image_description = models.ImageField(upload_to='images/', blank=True, null=True) event_release_date = models.DateField(null="false") def __str__(self): return self.event_title def publish(self): self.event_release_date = timezone.now() self.save() this is are the URLS def Event(request): return render(request, 'polls/events.html', {}) please help me out from this and how to write views from models -
Django: Module not Found on Azure App Service - Azure DevOps CD
I am looking to set up a simple Django application on Azure App Service (Linux OS) by running an Azure Devops Build and Release pipeline. The application builds and creates a release without a problem. However when the application has been released it runs into runtime errors. 2019-10-15T09:48:16.161816610Z ModuleNotFoundError: No module named 'django' I run pip3 install -r requirements.txt as part of the bash post deployment script, and requirements.txt contains Django but it claims the requirement is already satisfied. Or if I bash into the App Service and run the same command it get the same message with the requirements already being satisfied. Therefore my question is, why am I receiving a ModuleNotFoundError? -
get data first table from middle table
I want to display a series of books as a subset of a book model class Book(models.Model): rate_book = models.ManyToManyField("Book", blank=True) view book_rete = Book.rate_book.through.objects.filter( from_book_id=book_id).select_related() I need books details of books to show how I have to join between tow tabel -
Django-allauth URL Returns callback error for github despite correct url
I am trying to implement all-auth using Github in my django project. I have set the callback url as per this tutorial. So far, even if the login page for github shows up, it doesn't call back properly and I get this error in the url http://127.0.0.1:8000/accounts/github/login/callback/?error=redirect_uri_mismatch&error_description=The+redirect_uri+MUST+match+the+registered+callback+URL+for+this+application.&error_uri=https%3A%2F%2Fdeveloper.github.com%2Fapps%2Fmanaging-oauth-apps%2Ftroubleshooting-authorization-request-errors%2F%23redirect-uri-mismatch&state=exDbVJKNYzUI This is the github repo of the project. http://127.0.0.1:8000/accounts/github/login/callback/ is my authorization callback url set as per the tutorial. Any insight to why the callback url is not working is welcome. Thanks. -
Problem with queries ith Q object ('works' but not all the time)
I use Q object in a search input area I have many field to test in the search area so I use OR (|) in my query Sometime it works, sometimes not I mean, I test search on a field -> it work I had new field in the query and it does'nt work anymore... I check my code go back and test again but i do not understand what is wrong @login_required def liste_participantes(request): """ A view to list participants. """ liste_existe = True if request.POST: ide = request.POST.get('ide', False) try: # Participante.objects.get(pat_ide_prn_cse=ide) Participante.objects.get( Q(pat_ide_prn_cse=ide) | Q(pat_nom=ide) | Q(pat_pre=ide) | Q(pat_pti_nom_001=ide) | Q(pat_pti_nom_002=ide) | Q(pat_nai_dat=ide) ) except: liste_existe = False else: # participantes = Participante.objects.filter(pat_ide_prn_cse=ide) participantes = Participante.objects.filter( Q(pat_ide_prn_cse=ide) | Q(pat_nom=ide) | Q(pat_pre=ide) | Q(pat_pti_nom_001=ide) | Q(pat_pti_nom_002=ide) | Q(pat_nai_dat=ide) ) else: participantes = Participante.objects.all() return render(request, 'participante/liste_participantes.html', locals()) none of the fields works but if I suppress the last field (Q(pat_nai_dat=ide) and run again all fields works !!! -
Use date range in query filter
I have an HTML form which returns me two dates in a format like this: 2019-10-15. When I checked the type() of the date return it came out to be "str" how can I use this string in my Django query? Code: start = request.POST['from'] end = request.POST['to'] foo = bar.objects.filter(dispatch_date = ??) -
add url for category with django 2
I'm working on my blog page basically the blog has category for split the same posts, for this I made a class for category and made a relationship between the category and my post class like this : class Category(models.Model): name = models.CharField(max_length=256) def __str__(self): return self.name class Post(models.Model): image = models.ImageField(upload_to='Posts_image') title = models.CharField(max_length=256) configure_slug = models.CharField(max_length=512) slug = models.SlugField(max_length=512,null=True,blank=True) content = HTMLField('Content') date = models.DateTimeField(auto_now_add=True) categories = models.ManyToManyField(Category) tags = TaggableManager() publish = models.BooleanField(default=False) def __str__(self): return self.title after this I made some code for create a slug for the title of category because I want link the posts that has same title but I can't found a solution I want you help me for this problem and learn or help me what can i do for create a slug or Link the same posts together This is my views.py def category_count(): queryset = Post.objects.values('categories__name')/. annotate(Count('categories__name')) return queryset def blog(request, tag_slug=None): category = category_count() post = Post.objects.filter(publish=True) tag = None if tag_slug: tag = get_object_or_404(Tag, slug=tag_slug) post = post.filter(tags__in=[tag]) paginator = Paginator(post, 2) page = request.GET.get('page') try : posts = paginator.page(page) except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) context = { 'posts':posts, 'page':page, 'tag': tag, … -
django Serializer object has no attribute
I don't have much experience in python but got task to write server in django which will handle api requestes I sent from front part, the thing is that eventho GET works well, POST still throw some errors. If I add new Logo via admin panel, it works, when I try to do so via postman it throw this error: Traceback (most recent call last): File "/home/user/.local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/user/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/user/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/user/.local/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/user/.local/lib/python3.6/site-packages/rest_framework/viewsets.py", line 114, in view return self.dispatch(request, *args, **kwargs) File "/home/user/.local/lib/python3.6/site-packages/rest_framework/views.py", line 505, in dispatch response = self.handle_exception(exc) File "/home/user/.local/lib/python3.6/site-packages/rest_framework/views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "/home/user/.local/lib/python3.6/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception raise exc File "/home/user/.local/lib/python3.6/site-packages/rest_framework/views.py", line 502, in dispatch response = handler(request, *args, **kwargs) AttributeError: 'LogoSerializer' object has no attribute 'name' my code: class LogoViewSet(viewsets.ViewSet): def list(self, request): queryset = Logo.objects.all() serializer_class = LogoSerializer(queryset, many=True) return Response(serializer_class.data) def create(self, request): serializer_class = LogoSerializer(data=request.data) bg = Logo( name=serializer_class.name, thumb=serializer_class.thumb, thumbL=serializer_class.thumbL, dataL=serializer_class.dataL, ) bg.save() return Response(bg) and Serializer: class LogoSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Logo fields = … -
Heroku not correctly installing tulipy from requirements.txt
When deploying my django app on Heroku, I have a ModuleNotFoundError happening when it tries to install tulipy package from requirements with pip. It says No module named 'numpy' when importing numpy but it is the first package on the requirements.txt list so it should be installed first. The app is deploying fine without tulipy package. I tried calling another requirements file with -r ./requirements-prior.txt containing only numpy but it doesn't work. How can I force Heroku to install numpy before tulipy? Full error message Thanks -
Combination of foreigh keys and pre-defined values as choices for Django model field
A ForeignKey field (let's call it tc) in one of models (let's call it Venue) stores reference to terms and conditions model (let's call it TC) where different versions of document are stored. This way every Venue can select one of versions of tc that suits their needs. class Venue(models.Model): tc = models.ForeignKey( 'my_app.TC', on_delete=models.CASCADE, help_text=_('Version of tc used by this venue') ) Records in TC table are added frequently so if given Venue wants to use latest version of document someone needs to manually update it via django admin. This is a poorly though solution because there are dozens of Venue records in database and they all have different approaches to tc usage: some of venues want tc to be updated automatically to latest version some want/need to bump up their tc version manually some venues do not use tc at all The goal that needs to be achieved is having 2 default options for each Venue: 1. ---- (blank: venue does not use any `tc`) 2. Latest (venue automatically uses latest version of `tc` available` And unspecified number of available tc options (for example foreign keys to TC model) 1. v1.0.0 2. v2.1.0 3. ... So list of … -
How to redirect users after password change django 2?
I have a password change view in my project. Instead of the default django password_change_done/done/ I want users to be redirected to my custom page eg homepage. For login we need to edit the settings and add LOGIN_REDIRECT_URL. Is there anything like PASSWORD_CHANGE_REDIRECT_URL that we can specify in our settings.py file. This is my URL patterns urlpatterns = [ path('admin/', admin.site.urls), path('', include('mainapp.urls')), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name="login"), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name="logout"), path('password_reset/', auth_views.PasswordResetView.as_view(template_name='users/password_reset.html'), name="password_reset"), path('password_reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='users/password_reset_done.html'), name="password_reset_done"), path('password_reset_confirm/<uidb64>/<token>', auth_views.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html'), name="password_reset_confirm"), path('password_reset_complete/', auth_views.PasswordResetCompleteView.as_view(template_name='users/password_reset_complete.html'), name="password_reset_complete"), path('change_password/', auth_views.PasswordChangeView.as_view(template_name='users/change_password.html'), name="password_change"), path('password_change_done/done/', auth_views.PasswordChangeDoneView.as_view(template_name='users/password_change_done.html'), name="password_change_done"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I want the users to be redirected to custom view and not the default one. Any help would be highly appreciated. -
I want to add dependent dropdown in django, how to achieve it
I want to create multiple dependent dropdowns in Django. eg. list1 = ['home','school','hospital'], home = ['mixer','grinder','cooker'] #sublist of 'home' element of list1 and so on.. so if user selects the 'home' option my next dropdown which is item list of the selected option should show all related items to 'home' without refreshing the page. how can I achieve this in Django? -
Django application failing randomly after updating python and django
here is my problem: I have a Django application that I am trying to update from python2.7 / Django 1.8 to python3.7 / Django 2.1 In my browser, I can access the django admin with no problem, but when I try to access the website it often fails : in Google Chrome, "This site can’t be reached", with either ERR_CONNECTION_RESET or ERR_SOCKET_NOT_CONNECTED. It does not always fail though. There is apparently no pattern : sometimes it loads well, then I refresh and it does not, then I refresh again and it does load well again... The stack : python3.7, Django2.1, nginx, docker, redis It would be great if you had any clue -
Accessing specific element called from REST-API
I am building a login, registration, and profile page. When i log in everything works fine. My website gets redirected to the Profile-page where it should be. On my profile page there are 2 Select components that i have built using react-bootstrap. What i want to do is to have as options in my first Select component category names of each role in my database. I don't know what i am doing really. I have tried creating object with id, categoryname, and then mapping through it, and passing those properties in options, but it did not work. "Select component that i use later on." export const Select = props => { return( <Form.Group controlId={props.name} style={props.style}> <Form.Label>{props.label}</Form.Label> <Form.Control {...props} as="select" > {props.options.map(el => ( <option key={el.value} value={el.value}>{el.label}</option> ))} </Form.Control> </Form.Group> )}; "My actions for posting, and getting the role" export const RoleStart = (role_info) => async dispatch =>{ dispatch({ type: types.ROLE_REQUEST}); const bodyFormData = new FormData(); bodyFormData.set("Info about the role", role_info); const response = await apiCon.post( '/roles/', bodyFormData, ).then(res =>{ dispatch(RoleSuccess(res.data)); console.log("ROLELES", res.data); }) .catch(err => { dispatch(RoleFail("Role could not be created. "+err)); }) } export const RoleSuccess = (role_info) => async dispatch =>{ const msg="Role was created"; const payload = … -
docker-compose build requirements.txt not update
I would to use docker for publish my django project. I create a docker-compose.yml file, a .dockerignore and a Dockerfile like this one: FROM python:3.6-alpine RUN apk add --no-cache gcc musl-dev linux-headers RUN apk update && apk add postgresql-dev gcc python3-dev musl-dev RUN mkdir /code COPY requirements.txt /code WORKDIR /code RUN pip install --upgrade pip RUN pip install -r requirements.txt COPY . . CMD ["python", "manage.py", "runserver", "127.0.0.1:8000"] well, i run first time and i get an error installing a package contained into my requirements.txt file, at this point i remove the packages from my file and run: docker-compose down docker-compose build --no-cache but when procedure execute pip install -r requirements.txt there is again the package in file that execute...how can i clear the cache and use my new saved requirements.txt file? so many thanks in advance -
Using django-elasticsearch-dsl with AWS ElasticSearch - raise HTTP_EXCEPTIONS.get(status_code, TransportError)
I'm trying to convert up a Django application using django-elasticsearch-dsl and a elasticsearch server to using AWS ElasticSearch which I am deploying using ElsaticBeanStalk When I use 03_elasticsearch: command: "source /opt/python/run/venv/bin/activate && ./src/manage.py search_index --rebuild -f" I get this error Traceback (most recent call last): File "./src/manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django_elasticsearch_dsl/management/commands/search_index.py", line 134, in handle self._rebuild(models, options) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django_elasticsearch_dsl/management/commands/search_index.py", line 114, in _rebuild self._create(models, options) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django_elasticsearch_dsl/management/commands/search_index.py", line 84, in _create index.create() File "/opt/python/run/venv/local/lib/python3.6/site-packages/elasticsearch_dsl/index.py", line 102, in create self.connection.indices.create(index=self._name, body=self.to_dict(), **kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/elasticsearch/client/utils.py", line 69, in _wrapped return func(*args, params=params, **kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/elasticsearch/client/indices.py", line 110, in create params=params, body=body) File "/opt/python/run/venv/local/lib/python3.6/site-packages/elasticsearch/transport.py", line 327, in perform_request status, headers, data = connection.perform_request(method, url, params, body, ignore=ignore, timeout=timeout) File "/opt/python/run/venv/local/lib/python3.6/site-packages/elasticsearch/connection/http_urllib3.py", line 110, in perform_request self._raise_error(response.status, raw_data) File "/opt/python/run/venv/local/lib/python3.6/site-packages/elasticsearch/connection/base.py", line 114, in _raise_error raise HTTP_EXCEPTIONS.get(status_code, TransportError)(status_code, error_message, additional_info) elasticsearch.exceptions.TransportError: <exception str() failed> (ElasticBeanstalk::ExternalInvocationError) I do not understand what this is telling me - can anyone advise? -
Manage.py is not working or even giving any type of error
I am new in Django and I want to launch my portfolio site on my vps. the problem is none of my manage.py commands are working and I dont even get an arror I press enter and a new commands line comes.... I restarted my vps and searched on internet but cant find a sloution. all commands are working on my local computer but not in my vps. please help me. thanks -
vars_for_template() missing 1 required positional argument: 'inputs'
I want to write a small program in which people should enter a guess. If the guess is within the correct range, they will get one euro. Based on the internet search, I already found out that I am not calling the functions correctly. However, I can't find the error. This is my page.py file: class Guess(Page): form_model = 'player' form_fields = ['guess'] def vars_for_template(self,inputs): self.player.cumulative_guthaben = sum([p.guthaben for p in self.player.in_all_rounds()]) if 11.25 <= inputs["guess"] <= 13.75: self.player.cumulative_guthaben = self.player.cumulative_guthaben + 1 if not 11.25 <= inputs["guess"] <= 13.75: self.player.cumulative_guthaben = self.player.cumulative_guthaben In another file called models.py, I defined the guess field as guess = models.FloatField(label="Your Guess:") The argument of def vars_for_template is colored in yellow and says: Signature of 'Guess.vars_for_template()' does not match signature of base method in Class Page. But what does that mean? -
Call django function on HTML button
I want to call a django function on my Proceed button and pass the selected value to that function, how can I do that ? Here's the form: <select id="the-id"> {% for i in z %} <option value="{{ i }}">{{ i }}</option> {% endfor %} <form method="post" novalidate> {% csrf_token %} <a class="btn btn-outline-secondary" role="button">Proceed</a> <a href="{% url 'employee:products_table' %}" class="btn btn-outline- secondary" role="button">Nevermind</a> </form> </select> views.py def warehouse_details(request): queryset = AllotmentDocket.objects.filter(send_from_warehouse = #to be fetched from the form) print("queryset is ", queryset) return render(request, 'packsapp/employee/allotwarehousedetails.html', {'query': queryset}) -
Gunicorn is failing with OSError: [Errno 107] Transport endpoint is not connected
I was facing this issue while running with gunicorn version 19.9.0 Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/base_async.py", line 66, in handle six.reraise(*sys.exc_info()) File "/usr/local/lib/python3.7/site-packages/gunicorn/six.py", line 625, in reraise raise value File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/base_async.py", line 49, in handle req = six.next(parser) File "/usr/local/lib/python3.7/site-packages/gunicorn/http/parser.py", line 41, in __next__ self.mesg = self.mesg_class(self.cfg, self.unreader, self.req_count) File "/usr/local/lib/python3.7/site-packages/gunicorn/http/message.py", line 181, in __init__ super(Request, self).__init__(cfg, unreader) File "/usr/local/lib/python3.7/site-packages/gunicorn/http/message.py", line 54, in __init__ unused = self.parse(self.unreader) File "/usr/local/lib/python3.7/site-packages/gunicorn/http/message.py", line 230, in parse self.headers = self.parse_headers(data[:idx]) File "/usr/local/lib/python3.7/site-packages/gunicorn/http/message.py", line 74, in parse_headers remote_addr = self.unreader.sock.getpeername() OSError: [Errno 107] Transport endpoint is not connected``` -
Private static files on AWS with django app
I am running a django application and would like to host my static files (which includes my documentation with sphinx) on AWS. I configured everything and it works fine. It only works though if my bucket has public permissions. I do not want my static files be accessible to the public though. Yet I think that static files must be public on AWS. Is there any way of restricting the access to the bucket and still use it to serve my static files? I know that I can restrict the traffic to certain IP addresses, but since I am running my app on Heroku I don't have a fixed IP but DNS. I can't believe there is no way of hosting private static files. Or maybe do I need a different provider than AWS? Help is highly appreciate, I am stuck with this since forever. Thanks so much in advance... -
How to pass a value from one class of django models to another?
I'm trying to get the name of the table that I have to download and get the fields from that table in my next form. In order to get the fields I have to first pass the name of the table that I want to download then it loads the data from that field. But I don't know how that works. from django.db import models from multiselectfield import MultiSelectField from survey_a0 import details, analysis #Backend coding module import ast class HomeForm3(models.Model): Survey= models.CharField(choices=[('A','A'), ('B','B')],default='A') def __str__(self): return self.title class HomeForm1(models.Model): details.loadData(Survey)#<===== *** I need to pass the variable from above here *** global f1 f1=analysis.getQuestion(in_json=False) d=list(f1.keys()) for k in d: q=list(f1[k].keys()) q.sort() choices=tuple(map(lambda f: (f,f),q)) locals()[k]=MultiSelectField(max_length=1000,choices=choices,blank=True) def __str__(self): return self.title