Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reset Password link for django not working
After sending a reset link and clicking it the link is not working it shows that it is not valid. Url for link path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), password_reset_email.html {{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %} Your username is {{ user.username }} password_reset_confirm.html {% if vaidlink %} <form method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Change Password"> </form> {% else %} <p> The password reset link was invalid, possibly because it has already been used. Please request a new password reset. </p> {% endif %}``` -
System error: null argument to internal routine in xmlsec
I am trying to implement SSO in a Django application. I have a ubuntu 16.04 OS, Apache and WSGI and python 3.5.2 The packages that I installed: xlmsec 1.3.3 lxml 4.5.1 pkg-config 1.5.1 python3-saml 1.9.0 And all the dependencies for xmlsec: libxmlsec1-dev libxml2-dev libxmlsec1-openssl My server is behind a proxy (I dont have full access to that server) trying to install xlmsec >= 1.3.7 throws me a connection error, that why I used 1.3.3 version. Once I run the following command I get the error: python -c "import xmlsec" func=xmlSecOpenSSLAppKeyLoadMemory:file=app.c:line=188:obj=unknown:subj=data != NULL:error=100:assertion: func=xmlSecCheckVersionExt:file=xmlsec.c:line=185:obj=unknown:subj=unknown:error=19:invalid version:mode=exact;expected minor version=2;real minor version=2;expected subminor version=30;real subminor version=20 func=xmlSecOpenSSLInit:file=crypto.c:line=312:obj=unknown:subj=xmlSecCheckVersionExact:error=1:xmlsec library function failed: func=xmlSecOpenSSLAppPkcs12Load:file=app.c:line=580:obj=unknown:subj=filename != NULL:error=100:assertion: Traceback (most recent call last): File "", line 1, in SystemError: null argument to internal routine I am not sure if it could be something about wrong versions or related to xlmsec issue (I already tried to rollback to older versions and have the same issue). -
Django form validation not passing to cleaned_data, data is there though
So I am not actually adding any of the data in the form data to a database, it is going to run through a program to edit paragraphs. I'm having trouble getting the response to clean the data. I can retrieve the data normally but it doesn't get added to the clean dictionary. I assume it's because I overwrote the init method of the form but I'm totally getting stuck on how to fix it. If I can get away with not cleaning data, things will probably work, I'm new so I wonder what havoc that would cause in the end. My Form data: class GameForm(forms.Form): def __init__(self, *args, **kwargs): categories= kwargs.pop('categories', None) super(GameForm, self).__init__(*args, **kwargs) if categories: for i in range(0, categories[0]): j=i+1 self.fields["_noun_%d" % j] = forms.CharField(max_length=15, label=("Noun "+ str(j)+":")) self.fields["_noun_%d" % j].widget.attrs.update({'class': 'special'}) for i in range(0, categories[1]): j = i + 1 self.fields["_verb_%d" % j] = forms.CharField(max_length=15, label=("Verb "+ str(j)+":")) self.fields["_verb_%d" % j].widget.attrs.update({'class': 'special verb'}) for i in range(0, categories[2]): j = i + 1 self.fields["_adverb_%d" % j] = forms.CharField(max_length=15, label=("Adverb "+ str(j)+":")) self.fields["_adverb_%d" % j].widget.attrs.update({'class': 'special adverb'}) for i in range(0, categories[3]): j = i + 1 self.fields["_adjective_%d" % j] = forms.CharField(max_length=15, label=("Adjective "+ str(j)+":")) … -
cors issue with django, rest-framework and vue js
Im trying to create my first django application + rest-framework, in the frontend I use VueJS. backend path: http://127.0.0.1:8000/ frontend path: http://localhost:8080/ I read a lot of posts about this error but none works for me (maybe I need to save the changes migrate again or something, Im new to django) I get this Error on the frontend path: Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/todo' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. I installed 'corsheaders' and added it to the INSTALLED_APPS array, I added 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware' to the MIDDLEWARE array, I added CORS_ORIGIN_ALLOW_ALL = True what can cause this issue? -
accessing table fields using sessions in django
I have created session named id for each user. is there any way we can use this session id for retrieving data from the model. in my template I want to access college data (which is my model). how can i achieve this. Template: <div class="form-group"> <input type="hidden" class="form-control" id="clg_id" name="clg_id" value="{{request.session.id}}" required> </div> <div class="form-group"> <input type="hidden" class="form-control" id="institute_code" name="institute_code" value="{{c.institute_code}}" required> </div> i want to fetch institute_code, but {{c.institute_code}} isn't working as i never passed it from the view to this template. -
Queryset filtering by multiple FK attributes
My situation: I have django model HOST and model PACKAGE (with name and version) which has FK on host model. Now I need to filter all hosts which have packages with certain name and certain version.. therefore something like Host.objects.filter(name="best_package", version__in=['1.0','2.0']) This is all nice and easy, but I need to repeat this action for several packages so I would get host which has each of wished packages in one of the versions.. I tried two approached but both failed, first was applying filter above in the for loop, it was ugly but worked and as happy as I was I found out this isn't stable solution and some of my queries which I apply next SOMETIMES fails.. yes sometimes! As I said to my self I'm not going deeper in that hole of Django ORM magic I tried to build the query with Q. I ended up with following code pckgs_query = reduce( operator.and_, ( Q(packages__name=name, packages__version__in=versions) for name, versions in pckgs_dict.items() ) ) hosts = Host.objects.filter(pckgs_query) but unfortunately this isn't working properly, as I checked the SQL query it generates I'm sure it is looking for single PACKAGE object with all those parameters which of course does not … -
Using LIMIT SQL statement into Djnago prefetch_related - Prefetch
I'm using Django and Django-Rest-Framework and I have these two models: class Post(models.Model): ... some fields... class PostImage(models.Model): ... some fields... post = models.ForeignKey(Post, verbose_name=_('post'), related_name='gallery', on_delete=models.CASCADE) My serializers to retrieve the list of posts: class PostSerializer(serializers.ModelSerializer): gallery = PostImageSerializer(many=True) .... additional fields .... class Meta: model = Post And my view: class PostListAPIView(generics.ListAPIView): serializer_class = PostSerializer def get_queryset(self): app = self.request.app qs = Post.objects.prefetch_related( Prefetch('gallery', queryset=PostImage.objects.order_by('order')))\ .select_related('...')\ .filter(application=app, status_type=PostStatusType.ACTIVE)\ .order_by('-publication_date') return qs All works fine. Please note that I used prefetch_related and select_related to improove the queries. Now I would like to have, for each post, only the first image (not the entire gallery). So, I need to get only the first image. I can have this limit into my serializer using, for example, something like this: image = serializers.SerializerMethodField() and def get_image(self, obj): return PostImageSerializer(obj.gallery.first()).data But I think that using this approach I'm not able to use the LIMIT SQL statement for prefetch_related - Prefetch. Basically, in this case I will retrieve all associated images and into the serializer I can take only the first. But I would like to improove the query using the LIMIT. Is it possible? -
CSRF verification failed. Request aborted. Reason given for failure: CSRF token missing or incorrect. Using Django
I keep getting the message and have tried/ made sure: My browser is accepting cookies That the view function passes a request to the template's render method in the Views.py file: Views.py File ## **from django.shortcuts import render, redirect** from django.contrib.auth.models import User from django.contrib import auth def signup(request): if request.method == 'POST': # User has info and wants an account now! if request.POST['password1'] == request.POST['password2']: try: user = User.objects.get(username=request.POST['username']) return render(request, 'accounts/signup.html', {'error':'Username has already been taken'}) except User.DoesNotExist: user = User.objects.create_user(request.POST['username'], password=request.POST['password1']) auth.login(request,user) return redirect('home') else: return render(request, 'accounts/signup.html', {'error': 'Passwords must match'}) else: # User wants to enter info return render(request, 'accounts/signup.html') def login(request): if request.method == 'POST': user = auth.authenticate(username=request.POST['username'],password=request.POST['password']) if user is not None: auth.login(request, user) return redirect('home') else: return render(request, 'accounts/login.html', {'error': 'Usename or password is invalid'}) else: return render(request, 'accounts/login.html') def logout(request): if request.method == 'POST': auth.logout(request) return redirect('home') # Need to route to home page return render(request, 'accounts/signup.html') I have added {% csrf_token %} in the template for inside each POST form that targets an internal URL: <form class="form-signin" method="POST" action="{% url 'signup' %}"> {% csrf_token %} <input class="form-control" placeholder="Username" required autofocus type="text" name="username" /> <input class="form-control" placeholder="Password" required autofocus type="password" name="password1" … -
Template html form submit button in django is not working
I used django default template form to use submit a form. That form is working absolutely fine. But when i change the template to a customize format then the submit button does not work. I want to use customize form so that I can style it. employee_add_form.html: {% extends 'base.html' %} {% block content %} {% load static %} <link rel="stylesheet" href="{% static 'employee/css/master.css' %}"> {% load bootstrap4 %} <div class=""> <form class="form" action="{% url 'employee:employee-list' %}" method="post" id="employee_add_form"> {% csrf_token %} <!-- {% bootstrap_css %}--> {% bootstrap_javascript jquery='full' %} {{ form.media }} <div class="container"> <label for=""><b>Personal Info</b></label> <div class="border"> <div class="form-row"> <div class="col"> <label for="">First Name</label> {{ form.first_name}} </div> <div class="col"> <label for="">Last Name</label> {{ form.last_name}} </div> <div class="col"> <label for="">Photo ID</label> {{ form.photo_id }} </div> </div> <div class="form-row inline"> <div class="col-4"> <label for="">Gender</label> {{ form.gender }} </div> <div class="col-4"> <label for="">Blood Group</label> {{ form.blood_group }} </div> <div class="col-4"> <label for="">Religion</label> {{ form.religion }} </div> </div> <div class="form-row"> <div class="col"> <label for="">Date of Birth</label> {{ form.birth_date }} </div> </div> </div> </div> <div class="container"> <label for=""><b>Contact Info</b></label> <div class="border"> <div class="form-row"> <div class="col"> <label for="">Email</label> {{ form.email }} </div> <div class="col"> <label for="">Phone Number</label> {{ form.phone_number }} </div> <div class="col"> … -
Grouping results of a multi-model search in Django
I'm using the following code for my multi-model search in my Django application: model: class PostManager(models.Manager): def search(self, query=None): qs = self.get_queryset() if query is not None: or_lookup = (Q(title__icontains=query) | Q(body__icontains=query)| Q(slug__icontains=query) ) qs = qs.filter(or_lookup).distinct() return qs class Post(models.Model): [...] objects = PostManager() class EventManager(models.Manager): def search(self, query=None): qs = self.get_queryset() if query is not None: or_lookup = (Q(title__icontains=query) | Q(description__icontains=query) ) qs = qs.filter(or_lookup).distinct() # distinct() is often necessary with Q lookups return qs class Event(models.Model): [...] objects = EventManager() view: class SearchView(ListView): template_name = 'search.html' count = 0 def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['count'] = self.count or 0 context['query'] = self.request.GET.get('q') return context def get_queryset(self): request = self.request query = request.GET.get('q', None) if query is not None: blog_results = Post.objects.search(query) event_results = Event.objects.search(query) # combine querysets queryset_chain = chain( blog_results, event_results, ) qs = sorted(queryset_chain, key=lambda instance: instance.pk, reverse=True) self.count = len(qs) return qs return Post.objects.none() template: class_name.py: from django import template register = template.Library() @register.filter() def class_name(value): return value.__class__.__name__ template: {% load class_name %} {% for object in object_list %} {% with object|class_name as klass %} {% if klass == 'Post' %} <div class='row'> <div class='col-12'> Article: <a href='{{ object.get_absolute_url }}'>{{ object.title|highlight_search_term:query … -
Django add to watchlist No Jquery
I m trying to implement an Add to Watchlist link without utilization of Jquery, however, i am getting an error page not found after clicking the button. the startup model is created by one user and add to list is by another user. Models: class Startup ( models.Model ) : author = models.OneToOneField ( User , on_delete = models.CASCADE ) startup_name = models.CharField ( max_length = 32 , null = False , blank = False ) def __str__(self) : return str ( self.startup_name ) class Watchlist (models.Model): str_wl = models.ForeignKey(Startup, on_delete = models.CASCADE) wl = models.ManyToManyField(User, related_name = 'watchlist', blank = True) View for Global_list (listing) and watchlist function: @login_required @inv_required def global_list(request): startup = Startup.objects.all() return render(request, 'inv_template/global_list.html', {'startup': startup}) @login_required @inv_required def watchlist (request, pk): watch = get_object_or_404 ( Watchlist , pk = pk ) if request.user is not None: watch.watchlist.add ( request.user ) return redirect('/globallist') Global list that contain the watch list link: {% extends 'inv_template/inv_base.html' %} {% block content %} {% include 'inv_template/inv_nav.html' %} <div class="row" style="margin-top: 10px; font-size: 14px;background-color: rgba(255,255,255,0);"> {% for s in startup.all %} <div class="col-lg-12 col-xl-12"> <div class="card" style="margin-bottom: 10px;"> <div class="card-body shadow"> <div class="row"> <div class="col-lg-12 text-center d-lg-flex justify-content-lg-end align-items-lg-center"><a href="{% … -
Python manage.py runserver not responding
I am new to Python and trying to execute "python manage.py runserver" from the command line shell but nothing happens and it just goes to the next line without any error message. It was working fine earlier, and I realize that after I installed vcruntime140.dll and restarted the computer it stopped working. Please help -
In Django, how do I create a serializer that will auto-generate a primary key for a member of my model?
I'm using Django 3, the Django REST framework, and Python 3.7. I have the following models. Notice that the second is dependent upon the first ... class ContactMethod(models.Model): class ContactTypes(models.TextChoices): EMAIL = 'EMAIL', _('Email') PHONE = 'PHONE', _('Phone') type = models.CharField( null=False, max_length=5, choices=ContactTypes.choices, ) phone = PhoneNumberField(null=True) email = models.EmailField(null=True) class Meta: unique_together = ('phone', 'email',) ... class Coop(models.Model): objects = CoopManager() name = models.CharField(max_length=250, null=False) types = models.ManyToManyField(CoopType) addresses = models.ManyToManyField(Address) enabled = models.BooleanField(default=True, null=False) phone = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_phone') email = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_email') web_site = models.TextField() I would like to submit some JSON to create my model, so I created the below two serializers to help me ... class ContactMethodSerializer(serializers.ModelSerializer): class Meta: model = ContactMethod fields = ['type', 'phone', 'email'] def create(self, validated_data): contact_method = ContactMethod.objects.create(**validated_data) return contact_method def to_internal_value(self, data): if type(data) == dict: contatcmethod, created = CoopType.objects.create(**data) # Replace the dict with the ID of the newly obtained object data = contactmethod.pk return super().to_internal_value(data) ... class CoopSerializer(serializers.ModelSerializer): types = CoopTypeSerializer(many=True) addresses = AddressTypeField(many=True) class Meta: model = Coop fields = ['id', 'name', 'types', 'addresses', 'phone', 'enabled', 'email', 'web_site'] def to_representation(self, instance): rep = super().to_representation(instance) rep['types'] = CoopTypeSerializer(instance.types.all(), many=True).data rep['addresses'] = AddressSerializer(instance.addresses.all(), many=True).data … -
Django ManyToManyField admin page filter
I have the following models: class OrderItem(models.Model): item = models.ForeignKey(FoodDish, on_delete=models.CASCADE, blank=True, null=True) quantity = models.IntegerField(default=1) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) def __str__(self): return f"{self.quantity} of {self.item.name}" def get_total_item_price(self): return self.quantity * self.item.price class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) order_date = models.DateTimeField(blank=True, null=True) ordered = models.BooleanField(default=False) total_price = models.FloatField(blank=True, default=0.0) def __str__(self): return f"{self.user.username} ordered on {self.order_date}" Inside the administration page I want to see the items related to a certain order. When entering the page for a certain order however, the field that contains the ManyToManyField displays all the OrderItems in the database (with the entries that are related to the current order highlighted). Why does the datafield in the administration page display all those entries? When I add a new OrderItem to the database it also appears in the ManyToManyField even if there should be no link to the existing order entry. Then, is it possible to do a select before serving the admin page so I can get only those OrderItem instances that are linked to the current Order? -
Object repeated in DetailView's context
I have the following view in which I add extra context to send similar post to the template. class PostDateDetailView(DateDetailView): queryset = Post.published.all() date_field = "publish" month_format='%m' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) obj = self.get_object() post_tags_pks = obj.tags.all().values_list('pk', flat=True) similar_posts = self.queryset.filter(tags__in=post_tags_pks).exclude(pk=obj.pk) similar_posts = similar_posts.annotate(same_tags=Count('tags')).order_by('-same_tags','-publish')[:3] context["similar_posts"] = similar_posts print(context) return context The view works right, but when I print the context I get 'object' and 'post' (are the same object) {'object', 'post', 'view', 'similar_posts'} When I look into the function get_context_data from SingleObjectMixin it seems the result will be always duplicated: I mean, there will always be a self.object ['object'], and a context_object_name ['post']. def get_context_data(self, **kwargs): context = {} if self.object: context['object'] = self.object context_object_name = self.get_context_object_name(self.object) if context_object_name: context[context_object_name] = self.object context.update(kwargs) return super().get_context_data(**context) I would like to know if either there is a reason for that or if I'm missing something. Thanks in advance. -
Angular in Django not showing theme?
When I load my angular, it is fine. When I load my django, the calendar would shift far left and unable to close. In my angular: "styles" : [ "./src/styles.css", "./node_modules/handsontable/dist/handsontable.full.css", "./node_modules/@angular/material/prebuilt-themes/deeppurple-amber.css" ], I also tried importing the path in styles.css alone, removing ^ the above import. My django imports to index.html from angular dist/build <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"> <link rel="stylesheet" type='text/css' href="{% static 'assets/css/styles.css' %}"> <link rel="stylesheet" type='text/css' href="{% static 'assets/css/global.css' %}"> <link rel="stylesheet" type='text/css' href="{% static 'assets/css/nucleo-icons.css' %}"> <link rel="stylesheet" type='text/css' src="{% static 'assets/styles.css' %}"> <script type="text/javascript" src="{% static 'assets/polyfills-es5.js' %}"></script> <script type="text/javascript" src="{% static 'assets/polyfills.js' %}"></script> <script type="text/javascript" src="{% static 'assets/runtime.js' %}"></script> <script type="text/javascript" src="{% static 'assets/main.js' %}"></script> <script type="text/javascript" src="{% static 'assets/scripts.js' %}"></script> This is from my django build. This is from my angular build. -
Django: BooleanField not displayed with the 'default' CheckBoxInput but with Select?
I've just updated my one field of a model from IntergerField to BooleanField in order to have Checkbox in my admin form but it doesn't... Instead, It display a select list with 3 option (Unknown, Yes, No) As mentionned in the Django admin documentation, CheckBoxInput is the default widget so it shloudl works I try to 'force' CheckBoxInput defining a widget forms.CheckBoxInput but it doesn't works neither... I need this field to be editable. i verifiy that this not this option that prevent default widget but it isn't. models.py class Profile(SafeDeleteModel): _safedelete_policy = SOFT_DELETE_CASCADE pro_ide = models.AutoField(primary_key = True) user = models.OneToOneField(User, on_delete = models.CASCADE) site = models.ForeignKey(Site, on_delete = models.CASCADE) ... pro_mai = models.BooleanField("Send user login/password? (y/n)",default=0, null=True, blank=True) ... admin.py class ProfileFormAdmin(forms.ModelForm): FONCTIONS = Thesaurus.options_list(5,'fr') pro_mai = forms.BooleanField(label="Envoyer le mot de passe ? (Oui/Non)",required=False) pro_fon = forms.ChoiceField(label="Fonction", widget = forms.Select, choices = FONCTIONS) def send_login_password(modeladmin, request, queryset): queryset.update( pro_mai = 1, ) send_login_password.short_description = 'Envoyer login et mot de passe à l\'utilisateur' class ProfileAdmin(SimpleHistoryAdmin): list_display = ('name','contact','pro_mai','fonction',) list_editable = ('pro_mai',) exclude = ('pro_con','pro_lis_ran', 'pro_lis_rea', 'pro_lis_unb','pro_tel') search_fields = ['name'] actions = [send_login_password] form = ProfileFormAdmin -
Restart Nginx or reload certificate cache on cert change
Background: I am running an app inside Docker, that will be managed by random users that do often not have any knowledge about Docker itself. I am building the app to be as much configurable from the webserver itself as possible. It runs 3 non-root containers: Container 1: Gunicorn,Django,Certbot Container 2: Nginx Container 3: Postgresql I am able to let the Django app run certbot via the website itself to get a certificate and copy the certificate into the volume that nginx is using. But the old or self-signed certificate seems to be cached by nginx on startup and so the new certificate is not used until a restart of nginx. And here is the problem, I must now restart nginx or somehow reload the certificates automatically. Either by triggering the restart from the Django container to the Nginx Container maybe via a curl or something. Or I can use something like watchdog to watch the files for a file change. Question: What is the best approach to reload nginx automatically if a certificate changes? Or can I purge the certificate cache of the certificates even without restarting the server? What is your suggestion here? Thanks for your help in … -
How to mention static files in .js file for a django project?
I am facing an issue for mentioning one of the files in my django project for a .js file One of the lines in main.js reads navigator.serviceWorker.register("{% static '/static/sw.js' %}") but while running the project it says Not Found: /sw.js This is the directory structure - How should I mention the sw.js file in my main.js file to avoid fileNotFound error? Added to settings.py - STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), '/static/', ] urls.py includes urlpatterns = [ path('admin/', admin.site.urls), path('', index), path('/push_v1/', push_v1), path('/subscription/', subscription), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Complete error - -
BooleanField returning "on" instead of True/False
I have a boolean field which is returning "on" instead of True/False. When i print the request.POST queryDict i get something like this: <QueryDict: {is_superuser': ['on']}>` This is my form: class UserCreateForm(UserCreationForm): is_superuser = forms.BooleanField(label = 'Superuser', initial = False, required = False) class Meta(): fields = ('first_name', 'last_name', 'email', 'departments', 'password1', 'password2', 'is_superuser') model = get_user_model() def clean_is_superuser(self): return self.cleaned_data['is_superuser'] == True My view: class SignUpView(View): def get(self, request, *args, **kwargs): return render(request, 'accounts/signup.html', context = {'form':UserCreateForm}) def post(self, request, *args, **kwargs): form = UserCreateForm(request.POST) if form.is_valid(): user = form.save(commit = False) user.username = request.POST.get('email') user.is_superuser = request.POST.get('is_superuser') print(request.POST) user.save() return HttpResponseRedirect(reverse_lazy('accounts:allProfilesPage')) return HttpResponse('Form not valid') Why isn't the boolean field passing True or False? I even used the clean data function.. -
Django admin: add separators to model list (customization)
Let's say you have an installed app called "my_app". Inside this module you have models, each one related to an admin page. Accessing to {root}/admin/my_app you get the list of those models under "my_app". Is possible to customize this admin view? In particular, is it possible to add separators/dividers for that list? Example, from: My App Model 1 (add)(remove) Model 2 (add)(remove) Model 3 (add)(remove) Model 4 (add)(remove) to: My App Model 1 (add)(remove) Model 2 (add)(remove) configuration ---------------------------- Model 3 (add)(remove) Model 4 (app)(remove) -
Customizing Django authentication backend using a database view
I am trying to customize the default authentication backend for my django project (version 2.2.7), so i am implementing custom authentication backend. I have made a database view called v_auth_user which is my model. In the authentication backend I select from that view using a raw query (I need to use password_hash database function to verify password hash, hopefully it will work) Conserns: I need to specify User full_long_name and email when the user gets authenticated. How? Will all of this work? What are your thoughts? Model: class vAuthUser(models.Model): lb_id_no = models.IntegerField(primary_key=True) user_login_name = models.CharField(max_length=20) password = models.CharField(max_length=30) full_long_name = models.CharField(max_length=20) lb_email = models.EmailField(max_length=50) class Meta: managed = False db_table = 'v_auth_user' Custom authentication backend: from django.contrib.auth.models import User from erp.models import vAuthUser class OracleBackend: def authenticate(self, request, username=None, password=None): try: user = vAuthUser.objects.raw(f'select * from v_auth_user where user_login_name={username} and password=password_hash({username},{password}) and rownum=1') if user: return user except User.DoesNotExist: return None def get_user(self, lb_id_no): try: return vAuthUser.objects.get(pk=lb_id_no) except User.DoesNotExist: return None -
urls.py file in the backend folder - needs to locate index.html at frontend folder
I need to pass the route of my index.html file from the public folder at the frontend to the urls.py file that is located in the backend which is in another backend folder FOLDERS STRACTURE: backend -> backend -> urls.py frontend -> public -> index.html here is where I need to put that route so python will find my index.html file from django.contrib import admin from django.urls import include,path from .routers import router from django.views.generic import TemplateView urlpatterns = [ path('', TemplateView.as_view(template_name = '../../public/index.html')), ] I use VueJs in the frontend, that why I want to work organized and have dedicated frontend + backend libraries -
Get a status code using pytest and mock in django
I'm trying to get a status code for a test using mock. I'm doing something like this: def test_example(mocker): MyTest = mocker.patch("my_app_example.my_file_example.requests.post") test_ob_mock = Mock() test_ob_mock.status_code = 200 MyTest.return_value = test_ob_mock ... This way I get what I want (post returns a status code), but I was wondering if there is a better way to do it. -
How convert SQL to Django ORM
Need help to convert from SQL(PostgreSQL) to Django ORM SELECT task.lesson_id, task.name, task.content, task.max_score, MIN (log.action_time) AS created_at, MAX (log.action_time) AS modified_at FROM main_task task, django_admin_log log WHERE log.content_type_id=11 and task.id=CAST(log.object_id AS INTEGER) GROUP BY task.id, log.object_id ORDER BY modified_at DESC LIMIT 10 Thanks!