Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get a specific foreign key value
My models.py look like that: class Order(models.Model): items = models.ManyToManyField(OrderItem) class OrderItem(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) class Item(models.Model): quantity = models.IntegerField(default=1) In my function I have access to the Order table and I am trying to get information about the quantity of Item. I tried that: order.items.item.quantity, but I get that error: 'ManyRelatedManager' object has no attribute 'item' How would I get the quantity number from Item table? -
Django User not Logging in After Being Created Using Registration Form
I am pretty new at Django and I just got my project onto a Ubuntu server using nginx and uwsgi. When I try to login using a user I created on the front-end, Django tells me that either the username or password was incorrect. These problems did not occur when working on localhost, only now in production. I am just using the base django user model creating my users in views.py class CreateUser(FormView): def get(self, request): form = UserCreationForm context = {'form': form} return render(request, 'VR360/register.html', context) def post(self, request): form = UserCreationForm(request.POST) if form.is_valid(): user = user_form.save(commit=False) user.set_password(user_form.cleaned_data['password'] user.save() messages.success(request, 'User was saved') print("Creating the user was successful") return HttpResponseRedirect("main:homepage") else: for msg in form.error_messages: print(form.error_messages[msg]) messages.error(request,':( Your passwords do not match or it did not meet the below criteria') return redirect("main:register") I know that the user is being saved to the database because 'meme' was created using the registration page >>> from django.contrib.auth.models import User >>> def username_present(username): ... if User.objects.filter(username=username).exists(): ... return True ... ... return False ... >>> username_present('meme') True >>> I authenticate the user using django's login.html {% block content %} {% if form.errors %} <p> An error occured :(</p> <p>Your username and password didn't … -
Django registration serializers
Hello every one i need to make three apis for Login , registration and logout...can i make three api with these one serializer...? serializers.py from django.contrib.auth.models import User from rest_framework import serializers from rest_framework.authtoken.models import Token class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ['id', 'username', 'email', 'password'] extra_kwargs = {'password': {'write_only': True, 'required': True}} def create(self, validated_data): user = User.objects.create_user(**validated_data) Token.objects.create(user=user) return user views.py from django.contrib.auth.models import User, Group from rest_framework import viewsets from .serializers import UserSerializer # from rest_framework.authentication import TokenAuthentication # from rest_framework.permissions import IsAuthenticated class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer # authentication_classes = (TokenAuthentication,) # permission_classes = (IsAuthenticated, ) urls.py from django.urls import include, path from rest_framework import routers from .views import UserViewSet from rest_framework.authtoken.views import ObtainAuthToken router = routers.DefaultRouter() router.register(r'registration', UserViewSet) urlpatterns = [ path('', include(router.urls)), path('signIn/', ObtainAuthToken.as_view()) ] -
Django Simple Captcha HTML5 Validation Errors
I am not sure if the project maintainer for django-simple-captcha needs to fix their code to be HTML5 valid or if there is a way to fix the HTML5 validation errors using rendering method below. I would appreciate any assistance. https://django-simple-captcha.readthedocs.io/en/latest/advanced.html#rendering https://github.com/mbi/django-simple-captcha/blob/master/captcha/templates/captcha/hidden_field.html https://github.com/mbi/django-simple-captcha/blob/master/captcha/templates/captcha/field.html https://github.com/mbi/django-simple-captcha/blob/master/captcha/templates/captcha/text_field.html Attribute autocorrect not allowed on element input at this point. <input type="text" name="captcha_1" class="form-control mt-2" placeholder="Solve the captcha" required id="id_captcha_1" autocapitalize="off" autocomplete="off" autocorrect="off" spellcheck="false"></p> Attribute required not allowed on element input at this point. <input type="hidden" name="captcha_0" value="e83b1ca0e5149574b9b19098074dd3de390b339f" class="form-control mt-2" placeholder="Solve the captcha" required id="id_captcha_0"> Attribute placeholder is only allowed when the input type is email, number, password, search, tel, text, or url. <input type="hidden" name="captcha_0" value="e83b1ca0e5149574b9b19098074dd3de390b339f" class="form-control mt-2" placeholder="Solve the captcha" required id="id_captcha_0"> -------------- Forms.py: class CustomCaptchaTextInput(CaptchaTextInput): template_name = 'custom_field.html' class ContactForm(forms.Form): captcha = CaptchaField(widget=CustomCaptchaTextInput) def __init__(self, *args, **kwargs): super(ContactForm, self).__init__(*args, **kwargs) self.fields['captcha'].widget.attrs['class'] = 'form-control mt-2' self.fields['captcha'].widget.attrs['placeholder'] = 'Solve the captcha' self.fields['captcha'].label = "Enter the correct captcha as shown in the image" -------------- custom_field.html: {% load i18n %} {% spaceless %} <label class="control-label">{{ label }}</label> <img src="{{ image }}" alt="captcha" class="captcha" /> <br/> <audio class="w-100 mt-2" controls> <source src="{{ audio }}" /> … -
Limit mptt tree manager to only one tree node
using MPTTModelAdmin and DraggableMPTTAdmin through django admin is there any option to force only ONE TREE in the object? expected result: User should not be able to create any new Root Node or move an existing node to become a Root Node By manipulating the model, I can achieve some way around it, but it will casue throuble for future migrations class MySingleTree(MPTTModel): name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') #blank=False will prevent creating multiple root; null=False will prevent moving to become new root Thank you -
How do I run pytest for one testcase in a Django app when I have been using "python manage.py test" all this time?
Django v2.2 I have been writing my test case for 2 years now this way: from django.test import override_settings from rest_framework.test import APIClient, APITestCase from someapp.tests.factories import ( OrganizationFactory, ) class SomeTestCase(APITestCase): def setUp(self): self.maxDiff = None self.organization = OrganizationFactory(name="ENP", domain="localhost") @override_settings(ALLOWED_HOSTS=["*"]) def test_something(self): self.assertTrue(True) then I run python manage.py test logical.path.to.SomeTestCase.test_something --keepdb the --keepdb is to avoid thrashing the test database and rebuild from scratch My config.settings.test.py is """ With these settings, tests run faster. """ from .base import * # noqa from .base import env # GENERAL # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#debug DEBUG = False # https://docs.djangoproject.com/en/dev/ref/settings/#secret-key SECRET_KEY = env("DJANGO_SECRET_KEY", default="lKwzkRnq8dksTthPauE61WrNPVwA3HdnJtQ9HuIyCpBib5zCY06tFsD5TUpNlCnO") # https://docs.djangoproject.com/en/dev/ref/settings/#test-runner TEST_RUNNER = "django.test.runner.DiscoverRunner" # CACHES # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#caches CACHES = { "default": { "BACKEND": "django.core.cache.backends.locmem.LocMemCache", "LOCATION": "" } } # PASSWORDS # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#password-hashers PASSWORD_HASHERS = ["django.contrib.auth.hashers.MD5PasswordHasher"] # TEMPLATES # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#templates TEMPLATES[0]["OPTIONS"]["debug"] = DEBUG # noqa F405 TEMPLATES[0]["OPTIONS"]["loaders"] = [ # noqa F405 ( "django.template.loaders.cached.Loader", [ "django.template.loaders.filesystem.Loader", "django.template.loaders.app_directories.Loader", ], ) ] # EMAIL # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#email-backend EMAIL_BACKEND = "django.core.mail.backends.locmem.EmailBackend" # https://docs.djangoproject.com/en/dev/ref/settings/#email-host EMAIL_HOST = "localhost" # https://docs.djangoproject.com/en/dev/ref/settings/#email-port EMAIL_PORT = 1025 # Your stuff... # ------------------------------------------------------------------------------ The python manage.py test command worked Now i write a new test using pytest import pytest pytestmark … -
Reverse for 'probability' with arguments '('',)' not found. 1 pattern(s) tried: ['probabilities/(?P<probability_id>[0-9]+)$']
I have just started using django and have hit a road bump. I am trying to associate a probability.id with a url and keep receiving a "NoReverseMatch at /probabilities/". Every time I click the "Probabilities" link on my index page it crashed with aforementioned error. I am using django 3.0. Trace Back My trace back is telling me the error is within the " href="{% url 'probability_analysis_app:probability' probability.id %}">{{proability}}" in the template, probabilities.html I have tried configuring urls.py and have made sure my path is defined I have tried searching this error with more or less detail (None have helped me fix this issue) urls urls views views template template -
django runserver works, but with daphne there's an error
I have a django website with channels for websockets that is working on my local machine. I can call python manage.py runserver and the site runs fine, the frontend websocket connection can send and receive from the backend server. However, when I wrap the django code in a daphne call, it throws an error: daphne -b 0.0.0.0 backend.app_proj.asgi:application File "c:\projects\injurycheck\v1\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "c:\projects\injurycheck\v1\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "c:\projects\injurycheck\v1\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Program Files\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'pipeline' Can anyone say why the site builds correctly under runserver, but inside daphne it can't find an app that is actually included in INSTALLED_APPS? -
Django: the particuler user(driver) is not selected when submitting the post onto the database
am working on a project where I am using two main modules a normal user(Loader) and a Driver where loader can post their load and driver ship that load to starting to the final destination ... now I have a few problems while using two foreign keys in my model. one model for the post(where user post that load) and driver see that post and add their price to that post now I created a new model for a price where I inherit post model and user (driver) in my price model but when a driver submits their price ..the particular login driver is not selected in the database (admin). here is my post model.py (loader(user)) class Loader_post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE ,related_name="Loader") pick_up_station = models.CharField(max_length=150) destination_station = models.CharField(max_length=150) sender_name = models.CharField(max_length=150) phone_number = PhoneNumberField(null=False, blank=False, unique=True) receiver_name = models.CharField(max_length=150) sending_item = models.CharField(max_length=150) image_of_load = models.ImageField(default='',null=True) weight = models.CharField(max_length=150) metric_unit = models.CharField(max_length=30, default='') quantity = models.PositiveIntegerField() pick_up_time = models.DateField() drop_time = models.DateField() amount = models.CharField(max_length=150, null=True) paid_by = models.CharField(max_length=150) created_at = models.DateTimeField(auto_now=True) published_date = models.DateField(blank=True, null=True) def __str__(self): return self.user.username def publish(self): self.published_date = timezone.now() self.save() def approve_prices(self): return self.prices.filter(approved_price=True) def get_absolute_url(self): return reverse("Loader:my_job", kwargs={"pk": self.pk}) here is my price … -
Is it pythonic/Djangoic for Model A's methods to reference Model B?
Presume I have these classes: class Book(models.Model): title = models.CharField() authors = models.ManyToManyField(Author) def display_text(self): return f"{self.title} by {','.join([x.name for x in self.author_set.all()])}" class Author(models.model): first_name = models.CharField() last_name = models.CharField() def name(self): return f"{self.first_name} {self.last_name}" Is it normal/acceptable/the standard way of doing things to have the attributes of one model refer to another this way? This is a heated debate at work, with the two sides being "don't do that, it can promote query count leaks" and "this is much more readable than most alternatives". Is there a community-standard take on this problem? -
TypeError: int() argument must be a string, a bytes-like object or a number, not 'DCountry'
I am getting the captioned error whenever i try the below code: DCountryObj = DCountry.objects.filter(CountryCode=NewInputRefObj.CountryCode).get() I dont quite understand what its talking about because I am simply taking the countrycode from one object to use in a filter for another model object creation. See relevant models: class DCountry(models.Model): CountryCode = models.IntegerField(primary_key=True) Country = models.CharField(max_length=15) SPI = models.IntegerField() def __str__(self): return self.Country NewInputRefObj refers to a object made from the following model: class InputRef (models.Model): CountryCode = models.ForeignKey(DCountry, on_delete=models.CASCADE) Please point me in the right direction for what I should try here because i dont understand why its saying it has an issues with int()??? -
Django: Adding data to many to many fields
Everytime I try to add data to my many to many fields in Django, it just adds all the existing data from the relating table. I was researching possible solutions and I was thinking I could possibly overwrite the save method but there did not seem to be a clear way to do that. I need to be able to add a list of songs ids (our_id) to Playlist tracks and add multiple users to the Playlists users field. models.py from django.db import models from django.contrib.auth.models import User import uuid # Create your models here. class Track(models.Model): track_name = models.CharField(max_length=500) album_name = models.CharField(max_length=500) artist_name = models.CharField(max_length=500) album_pic = models.CharField(max_length=500) our_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) spotify_url = models.CharField(max_length=500, default=None) apple_url = models.CharField(max_length=500, default=None) def __str__(self): return self.track_name class Playlist(models.Model): playlist_name = models.CharField(max_length=500) tracks = models.ManyToManyField(Track, default=None) users = models.ManyToManyField(User, blank=True, default=None) def __str__(self): return self.playlist_name class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) target = models.ForeignKey(User, related_name='followers', on_delete=models.CASCADE) follower = models.ForeignKey(User, related_name='targets', on_delete=models.CASCADE) playlists = models.ManyToManyField(Playlist, default=None) def __str__(self): return self.user.username views.py def add_to_playlist(request): # 1) get the track name that is selected # 2) Get the track ID for that track # 3) Add that ID for each of the playlists if … -
Check User Perms Django
I am trying to use Django's default permissions to only show the link to the blog post page if they have the blog post permissions. The wonderful Django documentation provides the following: Assuming you have an application with an app_label foo and a model named Bar, to test for basic permissions you should use: add: user.has_perm('foo.add_bar') change: user.has_perm('foo.change_bar') delete: user.has_perm('foo.delete_bar') view: user.has_perm('foo.view_bar') My app is named about Here is my model: # models.py class BlogPost(models.Model): title = models.CharField(max_length=120) description = models.TextField(max_length=250, null=True) image = models.ImageField(upload_to='blog/main') content = HTMLField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) draft = models.BooleanField(default=False) def __str__(self): return self.title def get_absolute_url(self): return reverse("post-detail", kwargs={"pk": self.id}) Here is my HTML where I am trying to filter # base.html {% if user.has_perm('about.add_blogPost') %} <li {% if url_name == 'post' %}class="nav-item active"{% else %}class="nav-item"{% endif %}><a href="{% url 'post' %}" class="nav-link">Add Post</a></li> {% endif %} Whenever I follow it just as the documentation has written, I get: Could not parse the remainder: '('about.add_blogPost')' from 'user.has_perm('about.add_blogPost')' What am I doing wrong? -
Use Custom manager methods for data migrations in Django
I have a queryset class CustomQuerySet(models.query.QuerySet): def a(self): return 'something' class CustomQuerySetAllObjectsQuerySet(CustomQuerySet): def xyz(self): return 'something' class Custom(RemoteObjectQuerySet): all_objects = CustomQuerySetAllObjectsQuerySet.as_manager() I want to use the manager methods in my data migration. I read that we can use use_in_migrations = True to be set on Manager. But here since I am using as_manager(), will it still inherit this use_in_migrations. Also, how do I verify if I can use these manager methods for data migration. -
django queryset can not distinct the result with using Subquery?
I want to aggerate the work count of using the same video resource, and the user count that need distinct user. then I tried two method but got the different result. PROBLEM IS: the two qsets result is different. qset1 is correct, but qset2 is wrong that can not exclude the same users. MY QUESTION IS: what should I do if not to use RawSQL like qset1, and can get the right result. #models concerned class Video(models.Model): name = models.CharField(max_length=100, verbose_name=_('video name')) class Work(models.Model): video = models.ForeignKey(Video, on_delete=models.CASCADE, related_name='works_of_video', verbose_name=_('video')) maker = models.ForeignKey(User, on_delete=models.CASCADE, related_name='works_of_maker', verbose_name=_('maker')) #rawsql for get_queryset() video_sql = u'''SELECT COUNT(*) AS "num" From (SELECT DISTINCT maker_id FROM "video_manage_work" U0 INNER JOIN "video_manage_demouser" U2 ON (U0."maker_id" = U2."id") WHERE (U0."video_id" = ("video_manage_video"."id") AND U2."gender" IN (%s)) )''' #views concerned def get_queryset(request): what_gender = (0, 1) vall = Video.object.all() works = Work.objects.filter(video=OuterRef('pk')).filter(maker__gender__in=what_gender) works_makers = works.values('maker','video').distinct() # the next annotate use RawSQL of video_sql qset1 = vall.annotate(works_num=Subquery(works.values('video').annotate(num=Count('*')).values('num'), output_field=IntegerField()))\ .annotate(makers_num=RawSQL(video_sql, (gender_str,))) # the next annotate use Subquery that try to distinct queryset that excluded the same users qset2 = vall.annotate(works_num=Subquery(works.values('video').annotate(num=Count('*')).values('num'), output_field=IntegerField()))\ .annotate(makers_num=Subquery(works_makers.values('video').annotate(num=Count('*')).values('num'), output_field=IntegerField())) return render(request, 'video_manage/video_data.html') ''' ######sql sentenc of qset2 created by django: SELECT "video_manage_video"."id", "video_manage_video"."name", (SELECT COUNT(*) AS "num" … -
Django: Unsure why I'm getting CSRF error
I'm writing a Django app and my registration page raises a 403 error: Forbidden (403) CSRF verification failed. Request aborted. Reason given for failure: CSRF token missing or incorrect. Here's the view: def register(request): form = UserCreationForm(request.POST) if form.is_valid(): form.save() return redirect('login') return render(request, "register.html", {'form' : form}) Here's the form in the relevant template: {% block content %} <form method="POST"> {% csrf_token %} {% for field in form %} <p> {{ field.label_tag }} {{ field }} </p> {% endfor %} <button type="submit" class="button">Register</button> </form> {% endblock %} Some relevant facts: (1) No other pages on my site throw this error even though many require CSRF tokens. (2) The code I use to insert the CSRF token is the same in this template as in others (unless my triple-checking has failed me). (3) [probably relevant?] This is the only form I'm importing directly into views.py without modifying first in forms.py. So, two lines of views.py are: from django.contrib.auth.forms import UserCreationForm [...] from foo.forms import FooForm, FooBarForm, UploadFooForm Any and all help appreciated. I've tried most of what I think are the obvious debugging steps (removing the {% csrf_token %} line, reading the debug output and ensuring [I think] that those … -
Is there a way to rename a file that i just uploaded to the django admin to something specific every time I add a file?
I'm trying to add a way to rename my filefields in the django admin after i upload them. I already created my own action: class renameFile(admin.ModelAdmin): actions = ['rename_file'] def rename_file(modeladmin, request, queryset): #queryset.update() rename_file.short_description = "Rename selected file" Where I commented queryset.update() i'd like to replace that with a way to rename my file in the django admin. Something like when you select the file and click rename selected file and hit 'Go', it brings up a box with a field that i can write something to rename it. Is this even possible? Im not sure if the django admin is so flexible with those kind huge modifications. Any help would be very much appreciated! -
Django migration: "0001_initial.py" dependency error
I just started to work on someone else's project which uses Django. After running this sequence: python manage.py makemigrations python manage.py migrate python manage.py runserver 127.0.0.1:8000 I got the error: django.db.migrations.exceptions.NodeNotFoundError: Migration structures.0002_auto_20171121_1034 dependencies reference nonexistent parent node ('structures', '0001_initial') The migrations folder contains 0002_auto_20171121_1034.py, 0003_auto_xxxxxxxx_xxxx.py, 0004_auto_xxxxxxxx_xxxx.py, 0005_auto_xxxxxxxx_xxxx.py, 0006_auto_xxxxxxxx_xxxx.py, 0007_auto_xxxxxxxx_xxxx.py. But it doesn't contain 0001_initial.py. What I tried: 1) I tried to delete all .pyc files of migrations folder. 2) I tried to remove these three lines: dependencies = [ ('structures', '0001_initial'), ] contained in 0002_auto_20171121_1034.py, but, this time, I got this error: You have 6 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): structures. Run 'python manage.py migrate' to apply them. Is there anyone who could help? -
invalid date django form validation
i'am learning django and building a CRUD but i'am getting an error in my form validation. This is the form that i created class addSignForm(forms.ModelForm): active = forms.CharField(max_length=10) class Meta: model = signs fields = ("id", "active", "action", "date", "expiration_date", "add_by", "user_sign") widgets = { 'date': forms.DateTimeInput(attrs={'type': 'datetime-local'}, format='%d/%m/%Y %H:%M'), } This is the date that im reciving from the request (also tried format: '%d %m %Y %H:M') '2000-04-16T18:57' And when i try to: if (form.is_valid()): says that it is an invalid form and that i typed an invalid date <li>Enter a valid date/time.</li></ul> can someone help me -
How to resolve the issue with Django 3 that resets the user session when it gets POST data from an external page
My url path in project's url.py is defined as follows: path('endpoint/', views.Endpoint.as_view(), name='get_endpoint'), The views.py include the following class to handle this routing: @method_decorator(csrf_exempt, name='dispatch') class Endpoint(View): def get(self, request, *args, **kwargs): ############ Here I can see the User Session ########## if not request.user.is_authenticated: return redirect('authentication_router') return redirect( 'https://app.globus.org/file-manager?method=POST&action=%s&cancelurl=%s&folderlimit=1&filelimit=0&label=%s' % ( request.build_absolute_uri(), "/", "To Transfer your Files Select the Folder first!") ) def post(self, request, *args, **kwargs): # On return from OAuth Page ############ Here, User Session return nothing so user is AnonymousUser ########## if request.POST.get('folder[0]'): # A Endpoint folder was selected endpoint_path = os.path.join(request.POST.get('path'), request.POST.get('folder[0]')) else: endpoint_path = request.POST.get('path') profile = request.user.userprofile # request.user does not has userprofile profile.endpoint_path = endpoint_path profile.save() return HttpResponseRedirect(reverse('authentication_router')) The problem is when the get is called it finds the request.user value as authenticated user but once the redirect from OAUTH page with POST hits the class it loss all request user session and gives error at this line: profile = request.user.userprofile As, request.user seems loss its session and has value of AnonymousUser even though till GET method it is preserving the user's login session values. My settings.py file includes: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', **'django.contrib.sessions',** 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'myapp', ] MIDDLEWARE = … -
Using Decorator for Oauth
I am trying to complete Oauth2 using Decorator in Django. Until before I tried using decorator, I was doing it using this endpoint oauth (which works alright): def oauth(request): if not request.GET.get('oauth_verifier'): return oscar_oauth_init(request) else: res = oscar_oauth_accesstoken(request) return res def oscar_oauth_init(request): oauth = OAuth1(OSCAR_CLIENT_ID, client_secret=OSCAR_CLIENT_SECRET) url=OSCAR_INIT_URL+OSCAR_CALLBACK_URL r = requests.get(url=url, auth=oauth) credentials = parse_qs(r.content) credentials = convert(credentials) resource_owner_key = str(credentials.get('oauth_token')[0]) resource_owner_secret = str(credentials.get('oauth_token_secret')[0]) verifier = oscar_oauth_auth(resource_owner_key) request.session['resource_owner_key'] = str(resource_owner_key) request.session['resource_owner_secret'] = str(resource_owner_secret) request.session['verifier'] = str(verifier) return verifier def oscar_oauth_accesstoken(request): verifier = request.GET.get('oauth_verifier') resource_owner_key = request.GET.get('oauth_token') resource_owner_secret = request.session.get('resource_owner_secret') oauth = OAuth1(OSCAR_CLIENT_ID, client_secret=OSCAR_CLIENT_SECRET, resource_owner_key=resource_owner_key, resource_owner_secret=resource_owner_secret, verifier=verifier) if not verifier: return r = requests.get(url=OSCAR_TOKEN_URL+verifier, auth=oauth) credentials = parse_qs(r.content) credentials = convert(credentials) resource_owner_key = credentials.get('oauth_token')[0] resource_owner_secret = credentials.get('oauth_token_secret')[0] request.session['resource_owner_key'] = str(resource_owner_key) request.session['resource_owner_secret'] = str(resource_owner_secret) return credentials This endpoint was required to be called before other API calls that needed user to be authorized. I am trying to refactor this using the following decorator now: def oscar_login(view_func): def _wrapped_view_func(request, *args, **kwargs): if not request.GET.get('oauth_verifier'): return oscar_oauth_init(request) else: return oscar_oauth_accesstoken(request) return view_func(request, *args, **kwargs) I am not sure how to complete the redirection bit using the decorator. I allowed redirection to the same endpoint oauth (shared above) but the flow stops at end of the … -
Are there tools to generate CRUD operations from a given schema in Node.js/Angular/MongoDB or Flask/Django?
I recently got to know an amazing tool that generates CRUD operations from a given schema in Phoenix/Elixir. The command is- phx.gen.html DBName Table tables age:integer title:string This would generate Create, Read, Edit, and Delete operations connected to a Database in Phoenix/Elixir backend along with some strong tests too. Are there such tools available in Node.js or Flask/Django as well? Like automatic code generators for these frameworks? -
Django url with multiple parameters
I am trying to pass a URL with multiple parameters however, I keep getting NoReverseMatch Error. I have tried printing the parameters and they are printed correctly. Howver, I still get an error. My view: @login_required def comment_like(request,guid_url,id): data = dict() comment = get_object_or_404(Comment, id=id) user = request.user if request.method == 'POST': if comment.likes.filter(id=user.id).exists(): comment.likes.remove(user) else: comment.likes.add(user) data['comment'] = render_to_string('home/posts/comment_like.html',{'comment':comment},request=request) return JsonResponse(data) my link: action="{% url 'home:comment-like' post.guid_url comment.id %}" and my url: path('post/<str:guid_url>/comment/<int:id>/like/', views.comment_like, name='comment-like'), The error I get: django.urls.exceptions.NoReverseMatch: Reverse for 'comment-like' with arguments '('', 20)' not found. 1 pattern(s) tried: ['home/post/(?P<guid_url>[^/]+)/comment/(?P<id>[0-9]+)/like/$'] Thanks for all the help in advance! -
Why do I get 'ImproperlyConfigured' exception, implying circular imports?
I have had this issue before, but I've managed to find the circular import being referenced. I face it again, but I can't find the problem. My project's name is 'sare', and my sare/urls.py looks like this: from django.contrib import admin from django.urls import include, path urlpatterns = [ path('users/', include('users.urls', namespace='users')), path('admin/', admin.site.urls), ] And users/urls.py is this: from django.urls import path from .views import UsersTableView, UserCreateView, UserUpdateView, UserDeleteView app_name = 'users' urlpatterns = [ path('table/', UsersTableView.as_view(), name='users_table'), # path('create/', UserCreateView.as_view(), name='users_create'), # path('update/<int:pk>', UserUpdateView.as_view(), name='users_update'), # path('delete/<int:pk>', UserDeleteView.as_view(), name='users_delete'), ] The only piece of code that is not commented in my views is the UsersTableView, that looks like this: from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from .models import CustomUser from .tables import UsersTable from .filters import UserFilter from .form_helpers import UsersFilterFormHelper from django.views.generic import CreateView, UpdateView, DeleteView from .forms import UserForm from django.urls import reverse_lazy, reverse from django_tables2.export import ExportMixin from django_tables2 import RequestConfig,SingleTableView,Table as TableBase from django_filters import FilterSet class InitUserMixin(object): def __init__(self, *args, **kwargs): self.user = kwargs.pop("user", None) super(InitUserMixin, self).__init__(*args, **kwargs) class FilterUserMixin(InitUserMixin, FilterSet): pass class Table(InitUserMixin, TableBase): pass class PagedFilteredTableView(ExportMixin, SingleTableView): filter_class = None formhelper_class = None context_filter_name = 'filter' def get_queryset(self, **kwargs): qs = super(PagedFilteredTableView, … -
Django: How to handle error message in CreateView for UNIQUE constraint failed
I have a generic class based createview, which generates "UNIQUE constraint failed" error. I am able to handle this and redirect it to the same createview form. However i need to send an error msg to the createview saying 'Name already exists'. How to i achieve this. view.py class FeatureCreate(CreateView): model = Feature fields = ['name', 'summary'] def form_valid(self, form): form.instance.release_id = self.kwargs.get('pk') from django.db import IntegrityError from django.http import HttpResponseRedirect try: a = super(FeatureCreate, self).form_valid(form) except IntegrityError as e: if 'UNIQUE constraint failed' in e.args[0]: return HttpResponseRedirect(reverse_lazy('feature-create', args=(form.instance.release_id,))) return a url.py: path('release/<int:pk>/feature/create/', views.FeatureCreate.as_view(), name='feature-create'), feature_form.html: {% block content %} <form action="" method="post"> {% csrf_token %} <table> {{ form.as_table }} </table> <input type="submit" value="Submit"> <input type="button" value="Cancel" onclick="history.back()"> </form> {% endblock %} Any suggestions is welcome. Please help.