Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Heroku Is giving me 'error h14 for my django project
When I go to my heroku project it says to run heroku logs --tail, and when I do that I get: 2022-01-16T04:52:26.342707+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=riseupontario.herokuapp.com request_id=584f14b8-99da-4cfc-bfad-1811755db6fb fwd="49.149.136.159" dyno= connect= service= status=503 bytes= protocol=https 2022-01-16T04:52:27.375325+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=riseupontario.herokuapp.com request_id=63993a67-e160-4762-a520-9164646b74f7 fwd="49.149.136.159" dyno= connect= service= status=503 bytes= protocol=https I've tried heroku ps:scale web=1 but I get: Scaling web processes... failed ! No such type as web This is my procfile: web: gunicorn riseupontario.wsgi --log-file - How do I get my site working? -
How to prepopulate the django ckeditor page in html
I am creating a blogging site with django, and want to create an editing post page using the same form as the one I used for post creation. This is the forms.py class PostForm(forms.Form): title = forms.CharField(max_length=100, label='Post Title') short_description = forms.CharField(widget=forms.Textarea(attrs={"rows":3, "cols":100})) content = forms.CharField(widget=CKEditorWidget()) And this is the html so far: <div class="form-group"> <label class="col-form-label mt-4" for="inputDefault">Title</label> {% render_field form.title class="form-control" value=post.title %} </div> <div class="form-group"> <label class="form-label mt-4" for="exampleTextarea" >Short Description</label > <!-- {% render_field form.short_description class="form-control" initial=post.short_description %} --> <textarea class="form-control" cols="100" name="description" rows="3">{{ post.short_description }}</textarea> </div> <div class="form-group"> <label class="col-form-label mt-4" for="inputDefault">Content</label> {{ form.content }} </div> I want to be able to prepopulate the ckeditor widget with prexisting data from the model: class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name= 'blog_posts') short_description = models.TextField() Any advice on how to do so? updated_on = models.DateTimeField(auto_now=True) content = RichTextField() -
Compare data from two different models in Django
I created two models from statistics import mode from django.db import models # Create your models here. class Image(models.Model): photo = models.ImageField(upload_to="myimage") date = models.DateTimeField(auto_now_add=True) shape = models.CharField(max_length=20, default='') color = models.CharField(max_length=20, default='') class final(models.Model): fshape = models.CharField(max_length=20, default='') fcolor = models.CharField(max_length=20, default='') fnmae = models.CharField(max_length=20, default='') fdescr = models.TextField(max_length=50, default='') I want to compare shape from Image model with final model fshape if shape and fshape are equal then display fshape -
Django: set-cookie causes cookies to be stored in the backend instead of the frontend
example.com is frontend (Next.js) api.example.com is backend (Django) For some reason, the cookie is stored on the backend domain. This does not allow the front-end to access the stored cookies. I have implemented an authentication API using the following, but as far as I can tell, there is no setting to change the domain where cookies are stored. django-cors-headers dj-rest-auth djangorestframework-simplejwt CORS_ALLOWED_ORIGINS = ['https://example.com'] CORS_ALLOW_CREDENTIALS = True How can I store cookies on the front-end domain? -
CSS and Bootstrap only working on one html page and not the other
I launched my app on Heroku and everything seems to be working as usual except that the design (css) is only fully working on my home.html page but not my results.html page. On the results.html page it seems that only some css components are working while others are not. I've attached pictures of the design differences as well as the header code where I link my css and bootstrap. I would appreciate any help in knowing why my results.html page is not fully loading the css file. home.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <!-- jquery --> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <!-- Drag and drop script --> <script src="{% static 'PRIIIME_Travel/js/drag_drop.js' %}"></script> <!-- Get value of ranking boxes script --> <script src="{% static 'PRIIIME_Travel/js/get_value.js' %}"></script> <!-- Meta tags --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="robots" content="noindex, nofollow"> <link rel="icon" type="image/png" href="{% static 'logo/PRIIIME_Logo.png' %}" /> <!-- Bootstrap --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <!--- Include CSS --> <link rel="stylesheet" href="{% static 'PRIIIME_Travel/css/home.css' %}" type="text/css" /> <title>Travel</title> </head> results.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <!-- jquery --> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <!-- Drag and drop script --> <script src="{% … -
AttributeError: Got AttributeError when attempting to get a value for field `password2` on serializer `RegisterSerializer`
Original exception text was: 'CustomUser' object has no attribute 'password2'. I am trying to create a serializer for creating users but this error comes up when I try to create the model. Am I not allowed to have serializer fields that the Model doesn't have? class RegisterSerializer(serializers.Serializer): email = serializers.EmailField() username = serializers.CharField(max_length=150) password = serializers.CharField(max_length=128) password2 = serializers.CharField(max_length=128) profile_img = serializers.ImageField() def create(self, validated_data): email = validated_data.get('email') username = validated_data.get('username') password = validated_data.get('password') profile_img = validated_data.get('profile_img') return CustomUser(email=email, username=username, password=password, profile_picture=profile_img) def update(self, instance, validated_data): instance.email = validated_data.get('email', instance.email) instance.username = validated_data.get('username', instance.username) instance.password = validated_data.get('password', instance.password) instance.profile_img = validated_data.get('profile_img', instance.profile_img) return instance -
NameError When Running Python script through Bash
I am trying to run some python (Django) files via Bash (for some cronjobs); however I am coming across some odd errors. Setup is basically a .sh script I run with bash that loads some source files & then runs a python file via Django Shell. For demonstration purposes I have commented out some parts of the bash script, that I was using during testing. Bash Script #!/bin/bash source /home/grlaer/Desktop/mensam_games/bin/activate source /home/grlaer/Desktop/mensam_games/vars.env cd /home/grlaer/Desktop/mensam_games/cards_refactor #python3 manage.py shell < tcg_sku/test_bash.py ./manage.py shell < tcg_sku/test_bash.py #cat tcg_sku/test_bash.py | ./manage.py shell exit 0 Python Script from datetime import datetime print(datetime.now()) def do_this(): print("Its printing datetime") print(datetime.now()) return None do_this() Error/Traceback 2022-01-16 00:11:02.698550 Its printing datetime Traceback (most recent call last): File "./manage.py", line 22, in <module> main() File "./manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/grlaer/Desktop/mensam_games/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/grlaer/Desktop/mensam_games/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/grlaer/Desktop/mensam_games/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/home/grlaer/Desktop/mensam_games/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/home/grlaer/Desktop/mensam_games/lib/python3.8/site-packages/django/core/management/commands/shell.py", line 93, in handle exec(sys.stdin.read()) File "<string>", line 12, in <module> File "<string>", line 9, in do_this NameError: name 'datetime' is not defined I run bash test_bash.sh from the command line, and I get the … -
I Have a problem deploying my Django app on heroku [closed]
I am trying to deploy my django app on heroku, but it seems not to work because of the below error. ERROR: Could not find a version that satisfies the requirement kivy-deps.angle==0.3.0 (from versions:none) ERROR: No matching distribution found for kivy-deps.angle==0.3.0 ! Push rejected, failed to complete python app. ! Push failed The above is the error during my deployment process. I am using Python version 3.9.3 Django version 3.2.9 It will be of much help for me to hear a solution from you. -
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?