Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix trouble with urls better django
I have a section residential interiors on the site, so the typical url looks like this https://caparolcenterspb.ru/decision/livingrooms/kitchen/provans/ (room and style) However different rooms may have the same styles and when searching for styles in views.py it may output several styles and an error views.py selected_room = Room.objects.get(slug=rmslg) style = Style.objects.get(slug=stslg) When you try to replace slug with different styles depending on the room(for example, provans_kitchen), an error occurs in the template(just put provans by default will not work) residentialInteriors.html {% for room in all_rooms %} <li class="menu__item menu__item_interiors"><a href="{% url 'decision:style' rmslg=room.slug stslg='provans' %}">{{ room.name }}</a></li> {% endfor %} I have 2 solution ideas(preferably 2): either change stslg in template by default to 'provans_' + str(room. slug), but this line does not work(especially not the fact that provans will be everywhere) either search for style in views.py not only for stslg, but also for rmslg, but for this in the style model, you need to create a room field inherited from the room model, which also does not work for me, since Room is declared further than Style models.py class Style(models.Model): name = models.CharField(max_length=30) full_name = models.CharField(max_length=50) slug = models.SlugField() img = models.ImageField(upload_to='img/') walls = models.TextField() floor = models.TextField() roof … -
Exception Value: Invalid HTTP_HOST header: 'products_web:8001'. The domain name provided is not valid according to RFC 1034/1035
Here docker creates containers :- products, orders, email, nginx and postgres. enter image description here I have to get product details from orders service, for that i used requests pipe link response = requests.get("http://products_web:8001/products/fetch/?prod_id=%s" % product).json() when i execute, getting response in html format defining error as Exception Value: Invalid HTTP_HOST header: 'products_web:8001'. The domain name provided is not valid according to RFC 1034/1035. following is the docker-compose.yaml version: '2' services: products_web: build: ./products command: bash -c "python3 ./products/manage.py makemigrations && python3 ./products/manage.py migrate && python3 ./products/manage.py runserver 0.0.0.0:8001" volumes: - .:/code ports: - "8001:8001" restart: always depends_on: - datab links: - datab emails_web: build: ./emails command: bash -c "python3 ./emails/manage.py makemigrations && python3 ./emails/manage.py migrate && python3 ./emails/manage.py runserver 0.0.0.0:8002" volumes: - .:/code ports: - "8002:8002" restart: always depends_on: - datab links: - datab orders_web: build: ./orders command: bash -c "python3 ./orders/manage.py makemigrations && python3 ./orders/manage.py migrate && python3 ./orders/manage.py runserver 0.0.0.0:8003" volumes: - .:/code ports: - "8003:8003" restart: always depends_on: - datab links: - datab stdin_open: true tty: true datab: image: postgres environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres nginx: image: nginx:latest build: ./web ports: - "8084:80" links: - products_web - orders_web - emails_web depends_on: - products_web - … -
Django. SQLite. How to improve query speed/code and sorting speed within a list
I wrote a piece of a very ineffective, but working code, which is running approx. 24 hours to complete the task. I have a list choices = ["qwert", ... "ABCDE", ...], length of the list is 2...1000. I am making changes in the SQLite table as follows: first bad code: def update_records_in_bigtable(uid_br_next, choices): for k in choices: q = BigTable.objects.all().filter(Q(field1__exact=k) | Q(field1__exac2=k) | Q(field3__exact=k) & Q(field3=0) ).update(uid_nr=uid_nr_next) second bad code: def add_records_to_crossreftable(choices, obj): for k in choices: try: x = CrossRefTable.objects.create(field1=k, uid_nr_foreign=obj) except: x = DuplicatesTable.objects.create(field1=k) third bad code: def get_next_list(k): choices=list(BigTable.objects.all().filter(Q(field1__exact=k) | Q(field2__exact=k) ).values_list('field1', 'field2', 'field3', ) ) choice=[] for ch in choices: ch=set(ch) # remove same members if "" in ch: ch.remove("") # remove empty members if "ABC" in ch: ch.remove("ABC") # remove special member choice=choice + list(ch) choice=set(choice) return list(choice) Please help to improve. Thank you -
How to access and set Environment Variables for Django in production (Nginx and Gunicorn)
I am trying to set Environment Variables for a Nginx And Gunicorn Served Django Project on Ubuntu. The variables are set for the Ubuntu user and i am able to see the value using printenv VAR_EMAIL. But when i use them django settings it is not working , using them as os.environ['VAR_EMAIL'],This doesn't get the value of the variable in production and server doesn't work. However this works on Development side. Please provide me some guidance on how to accomplish this. -
how to delete duplicate entries by same user in django?
actually after submitting a form if the page is reloaded again the form is again getting submitted . So i want to delete duplicate entries from my form database. Help will be appriciated . Thanks in advance . Keep coding ,Stay sweet ... -
Django test TransactionTestCase execute before sql request is done
I'm running a test to check if my bulk inserts work correctly. The process_products_data method formats the input data, create some sql requests as a string then connects to the db and execute them. When I run the test, it fails and succeed randomly. I displayed the data stored in db in the teardown method and I could observe that when the test fails, the db is not filled correctly, like if the process_products_data method didn't trigger or is in the middle of it's job. Any idea how to force the test to wait for the process_products_data method to be over? class TestCaseCreation(TransactionTestCase): fixtures = ['test_1'] products = [ { 'internal_code': '403273', '_type': 'dict', 'description': 'Abc', 'brand': 'my brand', 'creation_date': 1587543189737.0, 'name': 'my name' } ] maxDiff = None def setUp(self): shop = Shop.objects.get(pk=1) process_products_data(self.products, shop) def test_creation(self): self.assertEqual(...) self.assertEqual(...) -
TypeError at /recomm/ __init__() got an unexpected keyword argument 'movie'
I got an error while getting the movies from the function it shows mistakes movies got an unexpected keyword argument movie File "E:\FinalYearProject\movierecommendationsystem\myapps\views.py" in recomm 106. return HttpResponse('recommend.html', movie=movie, r=r, t='s') Exception Type: TypeError at /recomm/ Exception Value: __init__() got an unexpected keyword argument 'movie' Here I got error while getting the recommending movie def recomm(request): if request.method == 'GET': movie = request.GET['movie'] r = recommendation('movie') movie = movie.upper() if type(r) == type('string'): return HttpResponse('recommend.html', movie=movie, r=r, t='s') else: return HttpResponse('recommend.html', movie=movie, r=r, t='l') my form for getting movies <form action="{% url 'recomm' %}" method="GET"> -
Implement SSO on a Django App running in iAPC
I deployed my first Django app on the iAPC and so far it's running fine. Now I'm trying to implement SSO for it. I already created a Corproot Identity v2 Service instance and linked it to my app. So I see that the environment variable VCAP_SERVICES containing all needed credentials is available. My problem is how to integrate this information in Django. If I look at the provided Java example here I understand that I have to configure an OAuth2 client with the VCAP_CREDENTIALS and should receive some kind of client token when the callback url in my app is called. Using this client token it should be possible to access the detail information of the logged-in user. But it's still unclear for me how to code all this details in Django. I already installed the oic Python package and am trying to find a way to implement SSO using it. Any concrete help here would be very appreciated. Thanks, Alejandro -
How to do user authentication in Django using MySQL Database? [closed]
I am trying to create a website by using Django. For the database, I decided to use MySQL. I was able to connect my Django project with MySQL. Also to do Sign up, receive user information, and save it to the database. But when I moved on to Login part I stuck here. I did much research and tried many things nothing works. I did Login previously with SQLite3, and it was pretty easy. Now as I change the database I want to be able to login but have no idea how to do it with MySQL using Django. I attached the model.py and signup view to give more details. Is anyone able to show me Django code on how to login using data in my database?(which saved using phpmyadmin) -
Make navbar active on url and any url's following from it
I am trying to make my navbar element active if the user is on the current url and any url's leading from it. For example, I want the navbar to be active on: http://example.com/products AND http://example.com/products/discounted-items I was using this: {% if url_name == 'products' %}active{% endif %} and was very happy till I realised that once I progress from the 'products' page to 'products/discounted-items' it would cease being active. Is there a clean way to do this in django? Thank you very much. -
DRF local variable 'msg_data' referenced before assignment
This is my serializers.py class UserProfileSerializer(serializers.ModelSerializer): img_count = serializers.SerializerMethodField('get_img_count') post_count = serializers.SerializerMethodField('get_post_count') msg_count = serializers.SerializerMethodField('get_msg_count') class Meta: model = User fields = ('id', 'username', 'img_count', 'post_count', 'msg_count') def get_img_count(self, obj): try: img_data = ImgSerializer(Img.objects.filter(author=obj.id), many=True) except img_data.DoesNotExist: return 0 return img_data def get_post_count(self, obj): try: post_data = PostSerializer(Post.objects.filter(author=obj.id), many=True) except post_data.DoesNotExist: return 0 return post_data def get_msg_count(self, obj): try: msg_data = Smessage(Msg.objects.filter(author=obj.id), many=True) except msg_data.DoesNotExist: return 0 return msg_data This is my views.py class UserProfile(APIView): permission_classes = [AllowAny] def get(self, request): query = User.objects.all() serializer = UserProfileSerializer(query, many=True) return Response(serializer.data) This is the Error Snippet I want to get this { "id": 9, "username": "emil@gmail.com", "img_count:3, "post_count":5, "msg_count":50, } also getting error after using img_count.count(). -
raised ConnectionResetError when i use set_password in ajax requests
I want to send ajax request named 'client password change' here is javascript code function sendmailConfirm() { var result = confirm("client(client@google.com) password will changed"); if (result == false) { event.preventDefault(); alert('canceled.'); } else { $.ajax({ 'url': '/change/password', 'method': 'GET', 'data': { 'email':'password-change@pass.com', }, 'success':function(event){ alert('success!'); } }) } }; and view.py is class ChangePW(TemplateView): def get(self, request): if request.is_ajax(): user = User.objects.get(email='password-change@pass.com') password = random_password_generate() user.set_password(password) user.is_active = False user.save() return JsonResponse({'status': 'success'}) i do runserver and i clicked the button but it raised error ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 59753) Traceback (most recent call last): File "/Users/hanminsoo/.pyenv/versions/3.7.1/lib/python3.7/socketserver.py", line 647, in process_request_thread self.finish_request(request, client_address) File "/Users/hanminsoo/.pyenv/versions/3.7.1/lib/python3.7/socketserver.py", line 357, in finish_request self.RequestHandlerClass(request, client_address, self) File "/Users/hanminsoo/.pyenv/versions/3.7.1/lib/python3.7/socketserver.py", line 717, in __init__ self.handle() File "/Users/hanminsoo/Desktop/issue/tving-ui/venv/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 174, in handle self.handle_one_request() File "/Users/hanminsoo/Desktop/issue/tving-ui/venv/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/Users/hanminsoo/.pyenv/versions/3.7.1/lib/python3.7/socket.py", line 589, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 54] Connection reset by peer ---------------------------------------- i cant understand when i remove user.set_password(password) it is working my django version is '3.0.4' and python version is '3.7.1' thank you :) -
Django, how to extract values list montly from DateField?
I have the following models: class Materiale(models.Model): sottocategoria = models.ForeignKey(Sottocategoria, on_delete=models.CASCADE, null=True) quantita=models.DecimalField(') prezzo=models.DecimalField() data=models.DateField(default="GG/MM/YYYY") I wanna calculate the value given by the following expressions PREZZO*QUANTIA in a monthly's view (in other words the total sum of PRZZO*QUANTITA of all items in a single month), but my code does not work: Monthly_views=Materiale.objects.filter(data__year='2020').values_list('month').annotate(totale_mensile=F(('quantita')*F('prezzo'))) -
How can I package a Django app with homebrew?
I'd like to package a Django + SQLite + JS-Frontend app with homebrew. Are there specifics to consider which are not obvious from the homebrew docs? -
DB level constraints to validate 1 field against another one in Django
Is it any way to use Django constraint in model (models.CheckConstraint class) in order to create a constraint to validate value of one field against another one? For example: class Season(models.Model): last_watched_episode = models.PositiveSmallIntegerField( null=True, ) number_of_episodes = models.PositiveSmallIntegerField( ) In this case I need to make a constraint that would raise an error in case value of the last_watched_episode field is greater then number_of_episodes field. 9 > 8 for example. Plus in case if last_watched_episode is Null(none) constrain should be omitted ( cant compare Null and int) I have model and serializer validators already but goal is to create DB level constraints. Way to create it with RAW SQL and custom migration is also possible but via DJANGO constraints would be preferable. Thank you. DB -postgres 12 -
celery .delay freezes for this task but runs for others
I am trying to send notifications using celery. @shared_task(name="send_notifs_to_devices_task") def send_notifs_to_devices_task(devices_ids, title, message, image=None, link=None): from pills_reminder.models import UserNotifications, UserDevice devices = UserDevice.objects.filter(id__in=devices_ids) for device in devices: UserNotifications.objects.create( uid=device.device_id, title=title, message=message, image=image, linksTo=link ) # TODO: to recieve image here device.send_notification(title=title, body=message, click_action=link) print('task to be done by celery') logger.info(f"successfully sent notifications to {len(devices)} devices") this works without .delay() >>> send_notifs_to_devices_task(devices, ... title=instance.title, ... message=instance.message, ... link=instance.link) {'multicast_ids': [4255826789468640174], 'success': 1, 'failure': 0, 'canonical_ids': 0, 'results': [{'message_id': 'https://updates.push.services.mozilla.com/m/gAAAAABepnOW1plHQRAB5kRMziPs47eXuzEFbJxR891Pps1Okyz_a-waK3jZ2IX3YehnDuuSut6WkVzEVoKODeOOkHFEf6teOyvVVatkjh3Du8UokRbLx8vC59_GbqeuS7wYxjtGGICXkrAK_xBaUjGbYaIII3nqXxGacLkcX2pWt2Ag6wGHmc3U3imzYx-3mde4zpncIVIb'}], 'topic_message_id': None} task to be done by celery {'multicast_ids': [7964723727637075692], 'success': 0, 'failure': 1, 'canonical_ids': 0, 'results': [{'error': 'NotRegistered'}], 'topic_message_id': None} task to be done by celery {'multicast_ids': [7140533530146400686], 'success': 0, 'failure': 1, 'canonical_ids': 0, 'results': [{'error': 'NotRegistered'}], 'topic_message_id': None} task to be done by celery {'multicast_ids': [5226660064264463708], 'success': 0, 'failure': 1, 'canonical_ids': 0, 'results': [{'error': 'InvalidRegistration'}], 'topic_message_id': None} but when i call this using .delay, it freezes. >>> send_notifs_to_devices_task.delay(devices, ... title=instance.title, ... message=instance.message, ... link=instance.link) Note, when i call another task such as add.delay(1,2), this works: >>> add.delay(1,2) <AsyncResult: 61b76768-73ef-4ca2-bbae-445ee528cafe> I don't have much knowledge of celery and i don't know what is wrong here? -
How to change lookup field in Model.viewset to other unique parameter in Django Rest Framework?
I am using Modelviewset in django rest framework. I want to change lookup field to email(unique) instead of id. I have tried adding lookup_field = 'email' inside my Schema viewset but it is not working. This is what i am getting { "detail": "Not found." } How do I resolve this. my Views.py: class SchemaViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet): queryset = models.Schema.objects.all() serializer_class = serializers.SchemaSerializer lookup_field = 'email' my models.py: class Schema(models.Model): """Database model for Schema """ name= models.TextField() version = models.TextField() email = models.EmailField(unique = True ) def __str__(self): return self.email my serializers.py: class SchemaSerializer(serializers.ModelSerializer): """Serializes Schema""" class Meta: model = models.Schema fields = ( 'id', 'name', 'version', 'email') -
Maintaining order of querylist
I have a query that looks like this: top_posts= Ranking.objects.all().order_by("-score").values("post") It gets the top posts ordered by score and then this query is executed: Posts.objects.filter(id__in=top_posts) However, the order_by score is thrown away when I run this query. How do I maintain the order of the score? -
Django: return translation text within views
I use translations in the templates. All messages are compiled and configured properly. However I would like to return a translated string directly from the view. How is this possible? from django.utils.translation import gettext as _ def MyView(request): return HttpResponse(_('FILE_TYPE_NOT_ALLOWED')) -
Integrating remote Django/Python applications on a WordPress hosted website
Let's say I have a website hosted on WordPress on an instance A. On an instance B (AWS EC or another cloud) there's a set of Python applications running, that are integrated with Django. These applications in result produce charts (e.g. Plotly) and in general serve requests trough WEB API. All these can be accessed after authenticating using Django user management subsystem. What I would like to do, is provide a means for authentication for accessing the EC hosted services on my WP hosted website. I assume that this should be relatively trivial, as I can simply add a small login form in an iframe, thus creating authorization token locally and this will be used whenever the WP website will contact EC instance e.g. for obtaining charts in few another iframes - please correct me if I'm wrong here. How can I inform the parent website (WP hosted) that it should for instance not display anything in an area where the iframes are located before authentication or when the session is lost (login in)? And then how to tell the parent website to place the iframes after authentication? -
Django elasticsearch unable to import modules
I am new to python and have some experience with Elasticsearch. I am trying to index my Model from Django to Elasticsearch. I have configured django-elasticsearch-dsl as per the official website. However, when I runserver, I got from elasticsearch.helpers import bulk, parallel_bulk ModuleNotFoundError: No module named 'elasticsearch.helpers' This happens only with my project which I worked for almost 2 weeks and have many models and data in it. I tried to create a new project and used 'django-elasticsearch-dsl' where I could connect to elasticsearch without any issues. I am not sure how to resolve this in my existing project/venv. -
How to load html template with parameters in Ajax callback (Django server)
When my user signs in, I want to check localStorage (using AJAX) to see if the user left any items in his basket. If yes, I want to render (or redirect) him to prebasket.html which I would normally do via return render(request, "pizza/prebasket.html", context) as per below in views.py: @login_required def prebasket(request): q_preselection = request.POST.dict() preselection = json.loads(q_preselection["preselection"]) items = [] # iterate thru menu items (ids) in user's selection for id in preselection: dish = Dish.objects.get(pk=id) item = { "id": dish.id, "name": dish.name, "size": dish.size, "price": ("%.2f" % float(dish.price)), "amount": preselection[id], "total": ("%.2f" % (int(preselection[id]) * float(dish.price))) } items.append(item) context = {"items": items} print(f"Context is: ", context) # comes out correctly on terminal return render(request, "pizza/prebasket.html", context) However, prebasket.html is not rendered. And I read that AJAX doesn't work like that, so I tried window.location.href in my JavaScript/AJAX (not using jQuery for now - sorry am new to all this...). But it's not working either - or at least I am not able to pass on the required parameters for the context needed in the url: var preselection = localStorage.getItem("preselection"); function previous_selection () { if (localStorage.getItem("preselection") != null) { const data = new FormData(); data.append("preselection", preselection); const request = … -
Testing an online payment Form using Django Keep getting Not Authenticated Error. Is it because of the Testing Credit Card numbers?
I am making a project for an online payment e-commerce I think I got everything right as am following a Tutorial Keep getting this Error: Not Authenticated Error I used the testing CC Numbers for testing purposes My question is the following codes correct and I'm getting fake Not Authenticated Error because they are testing Credit Card Numbers.? class PaymentView(View): def get(self, *args, **kwargs): # order return render(self.request, "payment.html") # `source` is obtained with Stripe.js; see https://stripe.com/docs/payments/accept-a-payment-charges#web-create-token def post(self, *args, **kwargs): order = Order.objects.get(user=self.request.user, ordered=False) token = self.request.POST.get('stripeToken') amount = int(order.get_total() * 100) try: charge = stripe.Charge.create( amount=amount, # cents currency="usd", source=token, ) # create payment payment = Payment() payment.stripe_charge_id = charge['id'] payment.user = self.request.user payment.amount = order.get_total() payment.save() # assign the payment to the order order.ordered = True order.payment = payment order.save() messages.success(self.request, "Your Order was Successful ! ") return redirect("/") except stripe.error.CardError as e: body = e.json_body err = body.get('error', {}) messages.error(self.request, f"{err.get('message')}") # Since it's a decline, stripe.error.CardError will be caught return redirect("/") except stripe.error.RateLimitError as e: # Too many requests made to the API too quickly messages.error(self.request, "Rate Limit Error") return redirect("/") except stripe.error.InvalidRequestError as e: # Invalid parameters were supplied to Stripe's API messages.error(self.request, "Invalid … -
Html content not showing up after if statement in Django
Im having some issues with my html content not showing up after putting in some {% if %} {% endif %} statements in my templates I have this snippet in my code where I display the checkout table if and only if the current user's username matches the one from my Order model. (order.customer_name has a foreign key that is set to the current users username) {% for order in latest_order %} {% if user.username == order.customer_name %} <tr> <td>{{ order.order_name }}</td> <td> <form method="post"> {% csrf_token %} <button type="submit" name="remove_quantity" value="{{ order.id }}" class="mr-3 btn btn-outline-info">-</button> {{ order.order_quantity }} <button type="submit" name="add_quantity" value="{{ order.id }}" class="ml-3 btn btn- outline-info">+</button> </form> </td> <td>${{ order.order_individual_price }}</td> <form method="post"> {% csrf_token %} <th><button type="submit" name="delete" value="{{ order.id }}" class="btn btn- danger">Delete Item</button></th> </form> </tr> {% endif %} {% endfor %}` I tried the following to see if it prints out the same username, which it does <h1>{{ user.username }}</h1> {% for order in latest_order %} <h1>{{ order.customer_name }}</h1> {% endfor %} Picture of the page with user.username and order.customername as h1 When I delete the if statement, this is what the website SHOULD look like Proper working table Im pretty sure I'm … -
Redirect From REST_API Response
I am using Angular and Django in my stack for a website, and after a user registers it emails them a link to activate their account. As of right now everything is working but the link takes the user to the Django rest framework page. I've been returning responses in my app like this data = {'success': True, 'message': 'An account has been activated.', 'response': {}} return Response(data, status=status.HTTP_201_CREATED) I am curious on how to redirect a user back to the login page which at the current moment would be a localhost page such as http://localhost:4200/#/authentication/login. From research I have found methods like return redirect('http://localhost:4200/#/authentication/login') but I am wanting to keep my responses consistent. Is there a way to redirect a user while still using the rest api Response object?