Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
DjangoCMS TypeError: from_db_value() missing 1 required positional argument: 'context' after upgrade to 3.7.2 w/ Django 3.0.1
I had a working DjangoCMS application running DjangoCMS 3.7.1 and Django 2.2, however after I just bumped the DjangoCMS version to 3.7.2 and with it, Django to 3.0.1, I am now getting a render error on a page that I have a simple list view. The site will load my custom account login page just fine, but once logged in, the listview breaks and displays this error: Traceback django.request ERROR 2020-04-26 21:15:16,809 log 461 140647593613056 Internal Server Error: /en/ Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 145, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 143, in _get_response response = response.render() File "/usr/local/lib/python3.8/site-packages/django/template/response.py", line 105, in render self.content = self.rendered_content File "/usr/local/lib/python3.8/site-packages/django/template/response.py", line 83, in rendered_content return template.render(context, self._request) File "/usr/local/lib/python3.8/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/usr/local/lib/python3.8/site-packages/django/template/base.py", line 171, in render return self._render(context) File "/usr/local/lib/python3.8/site-packages/django/test/utils.py", line 95, in instrumented_test_render return self.nodelist.render(context) File "/usr/local/lib/python3.8/site-packages/django/template/base.py", line 936, in render bit = node.render_annotated(context) File "/usr/local/lib/python3.8/site-packages/django/template/base.py", line 903, in render_annotated return self.render(context) File "/usr/local/lib/python3.8/site-packages/django/template/loader_tags.py", line 150, in render return compiled_parent._render(context) File "/usr/local/lib/python3.8/site-packages/django/test/utils.py", line 95, in instrumented_test_render return self.nodelist.render(context) File "/usr/local/lib/python3.8/site-packages/django/template/base.py", line 936, in render bit = node.render_annotated(context) File "/usr/local/lib/python3.8/site-packages/django/template/base.py", line 903, … -
how do i get the id immediately after inserting the data?
I hope the title is enough to understand what my problem is, I have this code in my views.py enroll = StudentsEnrollmentRecord( Student_Users=student,Old_Student=old,New_Student=new, Payment_Type=payment,ESC_Student=esc,Last_School_Attended=last,Address_OF_School_Attended=add, Education_Levels=educationlevel,School_Year=schoolyear,Courses=course,strands=strands,Student_Types=stype,GWA=gwa ) enroll.save() studentenrolment = StudentsEnrollmentRecord.objects.filter(Student_Users=enroll) return render(request, "print.html", {"studentenrolment":studentenrolment}) This is the error i get -
I do not get show data in the datatable angular 2.x
well, I make a web app with django and angular, the API is good but I'm newbie with angular and I don't understand that I'm wrong. import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class ListarPersonasService { public personas:any = null; constructor(private http: HttpClient) { } public obtenerPersonas() { const url = 'http://127.0.0.1:8000/api/v1.0/abogado/personas'; return this.http.get(url).subscribe( res => { this.personas = res; console.log(res); } ); } } this is my service, on the component the service to make the request is called and store the result in the variable datasource import { Component, OnInit } from '@angular/core'; import { ListarPersonasService } from "../servicios/listar-personas.service"; @Component({ selector: 'app-listar-personas', templateUrl: './listar-personas.component.html', styleUrls: ['./listar-personas.component.css'] }) export class ListarPersonasComponent implements OnInit { displayedColumns: string[] = ['documento','nombre', 'apellido']; dataSource : any; constructor(private listar:ListarPersonasService) { } ngOnInit() { this.dataSource = this.listar.obtenerPersonas() } } and here this html. <table mat-table [dataSource]="persona" class="mat-elevation-z8"> <ng-container matColumnDef="documento"> <th mat-header-cell *matHeaderCellDef>documento</th> <td mat-cell *matCellDef="let element">{{element.documento}}</td> </ng-container> <ng-container matColumnDef="nombre"> <th mat-header-cell *matHeaderCellDef> Nombre</th> <td mat-cell *matCellDef="let element"> {{element.nombre}}</td> </ng-container> <ng-container matColumnDef="apellido"> <th mat-header-cell *matHeaderCellDef> Apellido</th> <td mat-cell *matCellDef="let element"> {{element.apellido}}</td> </ng-container> <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr> <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr> </table> here is the … -
I want to ignore all the locale files in venv and compile others
I am making a locale directory to store the translations in it but I have venv which contains so many locale files.. I want to ignore them and only compile the ones I have made. I already have written in the setting LOCALE_PATHS = ( os.path.join(BASE_DIR, 'Medical_Healthcare_System/locale'),) but when I use compile messages command it compiles only the venventer image description here