Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django change password using custom inputs with PasswordChangeView
Currently working on a change password method, not sure how to do the html inputs for it. I am using PasswordChangeView in my urls.py from django.urls import path from .views import update_profile from django.contrib.auth.views import PasswordChangeView urlpatterns = [ path('profiles/settings/', update_profile, name='update_profile'), path('profiles/change_password/', PasswordChangeView.as_view( template_name='profiles/settings.html'), name='password_change'), ] The template it is pointing too is the user update profile. I want to use own inputs on the template, but not sure how to hook it up with PasswordChangeView html <!-- Password Change --> <div class="tab-pane fade" role="tabpanel" id="password"> <form action="{% url 'password_change' %}" method="post"> {% csrf_token %} <div class="form-group row align-items-center"> <label class="col-3">Current Password</label> <div class="col"> <input type="password" placeholder="Enter your current password" name="password-current" class="form-control" /> </div> </div> <div class="form-group row align-items-center"> <label class="col-3">New Password</label> <div class="col"> <input type="password" placeholder="Enter a new password" name="password-new" class="form-control" /> <small>Password must be at least 8 characters long</small> </div> </div> <div class="form-group row align-items-center"> <label class="col-3">Confirm Password</label> <div class="col"> <input type="password" placeholder="Confirm your new password" name="password-new-confirm" class="form-control" /> </div> </div> <div class="d-flex justify-content-end"> <button type="submit" class="btn btn-primary">Change Password</button> </div> </form> </div> Question I want each of those 3 inputs used to change password, but i dont know what label id and name label to use to … -
geodjango filter polygon intersections for every point
I was trying to get locations(polygon) with shops(point). I don't want to add foreign key reference for location into shop model, rather want to get them by checking their intersections. class Shop(models.Model): name = models.CharField(max_length=40) location = PointField() @property def point(self): return self.location.wkt class Location(models.Model): name = models.CharField(max_length=200) area = PolygonField() I get my desired querysets using for loop however I was looking for a database related approach. for i in Location.objects.all(): print(Shop.objects.filter(location__intersects = i.area)) ## output: <QuerySet [<Shop: Shop object (1)>, <Shop: Shop object (2)>, <Shop: Shop object (4)>]> <QuerySet [<Shop: Shop object (3)>]> so I tried using subquery but iterating over full Location queryset returns error more than one row returned. so I set the limit to 1. loc=Location.objects.all() shp=Shop.objects.filter(location__intersects=Subquery(loc.values('area')[:1])) However, I need to filter Shop for all the Location. What might be the best way of doing that? -
expected string or bytes-like object while sending a Post request to a view
i have this view Where im making a post request from my frontend, iam sending a list of objects as a body to this endpoint. I have recieved the list in the files variable. now im trying to create an objects with the data i get from my files list, but im getting this error @api_view(("POST",)) @renderer_classes((TemplateHTMLRenderer, JSONRenderer)) def get_import(request): files = json.loads(request.body) print(files) # im able to see the list in the console. user = UserAccount.objects.filter(email=request.user).first() for i in range(len(files)): trans, created = Transaction.objects.update_or_create( chp_reference=files[i]["transaction_chp_reference"], defaults={ "user": user, "income_period": files[i]["transaction_income_period"], "property_market_rent": files[i]["transaction_property_market_rent"], }, ) trans.save() return Response(status=status.HTTP_201_CREATED) I tried to delete all migrations and db, and re created . but still same problem. Traceback (most recent call last): File "G:\cra-react\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "G:\cra-react\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "G:\cra-react\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "G:\cra-react\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "G:\cra-react\venv\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "G:\cra-react\venv\lib\site-packages\rest_framework\views.py", line 505, in dispatch response = self.handle_exception(exc) File "G:\cra-react\venv\lib\site-packages\rest_framework\views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "G:\cra-react\venv\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception raise exc File "G:\cra-react\venv\lib\site-packages\rest_framework\views.py", line 502, in dispatch response = … -
Deploying Django Apps on Heroku
I'm at my wit's end. I have followed two tutorials about deploying a Django app onto Heroku. I created two apps with the first tutorial (MDN), and one app with the second tutorial (Corey Schafer's YouTube video). All three times I've created these Django apps and they work. But when it comes time to try to deploy these apps to Heroku, something I download through pip into these apps doesn't work. This time around, with Corey Schafer's tutorial, when I download "django-heroku" through pip, the download works but when I add import django_heroku django_heroku.settings(locals()) into my "settings.py" file, I get an error message saying Import "django_heroku" could not be resolved Pylance(reportMissingImports) I've searched high and low across the Internet for the answer for this and found nothing. And I'm taking a real chance putting up this question here and hoping for an answer. Is Django incompatible with Heroku? I'd like to be able to deploy my Django apps to Heroku since Heroku is free, but perhaps Heroku no longer allows Django apps to be deployed? Please help! I'm tearing my hair out. -
Getting an attribute error in django.how do i resolve this?
Getting an attribute error at a model in django. When I tried to call the model.get_absolute_url at my model_list templates.it says model has no attributen "id" while in the model,i ve also written both the url mapper and the view function correctly,including the detals templates the exception was pointing the this reverse line This is the function under the model in models.py file ''' def get_absolute_url(self): return reverse('my_midel_detail_template_name',args=[str(self.id)]) ''' -
Django dynamic url routing not working properly
I'm trying some dynamic url routing for my website. I got to the point but is not working properly when I want to redirect to other pages. Let me explain: I have the same navbar for each page. I have a "news" page with url /news from which I can dynamically route to each article with url /article/pk, where pk is the index of the article in postgresql database. The article page has the same navbar of each other page but when I click to redirect to another page (for example /news) it doesn't work since it looks for /article/news which obviously does not exists instead of /news. I don't know how to solve this and I would be glad if you could help me. Please don't roast me, it's my first project. Feel free to ask for code if needed. -
Django_tables2 : using bootstrap in django-tables2
If I want to use Bootstrap in django-tables2 what should I do? Where I should write DJANGO_TABLES2_TEMPLATE = 'django_tables2/bootstrap4.html' If I want to use bootstrap5 what should I do? -
The `.update()` method does not support writable dotted-source fields by default
i'm trying to update some data and got this error what is wrong here? Exception Value: The `.update()` method does not support writable dotted-source fields by default. Write an explicit `.update()` method for serializer `users.serializers.TransporteurSerializer`, or set `read_only=True` on dotted-source serializer fields. i'm trying to build a multi types user so the user (CustomUser) is the parent class class TransporteurSerializer(serializers.ModelSerializer): # user = CustomUserSerializer() first_name = serializers.CharField(source = 'user.first_name') last_name = serializers.CharField(source = 'user.last_name') email = serializers.CharField(source = 'user.email') phone_number = serializers.CharField(source = 'user.phone_number') address = serializers.CharField(source = 'user.address') class Meta: model = Trasporteur fields = [ 'id', 'first_name', 'last_name', 'email', 'phone_number', 'address', 'matricule','car_type','current_location','is_on_travail','bio', ] def update(self, instance, validated_data): user_data = validated_data.pop('user') user = instance.user instance.matricule = validated_data.get('matricule', instance.matricule) instance.car_type = validated_data.get('email', instance.car_type) instance.current_location = validated_data.get('email', instance.current_location) instance.is_on_travail = validated_data.get('email', instance.is_on_travail) instance.bio = validated_data.get('email', instance.bio) user.first_name = user_data.get('first_name',user.first_name) user.last_name = user_data.get('first_name',user.last_name) user.email = user_data.get('email',user.email) user.phone_number = user_data.get('first_name',user.phone_number) user.address = user_data.get('address',user.address) user.save() instance.save() return instance -
How to call posts comments from an api
Currently I have the following Models: class Post(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=200, blank=False, null=False) class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, null=False, blank=False) text = models.TextField(max_length=1000) and these ModelViewSets: class PostViewSet(ModelViewSet): queryset = Post.objects.all() serializer_class = PostSerializer class CommentViewSet(ModelViewSet): queryset = Comment.objects.all() serializer_class = CommentSerializer my question is how can I call comments from a post like this: GET /posts/{id}/comments currently I get the comments this way: GET /comments/{id} #comment Id, not post id. -
apply css class to ckeditor uploaded images
I have a feature that allows users to write blog posts using with ckeditor. The issue is if a image is uploaded it is way to large. I need to be able to apply a css class so I can properly size these images. I found this stack post saying to put this code in my config.js file and run collectstatic it should apply a class. However it does not do anything. Any suggestions? this is my config.js file /** * @license Copyright (c) 2003-2021, CKSource - Frederico Knabben. All rights reserved. * For licensing, see https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.editorConfig = function( config ) { // Define changes to default configuration here. For example: // config.language = 'fr'; // config.uiColor = '#AADC6E'; }; CKEDITOR.on('instanceReady', function (ev) { ev.editor.dataProcessor.htmlFilter.addRules( { elements: { $: function (element) { // check for the tag name if (element.name == 'img') { element.attributes.class = "img-fluid" // Put your class name here } // return element with class attribute return element; } } }); }); -
OSError: /opt/homebrew/opt/gdal/lib/libgdal.dylib: cannot open shared object file: No such file or directory
I am trying to deploy a webapp that utilises GDAL libraries. I have followed the heroku documentation pertaining to GDAL and Heroku here and here. My buildpacks are: === vygrapp Buildpack URLs 1. https://github.com/heroku/heroku-geo-buildpack.git 2. heroku-community/apt 3. heroku/python When I deploy my app through heroku I get this traceback: remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "/tmp/build_4575d756/manage.py", line 22, in <module> remote: main() remote: File "/tmp/build_4575d756/manage.py", line 18, in main remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute remote: django.setup() remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/__init__.py", line 24, in setup remote: apps.populate(settings.INSTALLED_APPS) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/apps/registry.py", line 114, in populate remote: app_config.import_models() remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/apps/config.py", line 300, in import_models remote: self.models_module = import_module(models_module_name) remote: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module remote: return _bootstrap._gcd_import(name[level:], package, level) remote: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import remote: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load remote: File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked remote: File "<frozen importlib._bootstrap>", line 680, in _load_unlocked remote: File "<frozen importlib._bootstrap_external>", line 850, in exec_module remote: File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/auth/models.py", line 3, in <module> remote: from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager … -
Django form not able to upload image
Trying to upload user avatar on profile page, but it wont do anything when pressing the button, I have set that there is not required to upload profile pic, so rest of form works. forms.py class UpdateProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['first_name', 'last_name', 'location', 'bio', 'avatar'] def __init__(self, *args, **kwargs): super(UpdateProfileForm, self).__init__(*args, **kwargs) self.fields['avatar'].required = False views.py @login_required def update_profile(request): context = {} user = request.user instance = Profile.objects.filter(user=user).first() if request.method == 'POST': form = UpdateProfileForm(request.POST, request.FILES, instance=instance) if form.is_valid(): print('\n\n form is valid') form.instance.user = user form.save() return redirect('/') else: form = UpdateProfileForm(instance=user) print(errors) context.update({ 'form': form, 'title': 'update_profile' }) return render(request, 'profiles/settings.html', context) From html <form method="POST" action="." enctype="multipart/form-data"> {% csrf_token %} <div class="media mb-4"> <img alt="Image" src="{{ user.profile.avatar.url }}" class="avatar avatar-lg" /> <div class="media-body ml-3"> <div class="custom-file custom-file-naked d-block mb-1"> <input type="file" class="custom-file-input d-none" id="{{ form.avatar.id_for_label }}"> <-- This is my label for the button <label class="custom-file-label position-relative" for="{{ form.avatar.id_for_label }}"> <-- Input field.. nothing happens when press <span class="btn btn-primary"> Upload avatar </span> </label> </div> <small>Use an image at least 256px by 256px in either .jpg or .png format</small> </div> </div> <!--end of avatar--> <div class="form-group row align-items-center"> <label class="col-3">First Name</label> <div class="col"> … -
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?