Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dynamically mocking the return value of a database call in Django test
I am trying to test a function and dynamically mock out the database call to the RecordType table, as the test database does not contains all the instances that I need for the function to run. This is the part of the function in question: permanent = [] temp = [] for category in enums.Category: category_name = str(category.name) if category_name in labels: if not category.is_temporary_code: permanent.append(category) else: temp.append(category) for category in permanent: category_name = str(category.name) internal_code = models.RecordType.objects.get( industry_code=category.value ).internal_code field_label = labels[category_name] self.fields[internal_code] = forms.BooleanField(label=field_label, required=False) I have a dict of values (record_type_dict) that I would like to be returned in place of calling the mocked function, depending on the passed in 'category.value'. In my test file I have this code: @mock.patch.object(forms, 'models') def test_records(mock_models, factory, support_client): .... mock_models.RecordType.objects.get().internal_code.side_effect = side_effect ... def side_effect(*args, **kwargs): if args[0] in record_type_dict: return record_type_dict[args[0]] else: return "" However this does not work as the database is being called with 'industry_code=category.value'. Is there a way of dynamically mocking this call depending only on the value of category.value? -
Django & Bootstrap - add Spinner to form
I want to make my quantity form a little bit more appealing: My original code: {% for form in formset_parts %} <div class="row form-row spacer"> <label>{{form.name.label}}</label> <div class="input-group"> {{ form.part }} {{ form.qty }} </div> </div> {% endfor %} <div class="row spacer"> <button type="submit" class="btn btn-block btn-primary">Create</button> </div> {% endfor %} I want to changed that to something like: {% for form in formset_parts %} <div class="row form-row"> <tr> <td>{{ form.part.label }}:</td> <td> <select class="browser-default custom-select"> {% for part in form.part %} <a class="dropdown-item" href="#">{{ part }}</a> {% endfor %} </select> </td> <td>{{ form.qty.label }}: </td> <td>{{ form.qty }}</td> </tr> </div> {% endfor %} I would now like to include a spinner for the qty label, like shown here. So I copy & pasted the code from here in a file called bootstrap-input-spinner.js in the root project directory under ../static/js/bootstrap-input-spinner.js. In the template of the app I added (below the code pasted above). {% block custom_js %} <script src="{% static 'js/bootstrap-input-spinner.js' %}"></script> <script> $("input[type='quantity']").inputSpinner() </script> {% endblock %} So now instead of my {{ form.qty }} i want to use <input type="quantity" value="0" min="0" max="50" step="1"/> but I don't know how this will link to the former {{ form.qty }} … -
DjangoFilterBackend: Filtering on a primary key results in "Select a valid choice. That choice is not one of the available choices."
I have two models (Product & Category) which every product has a linked category. I have installed DjangoFilterBackend which the hope of filtering on the category field to return a list of products in that category. However, whenever I send the query in Postman. I receive the error Select a valid choice. That choice is not one of the available choices.. I have tried filtering on another field in my product model (name for an example) and that works fine. So i'm not sure if i'm missing something for category to work. Product/View.py: class ProductView(ListAPIView): serializer_class = ProductSerializer queryset = Product.objects.all() filter_backends = [DjangoFilterBackend] filterset_fields = ('category', 'name') Products/Models.py: class Product(models.Model): name = models.CharField(max_length=250, unique=True, blank=False) photo = models.ImageField(upload_to=product_photo_path) category = models.ForeignKey(Category, on_delete=models.CASCADE) quantity = models.IntegerField() description = models.TextField(blank=False) price = models.DecimalField(max_digits=6, decimal_places=2) in_stock = models.BooleanField(default=False) trending = models.BooleanField(default=False) def __str__(self): return self.name Products/serializers.py class ProductSerializer(serializers.ModelSerializer): category = serializers.CharField(source='category.name', read_only=True) class Meta: model = Product fields = ('category', 'name', 'photo', 'quantity', 'description', 'price', 'in_stock', 'trending') The query I am using: http://127.0.0.1:8000/api/products?category=xxxx - which results in an error. -
Django,unable to download mp3 files in frontend
My Django app have mp3 file field as mentioned in the below model. I upload mp3 files from admin side. When I send GET request for mp3 files in frontend , it plays in browser but I can't download If I attempt download it results in error as mention below in terminal and download fails MODELS.PY from django.db import models class Music(models.Model): ... track = models.FileField(upload_to='tracks') ERRORS Traceback (most recent call last): File "c:\users\dell\desktop\pythonfiles\Lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "c:\users\dell\desktop\pythonfiles\Lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "c:\users\dell\desktop\pythonfiles\Lib\wsgiref\handlers.py", line 279, in write self._write(data) File "c:\users\dell\desktop\pythonfiles\Lib\wsgiref\handlers.py", line 453, in _write result = self.stdout.write(data) File "c:\users\dell\desktop\pythonfiles\Lib\socketserver.py", line 796, in write self._sock.sendall(b) ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host [05/Jun/2020 16:33:37] "GET /media/tracks/Kalimba.mp3 HTTP/1.1" 500 59 Exception happened during processing of request from ('127.0.0.1', 59832) During handling of the above exception, another exception occurred: TypeError: 'NoneType' object is not subscriptable AttributeError: 'NoneType' object has no attribute 'split' -
Frontend application displaing progress from API
I've got a case where I have got 3 docker containers: - frontend in Angular - backend in Django - processing API in python. The use-case is that user sends a file to backend volume (using frontend GUI) and then API processes it. Processing takes some time, so API sends updates using SSE to the backend (which was a trigger for that action) and I would like to forward that progress updates to the frontend. I've tried to use WebSockets for that (frontend <-- WebSocket --> backend <-- SSE --> API), but there is a lot of bugs in case of processing multiple files at once. I also would not like to expose API to frontend. API can process multiple files in parallel. Do You guys have got some best practices for such case? -
Django, JSONField, filter for non empty list
I have a jsonfield foo = JSONField(default=list) I want to filter queryset so that foo has some data (not empty list) I've tried MyModel.objects.filter(foo__ne=[]) // doesn't seem to work MyModel.objects.filter(foo__gt=[]) // seems to work but can't be sure if it's the right approach -
django-tables How to disable clickable <th>
What is the best way to disable clickable th in django-tables? everytime i click the url change this is my views.py gradelevels = request.GET.get('gradelevel') semesters = request.GET.get('semester') sections = request.GET.get('section') table = StudentTable(StudentsEnrollmentRecord.objects.filter(Education_Levels=gradelevels).filter( Semester=semesters).filter(Section=sections).filter(Status = 'Validated')) RequestConfig(request).configure(table) export_format = request.GET.get("_export", None) if TableExport.is_valid_format(export_format): exporter = TableExport(export_format, table) return exporter.response("table.{}".format(export_format)) return render(request, "Homepage/Detail_report.html", {"gradelevel": gradelevel, "semester": semester,"section":section, "table":table}) this is my html <div class="container"> <table class="table"> <tr> <td>{% render_table table %}</td> </tr> </table> {% for format in table.export_formats %} <a href="{% querystring '_export'=format %}"><button>download <code>.{{ format }}</code></button></a> {% endfor %} </div> -
How can I get request data in Django from a redirect?
I need to get data from a redirect, but I can't really figure out how. The method is GET as I can see from my print. But I have tried everything I found on searching for this without luck. What am I doing wrong? I really appreciate any help. I have this redirect: return redirect('/list-view', new = 'new') My urls looks like this: path('list-view/<new>', views.list_view, name='list'), Then my list-view is: def list_view(request, *args, **kwargs): print(request.method) if request.method == 'GET': aa=request.GET.get('new') if aa: bb = (request.GET.get('new')) print (bb['new']) -
Steps In Building a Social Media With Python [closed]
I'm learning python and I want to build a social media. What are the things I should learn, what part of python should I be based on to make that a successful social media -
Django prefetch_related performance - to_attr not working on nested lookups
I have a relatively complex model structure in a django project (v2.1.4). Let's say: class Pizza(models.Model): pass class ToppingPlacedOnPizza(models.Model): # Breaks a many-to-many relationship between Pizza and Topping and stores specific data # like the position of the topping in the pizza pizza = models.ForeignKey(Pizza, related_name='placed_toppings') topping = models.ForeignKey(Topping) # position ... class Topping(models.Model): brand = models.ForeignKey(Brand) class Brand(models.Model): name = models.CharField(max_length=32) I need to retrieve all the names of the brands that make toppings for each pizza of a set of pizzas. Say: pizza1: brand1, brand2, brand3 pizza2: brand2, brand4 ... To do so, prefetch_related has been of great help in order to improve performance: pizzas.prefetch_related('placed_toppings__topping__brand') But when making a query for ~1000 pizzas it starts being really slow. According to this stackoverflow answer, using Prefetch class and to_attr could improve performance, but I couldn't make it work on my case. It's not clear in which object to_attr will write the new attribute because of the nested lookup. I made to_attr work on first level. When setting pizzas.prefetch_related(Prefetch('placed_toppings', to_attr('mytoppings'))), then pizzas[0].mytoppings exists. But when setting pizzas.prefetch_related(Prefetch('placed_toppings__topping__brand', to_attr('mybrands'))), none of the following exist: pizzas.mybrands pizzas[0].mybrands pizzas[0].placed_toppings.mybrands pizzas[0].placed_toppings.first().mybrands pizzas[0].placed_toppings.first().topping.mybrands Any ideas on how to improve performance or make to_attr work on … -
Django app crashes on deploying to Heroku - Error H10
I am trying to deploy my django app on heroku and it crashes with exit status 1 error code h10. I am deploying to heroku for the first time and cannot find a fix. It is a simple project so i was trying to deploy it on sqlite database only. My project name is portfolio, appname is mywebsite heroku logs 2020-06-05T12:58:10.098179+00:00 heroku[web.1]: State changed from starting to crashed 2020-06-05T12:58:15.673642+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=harnaman.herokuapp.com request_id=a553ec3b-75b5-46c6-bf04-a3a2cfd6829c fwd="106.204.196.204" dyno= connect= service= status=503 bytes= protocol=https 2020-06-05T12:58:16.236791+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=harnaman.herokuapp.com request_id=e0f1cc63-1163-45c1-855d-784e1a1536be fwd="106.204.196.204" dyno= connect= service= status=503 bytes= protocol=https 2020-06-05T13:13:36.052752+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=harnaman.herokuapp.com request_id=5c0b2b72-48aa-412d-b6b7-1560fb6c72cc fwd="106.204.196.204" dyno= connect= service= status=503 bytes= protocol=https 2020-06-05T13:13:37.136635+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=harnaman.herokuapp.com request_id=88373377-a732-490d-a420-8b2295739eb3 fwd="106.204.196.204" dyno= connect= service= status=503 bytes= protocol=https 2020-06-05T13:13:44.436995+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=harnaman.herokuapp.com request_id=8fed326e-1da8-44a3-a79d-52df93f307e6 fwd="106.204.196.204" dyno= connect= service= status=503 bytes= protocol=https 2020-06-05T13:13:45.262259+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=harnaman.herokuapp.com request_id=85a7b359-74ef-40ee-8c08-f89cab6a2349 fwd="106.204.196.204" dyno= connect= service= status=503 bytes= protocol=https 2020-06-05T13:18:29.000000+00:00 app[api]: Build started by user *******@gmail.com 2020-06-05T13:19:02.798192+00:00 app[api]: Deploy 0823f045 by user *******@gmail.com 2020-06-05T13:19:02.798192+00:00 app[api]: Release v17 created by user *******.com 2020-06-05T13:19:02.976994+00:00 heroku[web.1]: State changed from crashed to starting … -
Django View Causes Psycopg2 Cursor Does/Does Not Exist Error
I run a Django site which has a simple ModelForm type view that is generating cursor errors. In the past two days, this view was POSTed to a couple hundred times and about 8% of the time generated an error. I ONLY have this problem with this view, even though I have another which is very similar. That's the frustrating thing is I haven't figured out what's special about it. I just started seeing these errors after upgrading to Django 2.1/2, but I think they may have pre-existed, yet were not seen. Full stack trace here: https://gist.github.com/jplehmann/ad8849572e569991bc26da87c81bb8f4 Some examples from logging from query [error] (internal users edit) OR (psycopg2 errors cursor) with usernames redacted, to show timing: Jun 04 12:42:12 ballprice app/web.1: [ERROR] Internal Server Error: /users/a/edit [log:228] Jun 04 12:42:12 ballprice app/web.1: psycopg2.errors.InvalidCursorName: cursor "_django_curs_140401754175232_2" does not exist Jun 04 12:42:12 ballprice app/web.1: psycopg2.errors.InvalidCursorName: cursor "_django_curs_140401754175232_2" does not exist Jun 04 12:42:27 ballprice app/web.1: [ERROR] Internal Server Error: /users/a/edit [log:228] Jun 04 12:42:27 ballprice app/web.1: psycopg2.errors.InvalidCursorName: cursor "_django_curs_140401754175232_3" does not exist Jun 04 12:57:51 ballprice app/web.3: [ERROR] Internal Server Error: /users/a/edit [log:228] Jun 04 12:57:51 ballprice app/web.3: psycopg2.errors.DuplicateCursor: cursor "_django_curs_140092205262592_2" already exists Jun 04 12:57:51 ballprice app/web.3: psycopg2.errors.InvalidCursorName: cursor … -
compress image before direct uploading to s3
I can direct upload the image to s3 with the help of django-s3direct. my question is How to compress image before upload to s3 ? because its direct upload I can't use PIL for compress from backend. is there any way to compress the image before direct upload to s3 ? I also want to preview the uploaded image to user after upload. when user cancel upload when its uploading then image is not stored. But after uploaded when we remove image and choose new, the previous uploaded image still in bucket. I want to delete that previous uploaded image. How to do it. What I try: I tried to compress image in model to over write save method. But I get error Errno 22] Invalid argument: 'https://s3-ap-south-1.amazonaws.com/collegestudentworld-assets/img/mainpost/amar.jpg I known because it's url can't open in PIL. is it good idea to get image and compress and then stored to s3? I think its best to compress before uploading. I also tired before uploading with javascripts but when I select image its directly start uploading . I am new to javascripts. models.py from django.core.files.uploadedfile import InMemoryUploadedFile from s3direct.fields import S3DirectField # Create your models here. class MainPost(models.Model): author = models.ForeignKey(main_user,on_delete=models.CASCADE,default=1) … -
How do I add custom file input button to Django TinyMCE editor for uploading like STL/ZIP files?
I just want to add file button to TinyMCE editor for uploading STL/ZIP/etc. files on Django. When I add "file" plugin to my TINYMCE_DEFAULT_CONFIG, It says "Failed to load plugin: file from url http://localhost:12000/static/tinymce/js/tinymce/plugins/file/plugin.min.js" I am using django-tinymce4-lite 1.7.5 My config file that is at settings.py is below: TINYMCE_DEFAULT_CONFIG = { "height": 360, "width": 1120, "cleanup_on_startup": True, "custom_undo_redo_levels": 20, "selector": "textarea", "theme": "modern", "plugins": """ textcolor save link image media file preview codesample contextmenu table code lists fullscreen insertdatetime nonbreaking contextmenu directionality searchreplace wordcount visualblocks visualchars code fullscreen autolink lists charmap print hr anchor pagebreak """, "toolbar1": """ fullscreen preview bold italic underline | fontselect, fontsizeselect | forecolor backcolor | alignleft alignright | aligncenter alignjustify | indent outdent | bullist numlist table | | link image media file | codesample | """, "toolbar2": """ visualblocks visualchars | charmap hr pagebreak nonbreaking anchor | code | """, "contextmenu": "formats | link image", "menubar": True, "statusbar": True, "default_link_target": "_blank", } -
Django and Stripe logging
With Django logging settings setup like below how can I get stripe info to log to only the stripe logger? With this setup it's logging to both loggers. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse', }, }, 'formatters': { 'verbose': { 'datefmt': '%Y-%m-%d %H:%M:%S', 'format': '[{asctime}] {levelname} {name}: {message}', 'style': '{', } }, 'handlers': { 'file': { 'level': 'INFO', 'filters': ['require_debug_false'], 'class': 'logging.handlers.RotatingFileHandler', 'filename': os.path.join(BASE_DIR, 'logs/django.log'), 'formatter': 'verbose', 'maxBytes': 5 * 1024 * 1024, # 5MB 'backupCount': 2, }, 'stripe': { 'level': 'INFO', 'filters': ['require_debug_false'], 'class': 'logging.handlers.RotatingFileHandler', 'filename': os.path.join(BASE_DIR, 'logs/stripe.log'), 'formatter': 'verbose', 'maxBytes': 5 * 1024 * 1024, # 5MB 'backupCount': 2, }, }, 'loggers': { '': { 'handlers': ['file'], 'level': 'INFO', 'propagate': True, }, 'stripe': { 'handlers': ['stripe'], 'level': 'INFO', 'propagate': True, }, } } Example function that logs to both files: def create_payment_intent(self): stripe.api_key = settings.STRIPE_SECRET amount = int(self.total * 100) intent = stripe.PaymentIntent.create( amount=amount, description=f'Order #{self.id}', receipt_email=self.customer_email, setup_future_usage='off_session', ) return intent -
Django - Is there a way to configure certain url to be inaccessible from browser request?
I've searched for this question but could not found an answer. Basically, let's say i have my_app/successfully_page that i want to be displayed within the application flow. I don't want that to be displayed if some one is typing into browser the direct url. How can i make that url page INACCESSIBLE from browser search? -
i want to display the list of pruducts based on the choice of the category chosing -django
so i want to khow what i have to add in the urls.py and in the views.py to add this functionnality: if i click in one of this categories here my categories display some products based on the category chosen. and this the models.py class Product(models.Model): name=models.CharField(max_length=200,null=True) price=models.DecimalField(max_digits=7,decimal_places=2) digital=models.BooleanField(default=False,null=True,blank=True) image=models.ImageField(blank=True,null=True,upload_to ='images/',default="images/default.jpg") categories = models.ForeignKey(Category,on_delete=models.CASCADE,blank=True, null=True) def __str__(self): return self.name @property def imageURL(self): if self.image and hasattr(self.image, 'url'): return self.image.url else: return '/static/images/default.png' class Category(models.Model): name = models.CharField(max_length=50) slug = models.SlugField(max_length=50, unique=True, help_text='Unique value for product page URL, created from name.') is_active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = 'categories' ordering = ['-created_at'] verbose_name_plural = 'Categories' def __unicode__(self): return self.name and this is the template : <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <form method="get" action=""> {% for c in active_categories %} <a class="dropdown-item" href='#'>{{ c.name }}</a> {% endfor %} <a class="dropdown-item" href="#">something else</a> </form> </div> -
UNIQUE constraint failed even after deleting the OneTone relation in Django
I've a OneToOneField in my Django models , and it gives me the error UNIQUE constraint failed even after remove it before trying to save ,, here is an example: models.py class Employee(models.Model): name = models.CharField(max_length=120) phone = models.CharField(null=True, blank=True, max_length=20) salary = models.IntegerField(default=0) shift = models.OneToOneField(Shift, on_delete=SET_NULL, null=True, blank=True, related_name='employee') def __str__(self): return self.name def get_absolute_url(self): return reverse('employee_details', args=[str(self.id)]) class Shift(models.Model): branch = models.ForeignKey(Branch, on_delete=CASCADE) start_time = models.TimeField() end_time = models.TimeField() def __str__(self): return str(self.branch) + ' ( ' + str(self.start_time) + ' / ' + str(self.end_time) + ' )' forms.py class AssignEmployeeToShift(forms.Form): employee = forms.ModelChoiceField(queryset=Employee.objects.filter(shift__isnull=True), widget=forms.Select()) views.py class EmployeeAssignToShift(SuccessMessageMixin, FormView): form_class = AssignEmployeeToShift template_name = 'back_office/employee_assign_to_shift.html' def get_success_url(self): return reverse_lazy('branch_details', args=[str(Shift.objects.get(id=self.kwargs['pk']).branch.id)]) def get_context_data(self, **kwargs): context = super(EmployeeAssignToShift, self).get_context_data(**kwargs) context['current_shift'] = Shift.objects.get(id=self.kwargs['pk']) return context def form_valid(self, form): shift_object = get_object_or_404(Shift, pk=self.kwargs['pk']) employee_instance = form.cleaned_data['employee'] employee_object = Employee.objects.filter(shift=shift_object) if employee_object.count() != 0: employee_object[0].shift = None employee_object[0].save() employee_instance.shift = shift_object employee_instance.save() else: employee_instance.shift = shift_object employee_instance.save() return super(EmployeeAssignToShift, self).form_valid(form) -
Docker & Django : Google Maps JavaScript API error
I am trying to include Google Map into my project using "Maps JavaScript API". I am able to successfully run in my local system when using the command ./manage.py runserver and the "Google Map Platform API Checker" return's success like this but when I run in docker with the commands docker-compose down docker-compose build docker-compose up and then check the the Google Map wont load and the "Google Map Platform API Checker" return's failure like this any solution to this ? -
Google App Engine: Deplying frontend and backend configuration (Nuxt + Django)
I am deploying Nuxt (frontend, universal configuration), Django (backend API, DRF), and Postgres on Google App Engine and Cloud SQL. If this is relevant: (I need to be able to store images, dynamically create and store new images and dynamically create and store pdfs.) In Google App Engine, what is the ideal setup for Django and Nuxt in terms of speed and performance? Should they be on separate apps? Any information you can provide/suggest regarding this setup would be helpful as this is my first time deploying this configuration on GAE. -
How to get video player to read local video files in djangocms?
I setup djangocms following instructions from https://www.django-cms.org/en/. When trying to embed a video using the default Video Player plugin. I see the following message under the embed video textfield: Use this field to embed videos from external services such as YouTube, Vimeo or others. Leave it blank to upload video files by adding nested "Source" plugins. Now I left it blank, but could not figure how to add a "nested Source plugin". Any thoughts? -
Push file create by Django than need to be ignore by git
I have make a first push to Gitlab with git, but the.gitignore wasn't completely configure. I configure the .gitignore like this now : # Environments env/ # Byte-compiled / optimized / DLL files poc_project/poc_project/__pycache__ poc_project/pollution/__pycache__ __pycache__/ *.py[cod] *$py.class # Django stuff: *.log local_settings.py db.sqlite3 db.sqlite3-journal The env/ and poc_project/poc_project/__pycache__ aren't push but the db.sqlite3 and poc_project/pollution/__pycache__ are already on the distant repository (Gitlab). I use this https://github.com/github/gitignore/blob/master/Python.gitignore for configure my .gitignore because I use django. My teammate will soon start working on the project. It's a problem to have pycache file and db.sqlite3 for team work on distant repository with Django? If yes how can I delete these files correctly from gitlab repository ? -
can you help me to how to fix this error in django?
I was working on project to import contacts from yahoo.I created app in yahoo developer(for client id and secret key). I was using contacts importer module for Django but I am getting this error.I unable to debug. Can you help me how to fix this error? This is the file producing error. I have provided error below. # -*- coding: utf-8 -*- """ Yahoo Contact Importer module """ from .base import BaseProvider from ..lib import oauth1 as oauth from urllib.parse import urlencode from urllib.parse import parse_qs from uuid import uuid4 as uuid from collections import OrderedDict from time import time from hashlib import md5 import requests import json REQUEST_TOKEN_URL = "https://api.login.yahoo.com/oauth/v2/get_request_token" REQUEST_AUTH_URL = "https://api.login.yahoo.com/oauth/v2/request_auth" TOKEN_URL = "https://api.login.yahoo.com/oauth/v2/get_token" CONTACTS_URL = "http://social.yahooapis.com/v1/user/%s/contacts" class YahooContactImporter(BaseProvider): def __init__(self, *args, **kwargs): super(YahooContactImporter, self).__init__(*args, **kwargs) self.request_token_url = REQUEST_TOKEN_URL self.request_auth_url = REQUEST_AUTH_URL self.token_url = TOKEN_URL self.oauth_timestamp = int(time()) self.oauth_nonce = md5("%s%s" % (uuid(), self.oauth_timestamp)).hexdigest() def get_request_token(self): request_params = dict( oauth_consumer_key=self.client_id, oauth_nonce=self.oauth_nonce, oauth_signature_method="plaintext", oauth_signature=self.client_secret + "&", oauth_timestamp=self.oauth_timestamp, oauth_version="1.0", oauth_callback=self.redirect_url ) request_url = "%s?%s" % (self.request_token_url, urlencode(request_params)) response = requests.post(request_url) query_string = parse_qs(response.text) self.oauth_token = query_string["oauth_token"][0] self.oauth_token_secret = query_string["oauth_token_secret"][0] def request_authorization(self): request_params = dict(oauth_token=self.oauth_token) return "%s?%s" % (self.request_auth_url, urlencode(request_params)) def get_token(self): request_params = dict( oauth_consumer_key=self.client_id, oauth_signature_method="plaintext", oauth_nonce=self.oauth_nonce, oauth_signature=self.client_secret + … -
Can you mock out a Python enums class?
I am trying to test a function that makes use of enums. permanent = [] temp = [] for category in enums.Category: category_name = str(category.name) if category_name in labels: if not category.is_temporary_code: permanent.append(category) else: temp.append(category) for category in permanent: category_name = str(category.name) internal_code = models.RecordType.objects.get( code=category.value ).internal_code field_label = labels[category_name] self.fields[internal_code] = forms.BooleanField(label=field_label, required=False) In my test, I make use of a factory that adds a Record Type to the test database. However, when the test calls this page and runs the function, it iterates over all the existing enums and therefore relies on the RecordType table containing all the rows from the real database. I feel a way to overcome this would be to mock out the enums, and replace it to contain only the value that corresponds with the factory Record Type. Is there a way of doing this? -
How to prefill a form with data from the same form in Django
I have a form, that calls itself and displays a result at the bottom. I want the form to be filled with the data from the previous POST request from the same form, so that I do not have to type in the same data again, after submitting it. This took me some time to figure out, so I'll self answer this yet again.