Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass field value from one model object to another?
Oh my... It is kind of a basic question, but I tried many solutions, but nothing works for me and I cannot find the similar question to mine... I have two models: class ForQuery(models.Model): id=models.BigAutoField(primary_key=True) dep_sch = models.ForeignKey('DepDict', models.DO_NOTHING, db_column='dep_sch', blank=True, null=True) code_dep_sch = models.CharField(max_length=5, blank=True, null=True) class DepDict(models.Model): department = models.CharField(primary_key=True, max_length=35) code = models.CharField(max_length=5) I have all minimal meta for these Models incuding get_absolute_url and str . I have defined url for the function in view which I am using in the template. I am matching both models by department in DepDict and dep_sch in ForQuery and in the template, based on this match I can print easily the code for the dartment, like so: {% for d in c%} {% if forquery.dep_station == d %} {{ d.code }} {% endif %} {% endfor %} Now, based on this match, I cannot save referenced field code from DepDict to field code_dep_sch from ForQuery. How would I approach this task? My view function looks like this so far: class MetalDetailView(generic.DetailView): model=ForQuery def get_context_data(self, **qwargs): content = super(MetalDetailView, self).get_context_data(**qwargs) content['c'] = DepDict.objects.all() self.code_dep_sch = c.code #this didn't work self.save() return conObject Trying to using object.field_name doesn't work... Thank you for … -
ModuleNotFoundError: No module named 'django_assets'
Whenever i am trying to use my manage.py I get this error. Please, can someone help me with this? Traceback (most recent call last): File "src/youla/manage.py", line 26, in <module> execute_from_command_line(sys.argv) File "C:\Users\bagzh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\bagzh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\bagzh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\bagzh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\bagzh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\bagzh\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django_assets' Fatal error: local() encountered an error (return code 1) while executing 'python src/youla/manage.py makemigrations is_free_user' Aborting. [localhost] local: python src/youla/manage.py makemigrations is_free_user``` -
Conftest.py is not loaded from a subfolder
The thing is that I need to have a conftest with a special setting for a set of tests. To use a live database in readonly mode only for these tests. Other tests from unit folder working with an empty db created by pytest. If I run pytest tests or pytest tests/unit conftest from tests_readonly_db are not recognized. It is recognized when I put conftest file in unit folder. And run any of these two commands. But it works perfectly when I run pytest tests/unit/tests_readonly_db with conftest in tests_readonly_db folder. Also tried to creat another subfolder in tests_readonly_db, put tests in there, with conftest.py staying level up. Doesn't work. I wonder if there is way to implement desired behaviour. Found some related answers, but couldn't fully understand how it helps in my case. For example: https://stackoverflow.com/a/13686206/7744657 But if conftest.py files from sub directories are by default not loaded at tool startup. Why it was loaded from a unit folder? conftest.py import pytest @pytest.fixture(scope='session') def django_db_setup(): """Avoid creating/setting up the test database""" pass @pytest.fixture def db_access_without_rollback_and_truncate(request, django_db_setup, django_db_blocker): django_db_blocker.unblock() request.addfinalizer(django_db_blocker.restore) App structure: -
How to update other table's fields using Post request in Django Rest
I'm new to Django and I am having issues updating the other table's fields when Posting or creating new entry. I am not sure how to. And I have been figuring this out for 2 days on how to do this through serializer or better implement it if it's not through serializer. Basically, I want to update the Fruits' status every time I create a delivery. So I can say if it's available or not. Below are the code snippet. This is my model: class Delivery(models.Model): delivery_type = models.CharField(max_length=60) driver_name = models.CharField(max_length=60) def __str__(self): return self.delivery_type class Fruits(models.Model): name = models.CharField(max_length=250) status = models.CharField(max_length=250) delivery = models.ManyToManyField(Delivery, related_name='fruits') def __str__(self): return self.name This is my serializer: class FruitSerializer(serializers.ModelSerializer): class Meta: model = Fruits fields = "__all__" class DeliverySerializer(serializers.ModelSerializer): fruits = FruitSerializer(many=True) class Meta: model = Delivery fields = "__all__" def create(self, validated_data): delivery = Delivery.objects.create( delivery_type = validated_data['delivery_type'], driver_name = validated_data['driver_name'] ) #update the status field in Fruits Table fruits = validated_data.get('fruits') for fruit in fruits: fruit_data = Fruits( id = fruit['id'], status = "Not Available", delivery=delivery ) fruit_data.save() return delivery This is my view: class DeliverySerializerView(APIView): def post(self, request): serializer = DeliverySerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return … -
How to make the characters dispalyed in django input text box as not human readable
How to make the characters dispalyed in django input text box as not human readable. For example, if I have a sensitive field like bank account number, I wanted to show the value as '*********'. Instead of showing the actual value. Just to secure the value I tried with changing my text input widget to password input, but the problem with that is , it doesnt display '*********' . and form assumes it as an empty value and when I submit it gives error to enter value for it. Your ideas will be much appreciated. Thanks Benny Varughese -
Django: How to add products to order model as whatever I try its showing ManyRelatedManager' object has no attribute 'add' or filter or similar error
Hello I am trying to learn developing a ecommerce website, and in the order model, I have this product with manytomany relation with order item. so whenever an order is processed, I would like to add the products from order item model to this product object of order model. How to implement this? Please have a look at the code. class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, blank=True, null=True) product = models.ManyToManyField('OrderItem', related_name='ordered_products') date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False) transaction_id = models.CharField(max_length=200, null=True, unique=True) payment = models.ForeignKey('Payment', on_delete=models.SET_NULL, blank=True, null=True) received = models.BooleanField(default=False) orderitem class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, null=True, blank=True,) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default=1, blank=True, null=True) views.py def processorder(request): transaction_id = create_transaction_id() data = json.loads(request.body) user = request.user order, created = Order.objects.get_or_create(user=user, complete=False) items = order.orderitem_set.all() total = float(data['form']['total']) order.transaction_id = transaction_id order.items = items if total == order.get_cart_total: order.complete = True order.save() if order.shipping == True: ShippingAddress.objects.create( user=user, order=order, address=data['shipping']['address'], city=data['shipping']['city'], state=data['shipping']['state'], zipcode=data['shipping']['zipcode'], ) return JsonResponse('Payment Complete', safe=False) How can I add the products ordered to the order model? Help would be much appreciated. -
How do i save/show manytomany field in select option field
I am working on a project where users can upload a post, edit a post and tag other users. I was able to implement upload post, edit and tag users (I implemented tag users with jquery ui). When i want to edit a post i have already tagged users on, i do not get the names of the users on select option field, instead it shows empty. How do i save/show users already tagged users from manytomany field in select option field in template. I will attach images to my question for clarity. These are the users i tagged on my post, showing in manytomany field: This image below is what i want, when i want to edit my post, let all tagged users of that post be shown in select option field: Views.py: def update_post_view(request, id): #update post post = get_object_or_404(Post, id=id) edit_form = PostForm(request.POST, instance=post) if request.method == "POST": if edit_form.is_valid(): edit_form.save() return redirect('site:comments', id=id) else: edit_form = PostForm(instance=post) #Tag username dropdown in form tag_list_users = User.objects.all() context = { 'edit_form': edit_form, 'post':post, 'tag_list_users': tag_list_users, } return render(request, 'update_post.html', context) Template: <label for="id_tag_someone">Tag someone:</label><br> <select name="tag_someone" id="id_tag_someone" multiple="" class="chosen w-100"> {% for user in tag_list_users %} <option value="{{user.pk}}">{{user}}</option> … -
Long running connection as part of my Django app
I would like to have a websocket client connection as part of my Django app. I want to listen to events and do stuff with those inside my Django world. Is there a clean way to pack something like that into the app startup? Do I put it in asgi.py or somewhere else? -
Compile python django files to run on server without storing raw codes?
I want to know is there any way to compile python Django files for running them on a server without storing main .py files? I mean like ASP.Net files, which can be compiled and make binary files in order to limit access to codes. -
Blank posts being added, as well as the user created post (Django)
Whenever you click on the Add a post button on my forum page, it will instantly add a blank post to the forum, while still adding the user-created post. Before Add a post is clicked: After Add a post is clicked (but no post details are added): I've had a go at changing the view I made for creating posts, but I ended removing the ability to add a post at all! So, wanted to see if anyone had any idea why blank posts were being added, as well as the post the user creates? View used for adding posts: @login_required def create_forum_post(request, pk=None): """ Create a view that allows us to create a post """ post = get_object_or_404(Post, pk=pk) if pk else None if not post: post = Post.objects.create(creator_id=request.user) if request.method == "POST": form = ForumPostForm(request.POST, request.FILES, instance=post) if form.is_valid(): post = form.save() return redirect('forum_post_details', post.pk) else: form = ForumPostForm(instance=post) return render(request, 'forum_post_form.html', {'form': form}) Post model: class Post(models.Model): creator_id = models.ForeignKey(User, null=False, default=1) title = models.CharField(max_length=200) content = models.TextField() created_date = models.DateTimeField(auto_now_add=True) published_date = models.DateTimeField(blank=True, null=True, default=timezone.now) views = models.IntegerField(default=0) category = models.CharField(choices=CATEGORY_CHOICES, max_length=30, blank=True, null=True) image = models.ImageField(upload_to="img", blank=True, null=True) def __str__(self): return self.title -
Query all objects by date | Django REST framework
I would like to add an URL like 'reports//month/' and list all the reports that I have for that month of that year Currently, my view.py is like that : class ReportViewSet(viewsets.ModelViewSet): queryset = Report.objects.all() serializer_class = ReportSerializer class ReportGroupData(ListAPIView): queryset=Report.objects.annotate(month=TruncMonth('date')).values('month').annotate(count=Count('id')).values('month', 'count').order_by('-month') serializer_class = ReportGroupMonthSerializer In Django I did it like this : urls.py : path('reports/<int:year>/month/<int:month>', ReportMonthArchiveView.as_view(month_format='%m'), name='report_archive_month'), Views.py : class ReportMonthArchiveView(MonthArchiveView): template_name = 'dashboard/reports_month.html' queryset = Report.objects.all() date_field = "date" allow_future = True paginate_by = 7 What are the steps to have something similar in DRF? Thanks! -
deleting data from the model django after a certain time
my model : class Registration(models.Model): fio = models.CharField(verbose_name = 'fio', max_length = 100, null=True) phone = models.CharField(verbose_name ='phone', max_length = 16, null=True) date_register = models.DateTimeField(verbose_name = 'date registers', max_length = 100, null=True) date_visit = models.DateField(verbose_name = 'date visit', blank=True, null=True) time_visit = models.CharField(verbose_name = 'time visit', null=True,max_length = 100) verification = models.BooleanField(default=False) upon registration, it must be confirmed by mail. How can automatic deletion of records be implemented if the registration is not confirmed after a certain period of time? decided to use the management command to delete (so far just all unconfirmed). It is launched by the manage.py del command. The code itself: import datetime from django.core.management.base import BaseCommand from django.utils import timezone from registers.models import Registration class Command(BaseCommand): help = 'delete unverified users' def handle(self, *args, **kwargs): regs = Registration.objects.filter(verification__in=["False"]) for a in regs: if a.date_register <= (datetime.datetime.now() - datetime.timedelta(minutes=10)): rg = Registration.objects.get(date_register = a.date_register.strftime("%Y-%m-%d %H:%M:%S")) rg.delete() How to make this command work even when the site starts every hour (p.s. after running the manage.py runserver command) -
Error uploading resized image to Google cloud storage
I'm trying to upload a resized image to google storage, but it throws the following error. Size 9422 was specified but the file-like object only had 9308 bytes remaining. Here is the code below. This works fine in my local machine without google storage. thus, i guess there should be some google setting models.py class Product(models.Model): image=models.ImageField(default='default.jpg',upload_to='productimages') def compressImage(self,uploadedImage): imageTemproary = Image.open(uploadedImage) outputIoStream = BytesIO() imageTemproary = imageTemproary.resize( (400,300) ) imageTemproary.save(outputIoStream , format='JPEG', quality=60) outputIoStream.seek(0) uploadedImage = InMemoryUploadedFile(outputIoStream,'ImageField', "%s.jpg" % uploadedImage.name.split('.')[0], 'image/jpeg', sys.getsizeof(outputIoStream), None) return uploadedImage def save(self, *args, **kwargs): self.image = self.compressImage(self.image) super(Product,self).save(*args, **kwargs) I Even tried the another method to resize image using thumbnail, but i ran into another error this backend doesn't support absolute paths code below models.py class Product(models.Model): image=models.ImageField(default='default.jpg',upload_to='productimages') def save(self): super().save() img=Image.open(self.image.path) outputsize=(400,300) img.thumbnail(outputsize) img.save(self.image.path) Please help me get the resized image uploaded. -
Unable to commit changes after running pre-commit hooks for django project
here is my pre-commit-config.yaml default_language_version: # force all unspecified python hooks to run python3 python: python3 fail_fast: true repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v2.3.0 hooks: - id: check-ast - id: check-byte-order-marker - id: check-builtin-literals - id: check-case-conflict - id: check-docstring-first - id: check-json - id: pretty-format-json args: [--autofix] - id: check-merge-conflict - id: check-symlinks - id: check-toml - id: check-vcs-permalinks - id: check-xml - id: check-yaml - id: debug-statements - id: detect-aws-credentials - id: detect-private-key - id: end-of-file-fixer - id: file-contents-sorter - id: fix-encoding-pragma - id: forbid-new-submodules - id: mixed-line-ending - id: name-tests-test - id: no-commit-to-branch args: [--branch, develop, --branch, master] - id: requirements-txt-fixer - id: sort-simple-yaml - id: trailing-whitespace - repo: https://github.com/pre-commit/mirrors-autopep8 rev: v1.4.4 hooks: - id: autopep8 - repo: https://github.com/pre-commit/pre-commit rev: v1.18.3 hooks: - id: validate_manifest - repo: https://github.com/asottile/pyupgrade rev: v1.25.1 hooks: - id: pyupgrade - repo: meta hooks: - id: check-useless-excludes - repo: https://github.com/ambv/black rev: 19.3b0 hooks: - id: black language_version: python3.7 args: [-S, -l 99, --exclude="migrations|.venv|node_modules"] - repo: https://github.com/egichuri/mirrors-future rev: 1fed4cb06bab1cc93e42b080b6645dd47e029b04 hooks: - id: future - repo: https://github.com/asottile/seed-isort-config rev: v1.9.3 hooks: - id: seed-isort-config - repo: https://github.com/pre-commit/mirrors-isort rev: v4.3.21 hooks: - id: isort After running git add . then git commit, most test pass but then … -
Can Django create a default row in a new table for each row in an existing table?
I have a company table populated with data. The need to introduce branches table has arisen. What mechanic would be used in Django to use the existing data in the company table to create a basic branch entry for each of the existing company entries. "Company A will get a default HQ branch as part of the migration." Is there a way to tie a function to the migration or would I need to create a custom migration that performs the operation after the table creation procedure is handled? -
Javascript qurryselectors not reading classes and ID when used in Django project
when I am working outside Django file, everything works fine with javascript reading classes and Ids like document.querySelector('.class_name').addEventListener. But when loaded in Django projects it gives an error that eventlistner can't read NULL. <script type="text/javascript" src="{% static 'info/js/for_recrs.js' %}"></script> <link href="{% static 'info/css/for_recrs.css' %}" rel="stylesheet" type="text/css" /> {% endblock %} ``` -
can't send post data to api in django
i can't send post data to api using django rest framework. i used postman to send data only user part is adding to the database , the activity of user is rejecting . i can't figure out problem can anyone help me to solve this problem sending post data to api { "name": "karen", "username": "karen", "timezone": "US/Samoa", "activity_periods": [ { "log_in": "2020-06-09T21:53:25.120897Z", "log_out": null }, { "log_in": "2020-06-09T22:02:35.289891Z", "log_out": null }, { "log_in": "2020-06-09T22:03:36.425212Z", "log_out": null } ] } but only the user data is stored the activity is ignored like this { "name": "karen", "username": "karen", "timezone": "US/Samoa", "activity_periods": [] } how can i add activity data to user...? models.py class User(models.Model): name = models.CharField(max_length=20) username = models.CharField(max_length=20) password = models.CharField(max_length=20) timezone = models.CharField(max_length=32, choices=TIMEZONES, default='UTC') def __str__(self): return self.name class Activity(models.Model): user = models.ForeignKey(User, related_name="activity_periods",on_delete=models.CASCADE,null=True, blank=True) log_in = models.DateTimeField(null=True, blank=True) log_out = models.DateTimeField(null=True, blank=True) def __str__(self): return self.user.name serializers.py class ActivitySerializer(serializers.ModelSerializer): class Meta: model = Activity fields = ['log_in', 'log_out'] class UserSerializer(serializers.ModelSerializer): # Passing login Logout to User activity_periods = ActivitySerializer(many=True, read_only=True) class Meta: model = User fields = ['name', 'username','timezone', 'activity_periods'] views.py class ActivityListView(generics.ListCreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer name = "activity-list" urls.py path('rest/',views.ActivityListView.as_view()) how … -
Django Autocomplete Light create_field Not Working
I really want to be able to use the django-autocomplete-light to enable users to create new Franchise names when they use the autocomplete box. I have set this up, but I don't get the option to create. I can see in the documentation about adding permissions, but I don't quite understand where it is done and also if I run in the shell, I get errors as below: >>> from user.models import User >>> user = User.objects.get(username="joeuser") >>> permission = Permission.objects.get(name='Can add franchise') >>> user.user_permissions.add(permission >>> user.user_permissions.add(permission) AttributeError: 'User' object has no attribute 'user_permissions' The form which uses it looks as below: franchisename = forms.ModelChoiceField(queryset=allfranchises,widget=autocomplete.ModelSelect2(url='/seasons/franchisesautocomplete/'),required=True) The url looks like: url(r'^franchisesautocomplete/', views.FranchiseAutocomplete.as_view(create_field='name'), name='franchiseautocomplete'), The view looks like: class FranchiseAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self, *args, **kwargs): user = getuser(self.request) if user == None: #Set a blank queryset if the user is not logged in qs = Franchise.objects.none() else: qs = Franchise.objects.all() return qs The autcomplete works in terms of returning the result set to the choice box, just can't get the create to work. Please can someone help. -
"TypeError: fs.existsSync is not a function" React
Started receiving this error when opening my react project: TypeError: fs.existsSync is not a function Traceback in browser: Now I believe that this is nodejs code trying to execute in the browser, but how is this happening? Uncaught TypeError: fs.existsSync is not a function at Object.hasBinary (extensions.js:405) at push../node_modules/node-sass/lib/binding.js.module.exports (binding.js:11) at Object.<anonymous> (index.js:14) at Object../node_modules/node-sass/lib/index.js (index.js:471) at __webpack_require__ (bootstrap:784) at fn (bootstrap:150) at Module../src/App.js (lib sync:9) at __webpack_require__ (bootstrap:784) at fn (bootstrap:150) at Module../src/index.js (index.css?f3f6:45) at __webpack_require__ (bootstrap:784) at fn (bootstrap:150) at Object.1 (utility.js:6) at __webpack_require__ (bootstrap:784) at checkDeferredModules (bootstrap:45) at Array.webpackJsonpCallback [as push] (bootstrap:32) at main.chunk.js:1 -
Mailchimp object not found django ('module' object has no attribute 'Mailchimp')
I wanted to use mailchimp in my Django app. so I did the following: pip install mailchimp and in my view.py I'm doing this def testtemplates(request): API_KEY = settings.MAILCHIMP_API_KEY LIST_ID = settings.MAILCHIMP_LIST api = mailchimp.Mailchimp(API_KEY) return HttpResponse(escape(repr(api))) l = api.lists.subscribe(LIST_ID, {'email': 'test@mail.com'}) While I can see the class Mailchimp in venv/lib/python2.7/site-packages/mailchimp.py I'm getting this error when I simply the URL 'module' object has no attribute 'Mailchimp' I believe I'm using the package correctly there must be some small stupid error or something which is out of my sight. Let me know if there's anything else to add Any help appreciated, Thanks -
How to add Thousand Separator to number in Javascript / Python / Django
I wanted to ask how to add thousand separator to the number when I type the number and also to the output. For example 10 000 becomes 10,000. I tried to use Django intcomma but it's not working. Really appreciate if you guys can help me with this. Below is my code : HTML <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" /> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <br /> <br /> <div class="form-group"> <form name="add_price" id="add_price"> <div class="table-responsive"> <table class="table table-bordered" id="price"> {{ priceformset.management_form }} {% for price in priceformset %} <tr> <td>{{ product.product_price }}</td> <td>{{ product.product_quantity }}</td> <td>{{ product.product_total_price }}</td> </tr> {% endfor %} </table> <input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" /> </div> </form> </div> </div> </body Javascript $('.textInput').on('change keyup', function() { product_total_price=0; var product_price= Number($('#id_Product-0-price').val()); var product_quantity= Number($('#id_Product-0-quantity').val()); product_total_price= product_price * product_quantity; $('#id_Product-0-total_price').val(product_total_price); }); Models.py class Price (models.Model): product_price = models.CharField(max_length=512,null=True,blank=True) product_quantity = models.CharField(max_length=512,null=True,blank=True) product_total_price= models.CharField(max_length=512,null=True,blank=True) Forms.py class PriceForm(forms.ModelForm): product_price =forms.CharField(required=False,label=('Price'),widget=forms.TextInput( attrs= { "class":"textInput form-control", "placeholder" : "Price" })) product_quantity =forms.CharField(required=False,label=('Quantity'),widget=forms.TextInput( attrs= { "class":"textInput form-control", "placeholder" : "Quantity" })) product_total_price =forms.CharField(required=False,label=('Total Price'),widget=forms.TextInput( attrs= { "class":"textInput form-control", "placeholder" : "Total Price" })) class Meta: model = Price fields = ('__all__') -
Django: Send API Key in response on successful authentication
I have created a Django(1.8) API to authenticate a user and on successful authentication create an API key and send it back as a response. The tricky part is that on successful authentication i would also need to redirect the user to another HTML page. I came across an answer where the api key is included in the context and then used in a hidden input field inside the HTML but this wont be secure. So what would be a secure way to send the API key and at the same time redirect to another HTML page My View: class LoginView(View): """On successful authentication return the api key.Authentication only if valid api identifier found in the request""" def post(self, request): try: username = request.POST['username'] password = request.POST['password'] app_id = request.GET['app_identifier'] context={} try: ConsumingAppInfo.objects.get(app_identifier=app_id) except Exception: raise Exception('Invalid app identifier found in the request') user = authenticate(username=username,password=password) if user is None: return HttpResponse('Invalid user credentials provided', status=400) request.session['user_id'] = user.id # Create API Key on first time login for the consuming user and return the same on any other subsequent # requests app_credentials,created = ConsumingAppAuth.objects.get_or_create(consuming_app_id=app_id, defaults={ 'api_key': str(uuid.uuid4())+'_'+str(datetime.now()), 'created_on': datetime.now(), 'consuming_app_id': app_id}) context['api_key'] = app_credentials.api_key return render(request,'response.html',context) except Exception as e: … -
Input field mask in Django
I am trying to create a mask for an input field for my Django field ex: (000) 000 000. I can't seem to get it working. Has anyone found a way to do this yet? -
How to prevent flushing data in test database after every test case in Django
I am currently writing my first Django application and writing selenium test cases for testing the UI. I am using the Django test case class for testing the app. This is the configuration for running test cases: "configurations": [ { "name": "test", "type": "python", "request": "launch", "program": "${workspaceFolder}\\manage.py", "args": [ "test", "review.tests.test_selenium.ReviewTests.test_app", "--keepdb" ], "django": true } This configuration uses the existing test database and I have to add data in the tables each time I run a new test case. Is there any way to preserve data after running test-cases? Thanks In Advance. -
Django: Send API Key back to the user on successful authentication
I have a requirement to create Django(1.8) API for authenticating end users of an external consuming app. The user along with the username and password would need to provide a valid app identifier as part of the URL.This app identifier would already be mapped to the consuming app in the database.The user would be authenticated only on providing a valid app identifier.My understanding is that this can be achieved using a hidden input form field which would then be appended to the URL My View: class LoginView(View): """On successful authentication return the api key.Authentication only if valid api identifier found in the request""" def post(self, request): try: username = request.POST['username'] password = request.POST['password'] app_id = request.GET['app_identifier'] try: ConsumingAppInfo.objects.get(app_identifier=app_id) except Exception: raise Exception('Invalid app identifier found in the request') user = authenticate(username=username,password=password) if user is None: return HttpResponse('Invalid user credentials provided', status=400) request.session['user_id'] = user.id # Create API Key on first time login for the consuming user and return the same on any other subsequent # requests app_credentials,created = ConsumingAppAuth.objects.get_or_create(consuming_app_id=app_id, defaults={ 'api_key': str(uuid.uuid4())+'_'+str(datetime.now()), 'created_on': datetime.now(), 'consuming_app_id': app_id}) return JsonResponse({'api-key': app_credentials.api_key}) except Exception as e: return HttpResponse("Invalid request.Please verify the request parameters.Error Message: "+str(e), status=400) My Form: <form method="POST" action="/login"> <div class="form-group"> …