Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
build generic query while triggering graphql api from django
Below is a graphql query that retrieves user details like id,username,city,pincode by passing a variable that matches with a cityname called 'osaka' : query = """ { userinfo (cityName: "osaka") { id user_name city pincode } }""" this query is being posted to an external graphql api using requests module of python url = 'http://192.168.200.58:8010/api/userdetails/v1/users' r = requests.post(url, query,headers=headers, auth=HTTPBasicAuth('api', 'api123')) json_data = json.loads(r.text) how to query this api by passing cityname dynamically , i tried the below code but that did not work json = {'query': """ { userinfo ($cityname: str) { id user_name city pincode } }""", "variables":{"cityName":"LA"} url = 'http://192.168.200.58:8010/api/userdetails/v1/users' r = requests.post(url, json=json,headers=headers, auth=HTTPBasicAuth('api', 'api123')) json_data = json.loads(r.text) -
Endpoints for Two factor authentication using Django REST
I am creating an api for authenticating the user with a two factor auth upon login. The Following view is redirected to after the login is successful. class TOTPView(APIView): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.verified = False self.last_verified_counter = -1 self.totp = self.generate_totp() def get(self, request, *args, **kwargs): logger.debug(self.totp) return Response({'success': True}, status=status.HTTP_201_CREATED) def post(self, request): token = int(request.data.get('totp_token')) # check if the current counter value is higher than the value of # last verified counter and check if entered token is correct by # calling totp.verify_token() if ((self.totp.t() > self.last_verified_counter) and (self.totp.verify(token))): # if the condition is true, set the last verified counter value # to current counter value, and return True self.last_verified_counter = self.totp.t() self.verified = True return Response({'success': True}, status=status.HTTP_404_NOT_FOUND) else: # if the token entered was invalid or if the counter value # was less than last verified counter, then return False self.verified = False return Response(status=status.HTTP_404_NOT_FOUND) def generate_totp(self): key = random_hex(20) totp = TOTP(key) totp.time = time.time() return totp Here, when the user posts the OTP code/token, the POST method calls self.totp and that overwrites its value by calling self.generate_totp() again. That never validates the TOTP. Am I doing something wrong here? -
How to solve the error Devtools failed to parse Sourcemap?
Whenever I load the site, it gives me a bunch of errors in the console and cmd. I don't know how to deal with that? Please help me to get rid of these errors. I went to those locations but have no idea what to do with these things? "GET /favicon.ico HTTP/1.1" 404 2264 [13/Feb/2020 13:32:06] "GET /static/home/js/popper.min.js.map HTTP/1.1" 404 1802 [13/Feb/2020 13:32:06] "GET /static/home/js/aos.js.map HTTP/1.1" 404 1781 [13/Feb/2020 13:32:06] "GET /static/home/js/typed.min.js.map HTTP/1.1" 404 1799 [13/Feb/2020 13:32:06] "GET /static/home/js/bootstrap.min.js.map HTTP/1.1" 404 1811 [13/Feb/2020 13:32:06] "GET /static/home/css/bootstrap-datepicker.css.map HTTP/1.1" 404 1838 [13/Feb/2020 13:32:06] "GET /static/home/css/aos.css.map HTTP/1.1" 404 1787 [13/Feb/2020 13:32:21] "GET / HTTP/1.1" 200 24434 [13/Feb/2020 13:32:22] "GET /static/home/css/bootstrap-datepicker.css.map HTTP/1.1" 404 1838 [13/Feb/2020 13:32:22] "GET /static/home/css/aos.css.map HTTP/1.1" 404 1787 [13/Feb/2020 13:32:22] "GET /static/home/js/popper.min.js.map HTTP/1.1" 404 1802 [13/Feb/2020 13:32:22] "GET /static/home/js/typed.min.js.map HTTP/1.1" 404 1799 [13/Feb/2020 13:32:22] "GET /static/home/js/bootstrap.min.js.map HTTP/1.1" 404 1811 [13/Feb/2020 13:32:22] "GET /static/home/js/aos.js.map HTTP/1.1" 404 1781 -
How to customize django rest auth email context
Similar to this question How to customize django rest auth password reset email content/template I would like to customize password reset (and other) emails automatically send by django rest auth. It perfectly works to use custom email templates with an custom serializer: class CustomPasswordResetSerializer(PasswordResetSerializer): def get_email_options(self): return { 'domain_override': settings.FRONTEND_URL, 'email_template_name': 'registration/custom_reset_email.txt', 'html_email_template_name': 'registration/custom_reset_email.html', } But additionally to customized templates I want to add custom context. Is there a simple way to do it? -
How am I able to filter post tags in Django
I have a blog type website where users can add tags to their posts and I want people to be able to filter by tag. Here is my models.py class Tag(models.Model): name = models.CharField(max_length=150,unique=True) def __str__(self): return self.name class Post(models.Model): author = models.ForeignKey(User,related_name='posts',on_delete=models.CASCADE) title = models.CharField(max_length=75) text = models.TextField(null=True,blank=True) tag = models.ManyToManyField(Tag,related_name='tags',blank=True) I cut a lot of the irrelevant model fields out so you weren't bombarded with lots of text. Now here is my views.py class TagFilterView(ListView): model = Post template_name = 'mainapp/tags_.html' def get_queryset(self): object_list = Post.objects.filter(tags=tag).distinct() return object_list Here is my url pattern path('tag/<int:pk>/',views.TagFilterView.as_view(),name='tag_view'), And finally here is the HTML file {% extends 'mainapp/base.html' %} {% block content %} <h1>Tags</h1> {% for post in object_list %} <h2>{{ post }}</h2> {% endfor %} {% endblock content %} I have tried lots of different filter combos and filter tags, but this seems to be the closest I think. So basically I want to know how I can filter posts to the specific tags they have associated with them. So for example, if a post has a programming tag, and I go to /tag/1 or something like that, it will filter so only the posts with the programming tag are shown. … -
Django: apply filter on field of related model which is in another database
I've two tables in two database, Say policy in DB_A and quote in DB_B. policy has a field result_reference which is the id of quote table in DB_B policy in DB_A class Policy(models.Model): result_reference = models.IntegerField() policy_date = models.DateTimeField() Quote in DB_B class Quote(models.Model): quote_type = models.IntegerField() policy_type = models.CharField(max_length = 100) policy_premium = models.IntegerField() The policy type can be S for Single and M for Multiple I want to get the policies with policy date after 30 days along with policy type=M What i've tried import datetime start_date = datetime.datetime.now() + datetime.timedelta(30) p = Policy.objects.using(default_database).filter(policy_date__gte=start_date) but this returns policies that have policy_type S and M. How can i filter it for policy type M? -
Django CMS Custom Plugin and Page
I have created a custom Django CMS plugin. I want to create a dynamic dropdown in Plugin config. So If I have a country and state dropdown when I select country its state should be populated in state dropdown. I have no idea how to do it? One more issue is with page. How can I know the plugin content that is loaded in the page. I have check the navigation object also but no direct way to get it. -
Django calculate compounded interest for all objects in model
Using: Python 3.8.1, Django 3.0.1 I’ve spent hours on particularly Stack Overflow to get everything working the way I have it now and also to find a solution for my current problem. I’m not able to use answers from other questions and apply to my problem I’m busy with a finance application to track outstanding debits and calculate the interest on the outstanding balances. I have three models: Debtor - which contains the client’s personal information as well as the applicable interest rate, compounding period etc. DebtorAccount – is created whenever a new client is created. It also keeps a running balance and accrued interest. DebtorTransaction – records the type of transaction description, debit/credit, amount etc. models.py class Debtor(models.Model): name = models.CharField(max_length=200, default="") period = models.DecimalField(max_digits=100, decimal_places=2, default=0, null=True) interestrate = models.DecimalField(max_digits=100, decimal_places=2, default=0, null=True, blank=True) def __str__(self): return self.name @property def unique_id(self): return str(self.pk) class DebtorAccount(models.Model): accountname = models.OneToOneField(Debtor, on_delete=models.CASCADE) balance = models.DecimalField(max_digits=100, decimal_places=2, default=0) interest = models.DecimalField(max_digits=100, decimal_places=2, default=0) rate = models.DecimalField(max_digits=100, decimal_places=2, default=0) period = models.DecimalField(max_digits=100, decimal_places=2, default=0) def __str__(self): return str(self.accountname) def create_debtoraccount(sender, **kwargs): if kwargs['created']: debtor_account = DebtorAccount.objects.create(accountname=kwargs['instance']) post_save.connect(create_debtoraccount, sender=Debtor) class DebtorTransaction(models.Model): CREDIT = 'CREDIT' DEBIT = 'DEBIT' TRANSACTION_TYPES = ( ("CREDIT", "Credit"), ("DEBIT", "Debit"), … -
How to Deploy/Upload Wagtail Site to DigitalOcean through ssh?
Can Anyone tell me how to deploy Wagtail site to DigitalOcean. And by deploy I mean upload the site with media files that I have in local machine, through ssh. Any link or blog or suggestion will work. There are many links and instruction available where they show fresh deployment from git or directly. But I need to upload it from my local machine with existing database. I need to upload and get running this site through ssh. Any database is fine, sqlite, postgresql, anything. I dont know how to upload data from local machine to server and get it running. I use made a local site in Windows 10. IDE=PyCharm. DigitalOcean Server has Python=3.5. For ssh I am using Git Bash. Any Help? -
Opencv read image RGB
I am new here, do you know the form to read image in python with cv2. Is necessary to put the flags always? or the function "know" the format of image? -
AWS : ERROR: ERROR: Could not find a version that matches pipenv-to-requiremnets
I miss-typing pipenv-to-requiremnets and then try pipenv-to-requirements right after. then, error getting this log message: Installing pipenv-to-requirements… Adding pipenv-to-requirements to Pipfile's [packages]… ✔ Installation Succeeded Pipfile.lock (15510c) out of date, updating to (b1d4ac)… Locking [dev-packages] dependencies… ✔ Success! Locking [packages] dependencies… ✘ Locking Failed! [pipenv.exceptions.ResolutionFailure]: File "/usr/local/Cellar/pipenv/2018.11.26_2/libexec/lib/python3.7/site- .... ... [pipenv.exceptions.ResolutionFailure]: pipenv.exceptions.ResolutionFailure: ERROR: ERROR: Could not find a version that matches pipenv-to-requiremnets [pipenv.exceptions.ResolutionFailure]: No versions found [pipenv.exceptions.ResolutionFailure]: Warning: Your dependencies could not be resolved. You likely have a mismatch in your sub-dependencies. First try clearing your dependency cache with $ pipenv lock --clear, then try the original command again. Alternatively, you can use $ pipenv install --skip-lock to bypass this mechanism, then run $ pipenv graph to inspect the situation. Hint: try $ pipenv lock --pre if it is a pre-release dependency. ERROR: ERROR: Could not find a version that matches pipenv-to-requiremnets No versions found Was https://pypi.org/simple reachable? Is it OK? or How can resolve this? what is it mean? I can't get to next step... -
How to upload a database on Kiwi TCMS from json file?
I have kiwi TCMS on docker through docker-compose.yml. And i have file json with database (old version of kiwi) To dump database from old serwer i use: docker exec -it kiwi_web /Kiwi/manage.py dumpdata --all --indent 2 > database.json. In new kiwi TCMS i want use my old database, but after enter this command docker exec -it kiwi_web /bin/bash -c '/Kiwi/manage.py sqlflush | /Kiwi/manage.py dbshell' i get: CommandError: You appear not to have the 'mysql' program installed or on your path. Exception ignored in: <_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'> BrokenPipeError: [Errno 32] Broken pipe What should I do? I use instructions from: kiwi blog -
Assigning a foreign key creates a new object
I'm trying to create a One-To-Many relationship in django which is working fine so far. @register_snippet class CarPart(models.Model): title = models.CharField(max_length=50) class Meta: verbose_name_plural = 'Car Parts' def __str__(self): return self.title class CarParts(CarPart): source_page = ParentalKey( 'home.CarPage', related_name='carparts' ) carpart = models.ForeignKey( CarPart, null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) panels = [ SnippetChooserPanel('catpart'), ] class CarPage(BasePage): content_panels = BasePage.content_panels + [ InlinePanel('carparts', label="Car Part"), ] def get_context(self, request): context = super().get_context(request) return context This is working fine - I can assign multiple car parts to a car but the problem is whenever I assign a car part it automatically creates a new empty objects other than the original data in Car Parts snippet or table. It's showing correct parts when I do {% for part in car.carparts.all %} {{ part.title }} {% endfor %} But when I delete the empty objects from car parts snippet, it deletes the car parts in car and the for loop doesn't seem to show any value as the related car parts are deleted. I don't understand why it is creating new empty objects but assigning the correct ids. Like: If I select car part engine from page editor and save it - it creates a … -
Deposit amount using Django
Model.py class Customers(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) contact = models.BigIntegerField(unique=True) amount = models.BigIntegerField() type = models.CharField(max_length=1)` Form.py class Deposit_Form(forms.Form): amount = forms.IntegerField(min_value=200, label="Enter amount u want to deposit") View.py class Log_in(TemplateView): template_name = 'login.html' def get(self, request, *args, **kwargs): Form = Login() return render(request, self.template_name, {'form': Form}) def post(self, request): username = self.request.POST.get('username').strip() password = self.request.POST.get('password').strip() if username is None or password is None: return HttpResponse({'Doesnt exist'}, status=HTTP_400_BAD_REQUEST) user = authenticate(username=username, password=password) if not user: return HttpResponse({'Invalid candidate '}, status=HTTP_404_NOT_FOUND) return redirect('customer_menu') def customer_menu(request): if "user_id" in request.session: return render(request, 'customer_menu.html') class Deposit(TemplateView): template_name = 'deposit.html' def get(self, request, *args, **kwargs): Form = Deposit_Form() return render(request, self.template_name, {'form': Form}) @staticmethod def post(request): if "user_id" in request.session: data = request.POST.get try: deposit_amount=data('deposit_amount') customer = CustomerModel( amount = deposit_amount+amount ) customer.save() return HttpResponse('action performed successfully', 500) except Exception as e: return HttpResponse("failed : {}".format(e), 200) now i can't understand how can deposit amount, it show error in deposit class post function amount = deposit_amount + amount -
How can I add prefix to the name field of group model in django
I am trying to extend the group model(add a new field called display field) and rename the name field of the django by adding some prefix(it would be company_id later on). Till now I have just added the extra field to default group model like this from django.db import models from django.contrib.auth.models import Group Group.add_to_class('display_field', models.CharField(max_length=180,null=True, blank=True)) How can I rename the name field now? -
Cannot run Django management command using Docker exec
I've got a Django server running nicely in a Docker container called loc-vol-web. When I try to run Django management commands straight from the host CLI, it just doesn't work: >> docker exec -it loc-vol-web "python /app/src/manage.py migrate" OCI runtime exec failed: exec failed: container_linux.go:346: starting container process caused "exec: \"python /app/src/manage.py migrate\": stat python /app/src/manage.py migrate: no such file or directory": unknown However, all of the following work fine: >> docker exec -it loc-vol-web "python" Python 3.7.6 (default, Jan 3 2020, 23:35:31) [GCC 8.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> >> docker exec -it loc-vol-web "/bin/bash" some_user@ce1b1c2ac208:/app$ python /app/src/manage.py Type 'manage.py help <subcommand>' for help on a specific subcommand. Available subcommands: [auth] changepassword createsuperuser [contenttypes] remove_stale_contenttypes [django] check compilemessages createcachetable dbshell diffsettings dumpdata flush inspectdb loaddata makemessages makemigrations migrate sendtestemail shell showmigrations sqlflush sqlmigrate sqlsequencereset squashmigrations startapp startproject test testserver [sessions] clearsessions [staticfiles] collectstatic findstatic runserver some_user@ce1b1c2ac208:/app$ I'm now getting at my wit's end as to why I can't just run manage.py so any help would be appreciated. -
Update javascript files
I'm developing a django app and I need my production server to tell browsers to update cached js files on every build. How do I do that. As you have probably guessed I've updated js files but my (and every other user's) browser cached previous version of those js files. I want those files to always be updated. Maybe I can tell browsers not to cache any data from page, or I can directly tell browsers to update js files. I accept any solutions, please help me. -
Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>`, AssertionError
AssertionError:Expected a Response, HttpResponse or HttpStreamingResponse to be returned from the view views.py # Create your views here. from rest_framework import serializers from rest_framework import views from rest_framework.views import APIView from rest_framework.generics import ListAPIView from rest_framework.response import Response from rest_framework.status import ( HTTP_200_OK, HTTP_201_CREATED, HTTP_400_BAD_REQUEST, ) import MySQLdb from testpro.settings import connection cur, conn = connection() class Product_ListAPIView(ListAPIView): def get(self,request,format=None): cur,conn = connection() query = ''' SELECT * FROM products''' try: with conn.cursor(MySQLdb.cursors.DictCursor) as cursor: cursor.execute(query) result = cursor.fetchall() data = list(result) print(request.data) return Response({"data":result},status=status.HTTP_200_OK) except Exception as e: print(e) I think the connection is proper but I am not sure why I am getting this error, it would be great if anyone can help me figure out what I am doing wrong -
GIT - Pushing from server to GitHub triggers a Pull error
I am quite new to git versioning so excuse me in advance if the query may seem trivial. I have a django project on my local computer and I pushed it on a GitHub repository. I cloned the repository on the online linux server hosting the project. So far so good. Due to the tight schedule I need to work on, I made some patches directly on the online code. Then i decided to push these changes on the github repository so that i can pull them on my local computer and start implementing new changes to push back on GitHub at a later stage. Once i run the push command from the server to GitHub an error informing me to consider pulling before pushing as another user (the local one) is pushing on the same GitHub repository is displayed. My questions are: is it safe to pull from GitHub on the server? I am afraid the patches I have applied directly on the server will disappear as a result of pulling from GitHub (which does not contain the patches) if it is safe to pull, what is the correct command sequence? Pull, add ., commit, push? Thanks in advance. -
Problem with adding additional attributes to django-oscar with solr and haystack
Im new here and its my first question, sorry if Im missing something. It seems django-oscar have a problems with search facets. However I have a project where its working with defaults "price range" and some default fields like "product class" and "raiting". Im trying to add my own attributes to solr, which was added true models.py: location = models.TextField(('Location'), blank=True, default=None, null=True) duration = models.TextField(('Duration'), blank=True, default=None, null=True) I added this lines to my search_indexes.py class ProductIndex(indexes.SearchIndex, indexes.Indexable): product_class = indexes.CharField(null=True, faceted=True) <-- deafult working location = indexes.CharField(null=True, faceted=True) duration = indexes.CharField(null=True, faceted=True) def prepare_product_class(self, obj): return obj.get_product_class().name <-- default working def prepare_location(self, obj): return obj.get_location_class().name def prepare_duration(self, obj): return obj.get_duration_class().name Im added them to settings.py OSCAR_SEARCH_FACETS = { 'fields': OrderedDict( [('product_class', {'name': _('Type'), 'field': 'product_class'}), ('rating', {'name': _('Rating'), 'field': 'rating'}), ('location', {'name': _('Location'), 'field': 'location'}), ('duration', {'name': _('Duration'), 'field': 'duration'}), ]), So the first problem is with command python manage.py build_solr_schema > solr/schema.xml building schema.xml which is not working - solr gives errors to some id field, and there is no fields that i wanted to add. Okay, I get working schema.xml from github, its working! And I added there two fields manually: <field name="location" type="edge_ngram" indexed="true" stored="true" … -
How to nest validation errors in Django
I am trying to nest validation errors into one response. How can I group them into fields? Using this example, instead of raising each error, group everything into one response. The example desired output is below. Here is my example: class HighScoreSerializer(serializers.BaseSerializer): def to_internal_value(self, data): score = data.get('score') player_name = data.get('player_name') # Perform the data validation. if not score: raise serializers.ValidationError({ 'score': 'This field is required.' }) if not player_name: raise serializers.ValidationError({ 'player_name': 'This field is required.' }) if len(player_name) > 10: raise serializers.ValidationError({ 'player_name': 'May not be more than 10 characters.' }) # Return the validated values. This will be available as # the `.validated_data` property. return { 'score': int(score), 'player_name': player_name } My desired result: {'player_name': ['This field is required.', 'May not be more than 10 characters.'], 'score': ['This field is required.']} -
I want to update a group of model object but it doesn't work
I am trying to assign these to users and using a form for the same model to update it but it doesn't work for some reason, this is the code def assign_blanks(request): if request.method == 'POST': form = assign_blank_form(data=request.POST) from_value = request.POST.get("from_value", "") to_value = request.POST.get("to_value", "") blanks = blank.objects.all() for b in blanks: if b.number >= int(from_value) and b.number >= int(to_value): b.advisor = form.instance.advisor print(b.number) return render(request, 'assign_blanks.html') else: form = assign_blank_form return render(request, 'assign_blanks.html', {'form':form}) class assign_blank_form(ModelForm): class Meta: model = blank fields = ['advisor'] <form class="box" method = "post"> {% csrf_token %} <h1>Air Ticket Sales</h1> {{ form }} assign from: <input type="number" name="from_value" value="{{ from_value }}"> assign to: <input type="number" name="to_value" value="{{ to_value }}"> <input type="submit" name="" value="Assign blanks"> </form> -
Is there a way to set different id for each ValidationError in Django?
This is how my form looks: class TestForm(forms.ModelForm): class Meta: model = Restaurant fields = [ 'title', 'content', ] def clean(self, *args, **kwargs): title = self.cleaned_data.get("title") content = self.cleaned_data.get("content") error_dict = {} if len(title) < 3: error_dict['title'] = ValidationError("testerror1") if len(content) < 3: error_dict['content'] = ValidationError('testerror2') if error_dict: raise ValidationError(error_dict) If I try to submit the form with empty title and content it shows two error messages (testerror1, testerror2), they appear above each field label and looks like this: <ul class="errorlist"> <li>test2</li> </ul> But I want to hide each of them if client click on input, so I tried with Jquery: $("#my_form_id").find('input, textarea').click(function() { $(this).closest('ul').hide(); }) Without success (it doesn't found any <ul> element. My question is, is there a way to set different id for each error? So that I can manage each one separately. -
Using Motor or any other async MongoDB driver in Django 3 projects
Is there any way using Motor or any other async MongoDB driver in Django 3 projects? I tried using motor clients First: motor_asyncio.AsyncIOMotorClient and Second: motor_tornado.MotorClient. The first one raises below exception: Task <Task pending coro=<SessionMiddlewareInstance.__call__() running at SOMEWHERE>> got Future <Future pending cb=[run_on_executor.<locals>._call_check_cancel() at SOMEWHERE]> attached to a different loop The second one doesn't raise any exceptions but it stops at the line that I insert messages in db with insert_one method. Is there any way to insert and read data from MongoDB asynchronously? -
Why don't work permissions in post method?
I get following viewset class ThankYouMessageViews(mixins.RetrieveModelMixin, mixins.CreateModelMixin, GenericViewSet): lookup_url_kwarg = 'id' permission_classes = (IsDonatedProductOwnerOrReadOnly,) def get_serializer_class(self): if self.action == 'create': return ThankYouMessagesCreateSerializer return ThankYouMessagesGetSerializer def perform_create(self, serializer): pass Why don't work permission in create method? But permission works in retrieve method