Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to get user object and pass it to form field in django
is there a better way to get the user object from the code below in forms.py? models class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ... forms.py class FooForm(forms.Form): def __init__(self, *args, **kwargs): self.request = kwargs.pop("user") super(ExperienceStart, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'post' self.helper.layout = Layout(InlineRadios('topics'),) hardcoded_username = "johndoe" # i want to find a way not to hardcode this current_user = User.objects.filter(username=hardcoded_username).first() profile = Profile.objects.filter(user=current_user).first() ... profile_values = list(zip(profile, profile)) profile = forms.TypedChoiceField( label="Select a Profile", choices=profile_values, coerce=str, widget=forms.RadioSelect, initial=profile[0], required=True) views.py def foo(request): form = fooForm(request.POST, user=request.user) print(form.request) # i have already tried this but i want to get it in form not views if request.method == "POST": if form.is_valid(): # do something else: form = fooForm(user=request.user) context = {"form": form} I am trying to find a way not to hardcode the username in forms.py and get the current logged in user. -
Appointment Booker. Querying Data
I have created an appointment system with separate date and time models. I am running into some issues trying to query the data as its separate and I would like to query it as day and time together. What's the best way to query this so i can check if there is availability when the user submits the form. models.py class Appointment(models.Model): name = models.CharField(max_length=80) email = models.EmailField(max_length=254) start_date = models.DateField() start_time = models.TimeField() end_date = models.DateField() end_time = models.TimeField() def __str__(self): return f"{self.email} {self.name} has booked {self.start_date} & {self.start_time} until {self.end_date} & {self.end_time}" forms.py class AvailabilityForm(forms.Form): name = forms.CharField(max_length=80, required=True) email = forms.EmailField(max_length=254, required=True) start_date = forms.DateField(required=True, input_formats=['%Y-%m-%d']) start_time = forms.TimeField(required=True, input_formats=["%H:%M"]) end_date = forms.DateField(required=True, input_formats=['%Y-%m-%d']) end_time = forms.TimeField(required=True, input_formats=["%H:%M"]) views.py class BookingView(View): def get(self, request, *args, **kwargs): return render(request, "availability.html") def post(self, request, *args, **kwargs): form = AvailabilityForm(request.POST) if form.is_valid(): data = form. cleaned_data else: return render(request, "unsuccessful.html") **bookingListMax = Appointment.objects.filter(start_date__lt=data['end_date'], end_date__gt=data['start_date'])** if not bookingListMax: booking = Appointment.objects.create( name=data["name"], email=data["email"], start_date=data["start_date"], start_time=data["start_time"], end_date=data["end_date"], end_time=data["end_time"], ) booking.save() *** is my issue code -
net::ERR_ABORTED 403 (Forbidden) Django - Nginx - Uwsgi: Problem to access on my static files
Despite all the different topics open about this problems, i didn't have succeeded to link my django admin to his static files on production with a uwsgi / nginx configuration I have set all the requirements on my settings.py: STATIC_URL = '/api/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') My nginx conf is here, you see i have my static files in a specific folder that own by www-data user: upstream api_portfolio { server unix:/var/run/api_portfolio/uwsgi.sock; } server { location /api { uwsgi_pass api_portfolio; include /etc/nginx/uwsgi_params; # the uwsgi_params file you installed } location /api/static/ { autoindex on; alias /var/www/api_portfolio_static/; } location / { root /var/www/example.com/html; try_files $uri $uri/ /index.html; index index.html index.htm index.nginx-debian.html index.php; } server_name example.com www.example.com; listen [::]:443 ssl ipv6only=on; # managed by Certbot listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/mydomain.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/mydomain.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = www.example.com) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = mydomain.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; listen [::]:80; server_name example.com www.example.com; return 404; # managed by Certbot } When i go … -
making an api to show the books of an auther in django rest framework
I have two models in my project: Author and Book. Each book has a foreignkey that points to the author of the book. I want to write an api which retrieves and instance of an Author and shows the details of that specific person. The problem is that I don't know how to include that said person's books in my API. This is my models.py: class Book(models.Model): title = models.CharField(max_length=150) rating = models.IntegerField(default=0, validators=[MaxValueValidator(10), MinValueValidator(0),]) summary = models.TextField() author = models.ForeignKey(Author, null=True, on_delete=models.SET_NULL) class Author(models.Model): authorID = models.AutoField(primary_key=True) name = models.CharField(max_length=200) dateOfBirth = models.DateField(null=True) nationality = models.CharField(null=True, max_length=255) AND this is the method that didn't work for me: # Serializers.py class AuthorRetrieveSerializer(serializers.ModelSerializer): class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = '__all__' bookDetails = BookSerializer(read_only=True, many=True) class Meta: model = Author fields = ('name', 'dateOfBirth', 'nationality', 'bookDetails') # Views.py class AuthorRetrieveViewSet(RetrieveUpdateDestroyAPIView): permission_classes = (AllowAny,) serializer_class = serializers.AuthorRetrieveSerializer queryset = Author.objects.all() lookup_field = 'authorID' def get_queryset(self): return self.queryset This code retrieves the Author details successfully but doesn't give me their Books. -
Django REST Framework: How can I make the cookies stored by set-cookie be stored in the frontend domain instead of the DRF domain?
We are using Next.js for the front-end, and we need to fetch cookies on the server-side of the front-end. However, the set-cookie that is fetched from the front-end is stored in the DRF domain. For example, let's say the domain of DRF is api.example.com and the frontend is example.com. I want to fetch from example.com and save the cookie in example.com, but for some reason the cookie is saved in api.example.com. We are using dj-rest-auth and djangorestframework-simplejwt, and The jwt cookie needs to be stored in the front-side domain. How can I change the target domain for the DRF set-cookie? -
How to determine which test is printing to console
I am trying to figure out which test is printing a datetime warning to console? I've tried using the '.' notation which I assume is printed after each test, but I am not sure in which order the test seem to be executed. For reference the warning is printed after the first '.' but the second test method in a the first TestCase class is not the culprit. -
How do I create Celery tasks at runtime within Django?
I have an App where the user can enter a time schedual and website URL. I then get all the HTML code from that site and enter it into a DB. Once added Celery will perodically check the website download the code and check for changes every N minutes/hour/days. My celery.py. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'derp.settings') app = Celery('derp') app.config_from_object(settings, namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') I then have my tasks.py. channel_layer = get_channel_layer() app = Celery('derp') def website_links(html_path: str = ""): ##Get website text and A tags return (text, links) @app.task def watch_links_and_text(url): text, links = website_links(url) # TODO Check status code if 404 but in DB mark url_active = False object, created = URLWatcher.objects.get_or_create(url=url) if created: ## True if website not found = object is created & not found for index, line in enumerate(text): line = LineWatcher.website.add_line(line=line, line_number=index, fk_url=object) line.save() return else: website_obj = object.fk_url website_obj.get() for index, line in enumerate(text): obj, cre = LineWatcher.objects.get(line=line, hash=hash, line_number=index) So I am getting this dat object from a request: {"cron":{"name":"task name","url":"https://randomsite.com/news","min":"10","hour":"0","day":"0"}} I then parse the data and try to create the task like so: schedule, _ = CrontabSchedule.objects.get_or_create(minute=minu, hour=hour, day_of_week=day_of_week, day_of_month="*", month_of_year="*") task = PeriodicTask.objects.create(crontab=schedule, name=name, task="watcher.tasks.watch_links_and_text", args=json.dumps([url])) task.save() I can see … -
A couple of url paths not working anymore after creating class ProfileDetailView.. Please help, I've been stuck at this for days
Working on a social website and after creating a class to render the user's profile in detail. The path that render all posts and all profiles aren't working anymore and I get the same error and when I uncomment the code from line 21 to 24 (def get_object) function it says "Does Not Exist at /posts/" " Profile matching query does not exist. Page not found (404) No profile found matching the query Request Method: GET Request URL: http://127.0.0.1:8000/posts/ Raised by: network.views.<class 'network.views.ProfileDetailView'> Using the URLconf defined in project4.urls, Django tried these URL patterns, in this order: admin/ [name='index'] login [name='login'] logout [name='logout'] register [name='register'] <slug>/ [name='profile-view'] The current path, posts/, matched the last one. " Urls: urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("<slug>/", ProfileDetailView.as_view(), name="profile-view"), path("posts/", post_comment_create_view, name="posts"), path("liked/", like_unlike_post, name="like-post-view"), path("<pk>/delete", PostDeleteView.as_view(), name="post-delete"), path("<pk>/update", PostUpdateView.as_view(), name="post-update"), path("invites/", invites_received_view, name="invites-view"), path("allprofiles/", ProfileListView.as_view(), name="all-profiles-view"), path("send-invite/", send_invitation, name="send-invite"), path("remove-friend/", remove_friends, name="remove-friend"), path("invites/accept/", accept_invitation, name="accept-invite"), path("invites/reject/", reject_invitation, name="reject-invite"), ] Views: from .models import Relationship, Post, Profile, Like from django.views.generic import TemplateView, View, UpdateView, DeleteView, ListView, DetailView from .forms import ProfileModelForm, PostModelForm, CommentModelForm class ProfileDetailView(DetailView): model = Profile template_name = 'network/profile.html' def get_object(self, slug=None): … -
Django query data with from child to parent model
I am creating an app where I want to show all the list of members of a certain committee in my template, but also I want to show the status of whether they have paid that month or not. Now I am quite confused as there is no linkage of my Member table to Payment detail. I can get the list of people who paid from the payment detail table but I want is to show all the list from members and then show status next to them. class Members(models.Model ): user = models.ForeignKey(Users,verbose_name='User Id', on_delete=models.CASCADE) com = models.ForeignKey(Committees, on_delete=models.CASCADE,verbose_name='Committee Name') mem_status = models.CharField( max_length=20,choices=MEMBER_STATUS, verbose_name='Member Status') mem_note = models.TextField(null=True, blank=True) class PaymentDetails(models.Model): mem = models.ForeignKey(Members,on_delete=models.CASCADE,verbose_name='Memeber Phone no') com = models.ForeignKey(Committees, on_delete=models.CASCADE,verbose_name='Committee Name') payment_month = models.DateField(default=datetime.now()) payment_amount_debit = models.IntegerField(null=True,blank=True) payment_amount_credit = models.IntegerField(null=True,blank=True) payment_status = models.CharField(max_length=16, choices=PAYMENT_DETAILS_CHOICES) -
Django form got submitted with the get method although post method was specified
In my rendered html page I have this form. Upon clicking on the Next button, the forms should be submit as a post method, being directed to the summary in url <form action="/summary" method="post"> <input type="hidden" name="csrfmiddlewaretoken" value="iC3L3QCDundSemg1jfZH96w8X83jrsaE3gQmtbb3rFCyNEN9jXdubao0TJ18EKnb"> <label for='customerName' class="subTitle">Name</label> <br> <input type="text" name="customerName" maxlength="100" required id="id_customerName"> <br> <br> <label for="email" class="subTitle">Email</label> <br> <input type="email" name="email" required id="id_email"> <br> <br> <label for="phone" class="subTitle">Mobile Phone</label> <br> <input type="tel" name="phone" required id="id_phone"> <br> <br> <label for="comment" class="subTitle">Comment</label> <br> <textarea name="comment" cols="20" rows="10" maxlength="500" required id="id_comment"> </textarea> <br> <button onclick="location.href='/deliveryFormCheckout'" type="button" class="btn btn-danger btn-lg">Back</button> <button onclick="location.href='/summary'" type="submit" class="btn btn-success btn-lg" id="deliveryNextBtn">Next</button> </form> In the urls.py, the summary is then directed to the Summary view class urlpatterns = [ path('admin/', admin.site.urls), path('', indexPage.as_view()), path('dimsumshop', MainShop.as_view(), name = 'mainShop'), path('box/<slug:productSlug>', ProductView.as_view(), name = 'viewProduct'), path('product/<slug:boxSlug>', BoxView.as_view(), name = 'BoxView'), path('changeItemQuantityInBasket', ChangeItemQuantity.as_view()), path('isOrderPriceAboveMinimum', MinimumOrderPriceFulfilled.as_view()), path('checkout', Checkout.as_view(), name = 'checkout'), path('deliveryFormCheckout', DeliveryFormView.as_view(), name = 'deliveryFormView'), path('checkSteamer', CheckoutCheckSteamer.as_view()), path('verifyAddress', VerifyAddress.as_view(), name = 'verifyAddress'), path('checkoutCustomer', CustomerInfo.as_view(), name = 'customerInfo'), path('summary', Summary.as_view(), name = 'summary'), re_path(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}) ] In the Summary view class I have the below code class Summary(View): def post(self, request, *args, **kwargs): print('post called') form = CustomerCheckoutInfoForm(request.POST) context = dict() return render(request=request, template_name='summary.html', context = … -
Combine 2 inputs into 1 form model
I am looking to see if there is way a combine 2 inputs from html form into 1 django form model. This is so i can combine a date and time together so it can be queried much easier when saved to a database. forms.py start = forms.DateTimeField(required=True, input_formats=['%Y-%m-%d%H:%M']) html <input type="text" name="start_date" required> <input type="text" name="start_time" required> I am creating an appointment system and having great difficulty querying dates and times separately when they are in different models so think the best way is to have the data and time together. SOS Thanks -
Django Custom User update with one to one to Customer model
I'm trying to create Update view for Customer model which have Onetoone relation with User(django model. After five hours and trying function base and class views I'm unable to get this working. Where am I making a mistake? my models.py class Customer(Model): user = OneToOneField(User, on_delete=CASCADE) mobile = CharField(max_length=12,null=True) dob = DateField(null=True) def __str__(self): return self.user.username my views.py class ProfileUpdateView(UpdateView): template_name = 'forms.html' form_class = AdminUserUpdateForm model = User success_url = reverse_lazy('controls') def get_object(self, queryset=None): return Customer.objects.get(pk=self.kwargs['pk']).user # Not working def customer_list_view(request): customer = Customer.objects.filter(user__groups__name='customer') premium = Customer.objects.filter(user__groups__name='premium') context = {'customer': customer, 'premium': premium} return render(request, 'customercontrol.html', context) my forms.py class AdminUserUpdateForm(UserChangeForm): class Meta: model = User fields = ['username', 'email', 'groups'] mobile = CharField(max_length=30) dob = DateField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for visible in self.visible_fields(): visible.field.widget.attrs['class'] = 'form-control' @atomic def save(self, commit=True): user = super().save(commit) mobile = self.cleaned_data['mobile'] dob = self.cleaned_data['dob'] customer = Customer.objects.get(user__pk=user.pk) customer.mobile = mobile customer.dob = dob if commit: customer.save() return user my templates, where I get PK for the queries. {% extends "base.html" %} {% block content %} <h1 class="font1">Our premium customers:</h1> <table class="table table-dark"> <thead> <tr> <th scope="col">User ID</th> <th scope="col"><a class="btn btn-secondary" href="">Username</a></th> <th scope="col"><a class="btn btn-secondary" href="">Name</a></th> <th scope="col"><a class="btn … -
Django-Q schedule nonetype error with custom function
I'm trying to create some scheduled tasks in my Django project using Django-Q. The problem is that every schedule task fails raising next exception: 'NoneType' object is not callable : Traceback (most recent call last): File "/home/ubuntu/.virtualenvs/gamesquare-pre/lib/python3.6/site-packages/django_q/cluster.py", line 432, in worker res = f(*task["args"], **task["kwargs"]) TypeError: 'NoneType' object is not callable The schedule is called like: from django_q.tasks import schedule schedule('orders.mails.product', 2, 2, schedule_type='O') Then, in mails.py (same folder) I have the method product defined: def product(x, y) return x * y My Django-Q's configuration in settings.py: Q_CLUSTER = { 'name': 'qclust', 'workers': config('Q_CLUSTER_WORKERS', cast=int), 'timeout': 20, 'cpu_affinity': 1, 'save_limit': 50, 'queue_limit': 100, 'redis': { 'host': 'localhost', 'port': 6379, 'db': 0 } } Can anyone help with this issue? -
how to retrieve request.user from form in django
I have the following codes: models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ... ... class Category(models.Model): name = models.CharField(max_length=30) ... forms.py class FooForm(forms.Form): # how to call 'request.user' here so i can achieve something like the two lines below ??? # user = User.objects.filter(username=request.user).first() <=== GOAL # profile = Profile.objects.filter(user=user).first() <=== GOAL categories = list(Category.objects.values_list("name", flat=True)) categories_values = list(zip(topics, topics)) categories = forms.TypedChoiceField( label="Select a category", choices=categories_values, coerce=str, widget=forms.RadioSelect, initial=topics[0], required=True) def __init__(self, *args, **kwargs): super(ExperienceStart, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'post' self.helper.layout = Layout(InlineRadios('categories'),) views.py def experience_start(request): form = FooForm(request.POST) if request.method == "POST": if form.is_valid(): # do something ... else: form = FooForm() context = {"form": form} This work as far as displaying the different categories available in a form so the user can select one of them to compute some result. Now my issue is that i want to include the possibility to retrieve the current user logged in user, which is usually done in the view using request.user but because i am using crispy forms the logic has to be implemented in the forms.py above and i cant seem to find a solution. I am running out of ideas, any help would be helpful … -
Django rest framework user model referring to several other model
I have a couple of models like: class Organization(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) .... class Customer(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) .... class Supplier(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) .... Each model have their own one or more users, I created a user model like this: class User(AbstractBaseUser, PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email_address = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) My question is how can I create a relationship between User and Organization, Customer, Supplier...? I found one solution like: class User(AbstractBaseUser, PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email_address = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) organization = models.ForeignKey(Organization) customer = models.ForeignKey(Organization) supplier = models.ForeignKey(Supplier) Which I did not like to do because I have several models that have their users. Another way I found is GenericForeignKey Relationship but also not a very good solution. One of the reasons for this is I have more models to implement similar relationships which becomes very complicated. Can anyone suggest an elegant solution for this? Thanks in advance! -
REST API Django does not show all tables in different endpoints
I am learning REST API Django and would appreciate your patience and help in understaing the below case. in myproject/abcapp/forms.py from django import forms from .models import * class ProfileForm(forms.ModelForm): class Meta: model=Profile fields = "__all__" class Zoo_data_2020Form(forms.ModelForm): class Meta: model=Zoo_data_2020 fields = "__all__" in myproject/abcapp/models.py from django.conf import settings from django.db import models class ProfileQuerySet(models.QuerySet): pass class ProfileManager(models.Manager): def get_queryset(self): return ProfileQuerySet(self.model,using=self._db) class Profile(models.Model): name=models.CharField(settings.AUTH_USER_MODEL,max_length=200) subtype=models.CharField(max_length=500) type=models.CharField(max_length=500) gender=models.CharField(max_length=500) objects = ProfileManager() class Meta: verbose_name = 'Profile' verbose_name_plural = 'Profiles' managed = False db_table ='profiles' def __str__(self): return '{}'.format(self.name) class Zoo_data_2020QuerySet(models.QuerySet): pass class Zoo_data_2020Manager(models.Manager): def get_queryset(self): return Zoo_data_2020QuerySet(self.model,using=self._db) class Zoo_data_2020(models.Model): name=models.CharField(max_length=200) size=models.DecimalField(decimal_places=3,max_digits=100000000) weight=models.DecimalField(decimal_places=3,max_digits=100000000) age=models.DecimalField(decimal_places=3,max_digits=100000000) objects = Zoo_data_2020Manager() class Meta: verbose_name = 'zoo_data_2020' verbose_name_plural = 'zoo_data_2020s' managed = False db_table ='zoo_data_2020' def __str__(self): return '{}'.format(self.name) in myproject/abcapp/api/views.py: from rest_framework import generics, mixins, permissions from rest_framework.views import APIView from rest_framework.response import Response import json from django.shortcuts import get_object_or_404 from abcapp.models import * from .serializers import * def is_json(json_data): try: real_json = json.loads(json_data) is_valid = True except ValueError: is_valid = False return is_valid class ProfileDetailAPIView(generics.RetrieveAPIView): permission_classes = [] authentication_classes = [] queryset= Profile.objects.all() serializer_class = ProfileSerializer lookup_field = 'id' class ProfileAPIView(generics.ListAPIView): permission_classes = [] authentication_classes= [] serializer_class = ProfileSerializer passed_id = None search_fields … -
Trying to save to database via ModelForm Django
My form is not saving to the database or at least i know the form is not valid i just dont know why? because it will always skip to the else in the if form.is_valid() (print("didnt work!")) the view.py: def index(request): component = Component.objects.all() form = ComponentModelForm() if request.method == 'POST': form = ComponentModelForm(request.POST) if form.is_valid(): form.save() return redirect('/maintenance') else: form = ComponentModelForm() print("didnt work!") context = { 'components': component, 'form': form, } return render(request, 'maintenance/index.html', context) forms.py: class ComponentModelForm(forms.ModelForm): note = forms.CharField(widget=forms.Textarea) image = forms.ImageField(error_messages = {'invalid':("Image files only")}, widget=forms.FileInput) class Meta: model = Component fields = ("name", "manufacturer", "model", "serial_number", "price", "note", "image", "parent",) the template form: {% load widget_tweaks %} <form class="component-update-grid" enctype="multipart/form-data" method='POST' action=''> {% csrf_token %} <div class="component-form-data"> <span class="component-label-text">Name</span> {% render_field form.name class="component-form-data-inputs" %} <span class="component-label-text">Manufacturer</span> {% render_field form.manufacturer class="component-form-data-inputs" %} <span class="component-label-text">Model</span> {% render_field form.model class="component-form-data-inputs" %} <span class="component-label-text">Serial Number</span> {% render_field form.serial_number class="component-form-data-inputs" %} <span class="component-label-text">Price</span> {% render_field form.price class="component-form-data-inputs" %} <span class="component-label-text">Note</span> {% render_field form.note class="component-form-data-inputs" %} {% render_field form.parent class="component-form-data-inputs " %} <input type="submit" class="button1" value='Create Component' /> </div> <div class="component-form-img"> <img class="maintenance-component-img" src='{%static 'imgs/sidebar/logo.png'%} ' /> {% render_field form.image %} </div> </form> -
How to run scheduler in different apps of same django project
I have two apps viz: app1 and app2 in my-project. I am running a scheduled task in views.py of app1 and app2 on every month basis on different timing. But app1 is functioning properly but app2 scheduler is not calling at all. here is my code. app1 views.py code ''' from apscheduler.schedulers.background import BackgroundScheduler scheduler = BackgroundScheduler() def start_job(): global job scheduler.add_job(ampplan, 'cron', day=15, hour=18, minute=46) scheduler.add_job(calib, 'cron', day=27, hour=5, minute=15) scheduler.add_job(oildue, 'cron', day=27, hour=5, minute=30) scheduler.add_job(sdrmplan, 'cron', day=27, hour=5, minute=45) try: scheduler.start() except: pass start_job() ''' app2 views.py code ''' scheduler = BackgroundScheduler() def nlr_start_job(): global job scheduler.add_job(ampplan, 'cron', day=15, hour=20, minute=0) scheduler.add_job(calib, 'cron', day=27, hour=6, minute=1) scheduler.add_job(oildue, 'cron', day=27, hour=6, minute=10) scheduler.add_job(sdrmplan, 'cron', day=27, hour=6, minute=20) try: scheduler.start() except: pass nlr_start_job() ''' -
GitHub user authentication in GitHub application through Django framework
I want to authenticate GitHub user to my GitHub application and serve to my local server 127.0.0.1:8000, but I am not able to take tokens. This is how GitHub is showing authentication. From GitHub documentation, I am not able to understand the process of authentication after generating private key, then how to create JWT and installation tokens ? Could someone show me what to do next ? -
Django Testing the model file midels.py
I am trying to test the models.py file using Django TestCases but after sovling few portion rest I could not figure out how to solve it Here the models.py file looks like import sys from datetime import datetime from dateutil.relativedelta import relativedelta from django.apps import apps from django.conf import settings from django.core.exceptions import ValidationError from django.core.validators import MaxValueValidator, MinValueValidator from django.db import models from django.db.models.signals import post_save, post_delete from django.dispatch import receiver from django_google_maps import fields as map_fields from django_mysql.models import ListTextField from simple_history.models import HistoricalRecords from farm_management import config from igrow.utils import get_commodity_name, get_region_name, get_farmer_name, get_variety_name db_config = settings.USERS_DB_CONNECTION_CONFIG class Device(models.Model): id = models.CharField(max_length=100, primary_key=True) fetch_status = models.BooleanField(default=True) last_fetched_on = models.DateTimeField(auto_now=True) geolocation = map_fields.GeoLocationField(max_length=100) device_status = models.CharField(max_length=100, choices=config.DEVICE_STATUS, default='new') is_active = models.BooleanField(default=True) history = HistoricalRecords() class Farm(models.Model): farmer_id = models.PositiveIntegerField() # User for which farm is created irrigation_type = models.CharField(max_length=50, choices=config.IRRIGATION_TYPE_CHOICE) soil_test_report = models.CharField(max_length=512, null=True, blank=True) water_test_report = models.CharField(max_length=512, null=True, blank=True) farm_type = models.CharField(max_length=50, choices=config.FARM_TYPE_CHOICE) franchise_type = models.CharField(max_length=50, choices=config.FRANCHISE_TYPE_CHOICE) total_acerage = models.FloatField(help_text="In Acres", null=True, blank=True, validators=[MaxValueValidator(1000000), MinValueValidator(0)]) farm_status = models.CharField(max_length=50, default="pipeline", choices=config.FARM_STATUS_CHOICE) assignee_id = models.PositiveIntegerField(null=True, blank=True) # Af team user to whom farm is assigned. previous_crop_ids = ListTextField(base_field=models.IntegerField(), null=True, blank=True, size=None) sr_assignee_id = models.PositiveIntegerField(null=True, blank=True) lgd_state_id = models.PositiveIntegerField(null=True, blank=True) … -
Missing Imports [Django] [Pip External Packages]
I started using django for the first time today and I have been encountering one issue I want to use the PDFNetPython3 library for my project in Django framework. I ran the command pip install PDFNetPython3 and it is says its already installed, however Django isn't able to resolve the import Error/Warning Import "PDFNetPython3" could not be resolvedPylancereportMissingImports This is the line below being shown as unresolved import. from PDFNetPython3 import PDFDoc, Optimizer, SDFDoc, PDFNet views.py from http.client import HTTPResponse from django.shortcuts import render, HttpResponse # Create your views here. def index(request): return render(request, 'index.html') def compress(request): return render(request, 'compress.html') def showName(request): if request.method == 'POST': user_initial_pdf = request.POST['user_initial_pdf'] from PDFNetPython3 import PDFDoc, Optimizer, SDFDoc, PDFNet return HttpResponse("ok") Python Version - 3.9.7 Django Version - 4.0.1 Please note : I havent created any virtual environment as of now cause I just started django and found out its a good practice to do so, can it be the cause django not able to resolve the library through pip ? Help would be appreciated :) -
how to set simplejwt token as authentication_classes in django rest
so I'm using django rest framework and I'm using simpleJWT for authentication. now i have some APIs that require the user to be logged in which means they require the token that was given to them beforehand. My problem is that I don't know what to do to make this happen. Is there anything that I could write any value for the following variable to make this automatic? authentication_classes = () and if that's not possible, how would I be able to do this? -
Django HTML issue with HTML text formatting
I am developing django site locally, I have some issues with Formatting of text (highlighted yellow). On a main blog yellow is incorrectly showing that HTMl tags, although when I enter detailed view of post I see all is ok. Do you know what can be issue? incorrect: correct: base.html: <!DOCTYPE html> <html> <head> <title>Django Central</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Tangerine"> <meta name="google" content="notranslate" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous" /> </head> <body> <style> body { font-family: "Tangerine", serif; font-size: 37; background-color: #fdfdfd; } .shadow { box-shadow: 0 4px 2px -2px rgba(0, 0, 0, 0.1); } .btn-danger { color: #fff; background-color: #f00000; border-color: #dc281e; } .masthead { background: #3398E1; height: auto; padding-bottom: 15px; box-shadow: 0 16px 48px #E3E7EB; padding-top: 10px; } img { width: 00%; height: auto; object-fit: contain; </style> {% load static %} <center> <img src="{% static 'blog/moj.png' %}" alt="My image"> </center> <!-- Navigation --> <nav class="navbar navbar-expand-sm navbar-light bg-light shadow" id="mainNav"> <div class="container-fluid"> <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item text-black"> <a class="nav-link text-black font-weight-bold" href="/">Blog</a> </li> <li class="nav-item text-black"> <a class="nav-link text-black font-weight-bold" href="portfolio/">Moje projekty/ Portfolio</a> </li> <li class="nav-item … -
Django sorting objects with Dropdown-List / url parameter
I have problems with sorting objects from database in main template which are based on url parameters. I want to sort objects on different ways. Mainly by date, price etc. I have my form in template, my views.py function where I'm trying to get the parameter "sort=new". If I'm using checkboxes or radio then everything works. But I need to sort objects with select and option. My template: <h2>Number of adverts: {{num}}</h2> <form action="{% url 'adverts' %}"> <span>Sort by:</span> <select name="sort"> <option value="new">newest</option> <option value="old">older</option> <option value="price_low">price low</option> <option value="price_high">price high</option> <option value="mileage_low">mileage lowest</option> <option value="mileage_high">mileage higher</option> <input type="submit" value="Sort"> </select> </form> My views.py function: def adverts(request): page = 'adverts' if request.GET.get('sort', 'new'): adverts = Advert.objects.all().order_by('-created') elif request.GET.get('sort','old'): adverts = Advert.objects.all().order_by('created') else: adverts = Advert.objects.all().order_by('-mileage') a = 0 for num in adverts: a += 1 context = {'adverts': adverts, 'num': a, 'page': page} return render(request, 'adverts/adverts.html', context) As I mention above. I want to sort objects which I’m printing in my template. I want it to be a Dropdown list not a checkbox or radio. Maybe I need to create a form in forms.py file and then get access to form fields in my template? I’m confused. -
Trying to change new_manager.user.is_employee = False and set it as new_manager.user.is_manager = True , but not working
Upon converting a user into a manager, I need to set 'is_employee = False' and 'is_manager = True'. The process appears to be quite straightforward, but I can't get it to work. models.py class User(AbstractUser): is_admin = models.BooleanField(default=False) is_employee = models.BooleanField(default=True) is_manager = models.BooleanField(default=False) def __str__(self): return f'{self.first_name} {self.last_name} as {self.username}' class Manager(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user_profile = models.OneToOneField(Profile, on_delete=models.CASCADE) business_unit = models.OneToOneField(BusinessUnit, on_delete=models.SET_NULL, null=True) previous_business_units = models.CharField(max_length=100, default=None, blank=True, null=True) manager_description = models.TextField(blank=True, null=True) manager_created_date = models.DateTimeField(auto_now_add=True, blank=True, null=True) def __str__(self): return f'{self.user.first_name} {self.user.last_name}' views.py @login_required @admin_required def manager_create_view(request): form = ManagerCreationForm() if request.method == 'POST': form = ManagerCreationForm(request.POST) if form.is_valid(): new_manager = form.save(commit=False) group = Group.objects.get(name='Manager') new_manager.user.groups.add(group) new_manager.user.is_employee = False new_manager.user.is_manager = True new_manager = form.save() new_manager = form.cleaned_data.get('user') messages.success(request, f'{new_manager} is now a Manager!') return redirect ('list-managers') messages.error(request, 'Something went wrong, please check the hilighted field(s)') context = { 'title': 'Create Manager', 'form': form } return render(request, 'managers/manager-form.html', context) I tried using signals as well but, no luck. signals.py from django.db.models.signals import post_save from accounts.models import User, Manager from django.dispatch import receiver @receiver(post_save, sender=Manager) def change_user_type(sender, instance, created, **kwargs): if created: instance.user.is_manager = True instance.user.is_employee = False Trying to learn on my own, so any help …