Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
I don't want drf ValidationError response to be textual. How to do that?
I'm using django rest framework. How to change the drf ValidationError detail not to be textual. for this: raise ValidationError(detail={"some_thing": True} response: { "something": "True" } expected response: { "something": true } -
How to generate one time password when creating user and send the same to users mail id in Django?
I am trying to send a random one-time password to the user when I create a new user and make him change the password when the user login for the first time. -
Creating models objects to load to load to database using text file in Django
I have a file full of english words and I am trying to add them to my postgres database via python shell. I am currently getting this error for the first word: ValueError: invalid literal for int() with base 10: 'AA' I think it is because a primary key isn't being considered because after migrating my models to postgres I see that the tables looks like this Table "public.boggle_word" Column | Type | Collation | Nullable | Default --------+-------------------------+-----------+----------+----------------------------------------- id | integer | | not null | nextval('boggle_word_id_seq'::regclass) word | character varying(1024) | | not null | and Python is complaining about int() models.py class Word(models.Model): word = models.CharField(max_length=1024) code snippet: from boggle.models import Word with open('files/dictionary.txt') as wfile: line = wfile.readline().strip() word = Word(word) word.save() -
Why does LDAPBackend.authenticate() store user info in custom user model in Django
I'm new to LDAP authentication and going through some of the StackOverflow questions and django-auth-ldap documentation I was able to implement LDAP authentication in my django project. I have a custom user model to store the user information. But my question here is that when we do authenticate using user_id and password why does authenticate store the user info in the custom user model. It also stores the hashed password. I have used LDAPBackend as my authentication backend in settings.py file like this AUTHENTICATION_BACKENDS = [ 'django_auth_ldap.backend.LDAPBackend' ] and for example when we perform the below operation auth = LDAPBackend() user = auth.authenticate(request, username=user_id, password=user_password) the user object is stored in the custom user model. My requirement is here not to store any user information when authenticate happens and not to store any password(be it hashed password). There are some pre-checks I need to do before storing it into user info to the custom user model. But LDAPBackend.authenticate() stores user info as it authenticates. Can anyone please help me on this and clarify what's going on here. Thanks -
How to navigate to sharefolder from view in Django?
I am trying to set button url, so it will open a folder. But there is still some problem. If I try to open URL on my own, or just paste it into file explorer, it works fine. Can someone please help me? I tried to set link on text, this is not working and nothing really happens. <a href="\\servername\Users\tom\cd\">Documentation</a> I also tried to set it on button. Now the button is clickable but will navigate to url in browser and will not open a folder. <button type="button" onclick="window.location.href = '\\server\Users\tom\cd\';">Navigate to folder</button> -
Django - upload just picture in model with a POST request
I would like to upload a profile picture with ajax. But even if I don´t send the image with ajax, it doesn´t work. I have the following code in my website: <form action="{% url 'update_profile_pic' %}" method="post"> {% csrf_token %} <input name="profilePic" type="file" accept="image/*"/> </form> The profilePic should be saved in the model: class UserProfile(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True, ) profilePic = ProcessedImageField( upload_to=generate_random_filename, processors=[ResizeToFill(150, 150)], format='JPEG', options={'quality': 60}, ) ... The url.py has the correct entry: ... path('update_profile_pic/', views.UpdateProfilePic.as_view(), name='update_profile_pic'), ... The form is like this: class ProfilePicForm(forms.ModelForm): class Meta: model = UserProfile fields = ('profilePic',) And the view should also be correct: class UpdateProfilePic(View): def post(self, request): form = ProfilePicForm(self.request.POST, self.request.FILES) if form.is_valid(): request.user.userprofile.profilePic = form.cleaned_data['profilePic'] request.user.userprofile.save() return JsonResponse({ image_url : request.user.userprofile.profilePic.url }) else: raise Http404(form.errors) But I always get the error "profilePic This field is required.", when I upload a picture. This error comes from the raise Http404(form.errors), so the form is not valid. When I look at the headers in the network tab in google chrome, it shows me this: csrfmiddlewaretoken: sbyaJ8J7COSdC0OUYr4p8ToaarjFrIniDKLT3Lr36PVeTUlc9MEafr77exYVvkXL profilePic: fr.cc38d01b0b77.gif What do I do wrong here? -
how to edit form which have single or multiple MultichoiceFields
I have a form with MultipleChoiceField. I am able to save the data correctly. Now, if a user wants to edit that form he/she should see already selected items in the dropdown along with remaining all the other option. I want this as a function-based view. eg. I have 5 products in the dropdown and at the time of form submission, I selected products 1 and 2. Now, when I click on edit I should be able to see products 1 and 2 selected along with the other 3 products as unselected.Just help me with the edit view of this form models.py class Product(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class DemoForm(models.Model): name = models.CharField(max_length=100) area = models.CharField(max_length=50) opted_products = models.ManyToManyField(Product,related_name='selected_products') def __str__(self): return self.name -
Unable to import 'django.http'pylint(import-error)
I am getting this problem in visual studio code 2019 i hope anyone can help to solve this problem this problem occuring with pip new version and django 2.2+ version and python latest 3.7 version for information please help to solve this problem Need Help -
Django. Revert previous page
I have an image_delete django-controller. I use it on several pages. I need that after deleting the image, the controller returns me to the previous page. but I get an error. what is the problem? How to fix it? views.py class ImageDelete(DeleteView): model = Picture template_name = 'adminapp/pet/pet_image_delete.html' @method_decorator(user_passes_test(lambda x: x.is_superuser)) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) def get_success_url(self): return HttpResponseRedirect(request.META.get('HTTP_REFERER')) urls.py path('delete/image/<int:pk>/', adminapp.ImageDelete.as_view(model=Picture), name='image_delete') Error -
Django Viewflow: Quick Start says to include formpack. What is a formpack?
I'm trying to use django viewflow to style some forms to keep a page consistently styled within an django app using materialize. In the viewflow documents, it recommends to include formpack javascript and styles into your database. What is a formpack and where could I find one for Materialize? -
How can i serialize Django View object?
I want to serialize my context data, but i get this error: TypeError: < tests.views.ExamView object at 0x7f8e18873668 > is not JSON serializable Here is my code: from django.template.loader import render_to_string context = self.get_context_data() html = render_to_string('difficult_test.html', context) if self.request.is_ajax(): return http.JsonResponse({"html":html, 'context':context}) return response -
Pycharm underlines absolute import, but it works fine
I have path server->api(folder), manage.py. Pycharm underlines my absolute import from api.views import create_user but it works! If i type like from server.api.views import create_user pycharm does not underline, but it doesn't work -
How to use django SESSION_COOKIE_AGE dynamically
In my django application I want to make this session cookie age dynamic.For example the default session is for two weeks in django .If i wanted to change into 1 weeks i can change by changing the setting in django but for this i need to go in the project settings.py file. Is there any solutions so that later after some time if i needed to change my SESSION_COOKIE_AGE i can change this with the admin panel butnot going in the projects settings.py file settings.py SESSION_COOKIE_AGE = 1209600 # I want to make this dynamic ANY HELP WOULD BE GREAT -
Django website for Subscriptions with paypal integration
Anyone help me on django with website for Subscription of two plans and integrate paypal payment gateway Thanks In advance -
(Django) Reverse dynamic urls with multiple arguments using Django Views
I am trying to pass two arguments to make a dynamic URL for each post of a blog app I'm working on. I get it to work if I pass the id, but don't know what's the syntax when using +1 arguments (nor if I'm doing things right). I want to make urls be 'post/<int:pk>/<slug:slug>/' but can only make it work with the id: 'post/<int:pk>/ Here's how I have it now: URLS.PY urlpatterns = [ ... path('post/<int:pk>/<slug:slug>/', PostDetailView.as_view(), name='post-detail'), path('post/new/', PostCreateView.as_view(), name='post-create'), path('post/<int:pk>/<slug:slug>/update/', PostUpdateView.as_view(), name='post-update'), path('post/<int:pk>/<slug:slug>/delete/', PostDeleteView.as_view(), name='post-delete'), ... ] VIEWS.PY class PostDetailView(DetailView): model = Post I am calling this in the template: <ul class="secondary-menu menu-list"> <li class="menu-item"><a href="{% url 'post-update' object.slug %}">Edit Post</a></li> <li class="red-button"><a href="{% url 'post-delete' object.slug %}">Delete</a></li> </ul> And have this function to retrieve the path to any specific instance in MODELS.py def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk, 'slug':slug}) I get the following error during template rendering Reverse for 'post-detail' with arguments '(1,)' not found. 1 pattern(s) tried: ['post/(?P<pk>[0-9]+)/(?P<slug>[-a-zA-Z0-9_]+)/$'] -
unable to apply search on multiple fields Django
def search(request): if request.method == 'POST': srch = request.POST['title'] if srch: match = Post.objects.filter(title__icontains=srch,email__icontains=srch) # match = Post.objects.annotate(search=SearchVector('title', 'email'),).filter(search=srch) if match: return render(request,'post/index.html',{'sr':match}) else: messages.add_message(request,messages.INFO,' No result found ') else: return redirect('post') return render(request,"post/index.html")