Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
showing "Did not find any relations." though I have many tables while working in google app engine
Google App Engine Cloud Shell Terminal: SSL connection() Type "help" for help. postgres=> \l List of databases Name | Owner | Encoding | Collate | Ctype | Access privileges ---------------+-------------------+----------+------------+------------+----------------------------------------- cloudsqladmin | cloudsqladmin | UTF8 | en_US.UTF8 | en_US.UTF8 | daysdb | cloudsqlsuperuser | UTF8 | en_US.UTF8 | en_US.UTF8 | postgres | cloudsqlsuperuser | UTF8 | en_US.UTF8 | en_US.UTF8 | template0 | cloudsqladmin | UTF8 | en_US.UTF8 | en_US.UTF8 | =c/cloudsqladmin + | | | | | cloudsqladmin=CTc/cloudsqladmin template1 | cloudsqlsuperuser | UTF8 | en_US.UTF8 | en_US.UTF8 | =c/cloudsqlsuperuser + | | | | | cloudsqlsuperuser=CTc/cloudsqlsuperuser (5 rows) postgres=> \c daysdb Password: psql (13.1 (Debian 13.1-1.pgdg100+1), server 12.4) SSL connection() You are now connected to database "daysdb" as user "postgres". daysdb=> \dt Did not find any relations. I don't know where I am mistaking. Is there any method to give permission to view tables or something else... and when I directly run my app using gcloud app deploy command it shows error: LINE 1: ..._header"."mob_img", "days_header"."welcome" FROM "days_hea... which means my tables are not migrated. Please help me! -
How to check if a file is csv or not?
I have a django views function that converts csv into another delimiter format. But, I just want to convert csv file and reject other files. def index(request): csv_form = '' if request.method == 'POST': csv_form = CsvForm(request.POST, request.FILES) if csv_form.is_valid(): csv_file = TextIOWrapper(request.FILES['csv_file'].file, encoding='ascii', errors='replace') #other actions I cannot use the below code because this works with only binary files, but the csv module wants to have text-mode files instead. Any alternatives to proceed with only csv files. if not csv_file.name.endswith('.csv'): messages.error(request, 'THIS IS NOT A CSV FILE') -
Is it possible to substitute an image file for a user selected upload in Django?
I have a model that has an image field with the usual create and edit pages in my Django app. However I need a copy function for the user with the functionality to copy the image in addition to some of the other fields. Now it would be possible to copy the image entirely on the server side, however this gets messy with having to delete the image if the user cancels the copy, or if the user decides to replace the copied image with a new upload. So I was wondering if there was a different way, where the image to be copied is substituted in for the usual upload? Almost like as if the image file to be copied is temporarily downloaded to the client before they interact with the copy page. Current model code for reference: import os from uuid import uuid4 @deconstructible class UploadToPathAndRename(object): def __init__(self, path): self.sub_path = path def __call__(self, instance, filename): ext = filename.split('.')[-1] filename = '{}.{}'.format(uuid4().hex, ext) return os.path.join(self.sub_path, filename) class Foo(models.Model): name = models.CharField(db_index=True, max_length=60) image = models.ImageField(upload_to=UploadToPathAndRename( 'default'), blank=True) -
Multiplying an integer and a decimal in a Django model using model expressions
I am a Django and in one of my projects, I made this model: class Piece(models.Model): order = models.ForeignKey(Order,on_delete=models.CASCADE) coil = models.ForeignKey(Cut_Material ,on_delete=models.CASCADE) piece_length = models.DecimalField(max_digits=4, decimal_places=2) prime_pieces = models.IntegerField() reject_pieces = models.IntegerField() def __str__(self): return (str(self.piece_length)) class Meta: ordering = ["-order","piece_length"] I want to be able to multiply piece_length with prime_pieces to get running meters and here is my solution: Piece.objects.annotate(running_meters = (F('reject_pieces') * F('prime_pieces')), output_field=FloatField()) I get this error: TypeError: QuerySet.aggregate() received non-expression(s): <django.db.models.fields.FloatField>. Can anyone help me with a solution, please? -
Django "Table 'myproject.auth_user' doesn't exist"
I have a bunch of tables generated in different apps in my app. Because of some issue I had to drop all the tables and create them from the scratch. one app is related for profile. One I run these commands I get an error as below: python manage.py makemigrations Operations to perform: Apply all migrations: admin, myapp, auth, cities, contenttypes, sessions, users and by this: python manage.py migrate I get: Running migrations: No migrations to apply. After all I don't see the dropped tables between database tables and consciously after run server get errors which "Table 'myproject.auth_user' doesn't exist". I also tried to remove the files in the migrations folder but does not work. Most probably these files are stored somewhere which I don't find!! Do you have any suggestion? -
How to change id field from uuid type to integer in a django model
My model as exists it has the below format: class MyModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) How it is possible to turn id to be of integer type , auto incremented and primary key? As the default behaviour of db when someone does not define at all the id field Deleting id field and running : python manage.py makemigrations python manage.py migrate raises an error of : django.db.utils.ProgrammingError: cannot cast type uuid to integer LINE 1: ...MyModel" ALTER COLUMN "id" TYPE integer USING "id"::integer Deleting the id field as it is and create again the id field as below: id = models.AutoField(primary_key=True, unique=True) and running again (now with two migration files) python manage.py makemigrations python manage.py migrate raises the same error as before. Finally, changing the data type of the id field from uuid to integer directly from the db is not a good option and may cause deployment issues. How can I make this transition and keep my db working properly? -
How to preserve key order in a Django JSONField
I am having a hard time preserving the order of keys in a JSON object stored in a Django JSONField. I have tried using a custom encoder and decoder as per the docs, but the JSON object keeps re-ordeing itself: >>>from models import MyModel >>>my_dict = {"c": 3, "b": 2, "a": 1} >>>my_model = MyModel() >>>my_model.my_field = my_dict >>>my_model.save() >>>my_model.refresh_from_db() >>>my_model.my_field OrderedDict([('a',1), ('b', 2), ('c', 3)]) I would have expected it to return OrderedDict([('c',3), ('b', 2), ('a', 1)]). Here is what I've tried so far: models.py: import collections import json from django.db import models class OrderedEncoder(json.JSONEncoder): def encode(self, o): if isinstance(o, collections.OrderedDict): encoded_objs = [ f"{self.encode(k)}: {self.encode(v)}" for k, v in o.items() ] return f"{{{','.join(encoded_objs)}}}" else: return super().encode(o) class OrderedDecoder(json.JSONDecoder): def __init__(self, *args, **kwargs): default_kwargs = { "object_pairs_hook": collections.OrderedDict } default_kwargs.update(kwargs) super().__init__(*args, **default_kwargs) class MyModel(models.Model): my_field = models.JSONField(encoder=OrderedEncoder, decoder=OrderedDecoder) Any ideas? -
Django - Modifies models field arguments
I am not sure how to make a change in my code. I have 2 models that have the same fields and I want to respect the DRY principle and make just one model with a field "type" and to filter the objects by the type field, the problem is that these models on the category field have diferent categories choices and I'm wondering if I can add a function that will decide depending on the model type which choices to attribute. the models: class Income(models.Model): class IncomeCategory(models.TextChoices): SALARY = 'SLRY', _('Salary') PROFIT = 'PRFT', _('Profit') INTEREST = 'ITRT', _('Interest') DIVIDENT = 'DVDT', _('Divident') RENTAL = 'RNTL', _('Rental') CAPITAL = 'CPTL', _('Capital') ROYALTY = 'RYLT', _('Royalty') GIFT = 'GIFT', _('Gift') OTHERS = 'OTRS', _('Others') user = models.ForeignKey(User, on_delete=models.CASCADE), name = models.ChardField(_('Income Name')max_length=50), amount = models.DecimalField(_('Income Amount'), max_digits=10, decimal_places=3) category = models.CharField(_('Category'), max_length=4, choices=IncomeCategory.choices, default=IncomeCategory.SALARY) recurrent = models.BooleanField(default=False) created_date = models.DateTimeField(_('Created Date')auto_now_add=True) updated_date = models.DateTimeField(_('Updated Date')auto_add=True) def __str__(self): return f'{self.user.username} - {self.name}' class Spending(models.Model): class SpendinCategory(models.TextChoices): UTILITIES = 'UTLT', _('Utilities') RENT = 'RENT', _('Rent') INVOICES = 'INVC', _('Invoices') SHOPPING = 'SHPG', _('Shopping') FOOD = 'FOOD', _('Food') EDUCATION = 'EDCN', _('Education') FUN = 'FUN', _('Fun') INSETMENT = 'INVT', _('Investment') OTHERS = 'OTRS', … -
CoreAPI to OpenAPI schema generation transition (Django REST Framework)
Django REST Framework 3.10 (September 2019) introduced OpenAPI based schema generation instead of CoreAPI, which has been deprecated (see release notes here). I'm creating an API using the current actual 3.12.0 version (13th October 2020). This change introduces regressions: Redundant Operation IDs, A "workaround" is required to get schema using coreapi cli command (see here), Mandatory parameters defined in serializer are not extracted in schema generation, thus I cannot use the coreapi cli command. The last point is the really problematic one. I can easily switch from the OpenAPI to the (deprecated) CoreAPI AutoSchema class changing the url parameter in get_schema_view function and adding this in settings.py: REST_FRAMEWORK = { # [...] 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema', } Example Below is an example using both schema classes. models.py: class Operator(models.Model): code = models.IntegerField(unique=True, blank=False, null=False) first_name = models.CharField(max_length=45, unique=False, blank=False, null=False) last_name = models.CharField(max_length=45, unique=False, blank=False, null=False) serializers.py: class OperatorSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Operator fields = ['url', 'id', 'code', 'first_name', 'last_name'] views.py: class OperatorViewSet(viewsets.ModelViewSet): queryset = Operator.objects.all() serializer_class = OperatorSerializer permission_classes = [permissions.IsAuthenticated] Using Core API # No workaround coreapi get http://127.0.0.1:8000/api/openapi # [...] operators: { list([page]) create(code, first_name, last_name) read(id) update(id, code, first_name, last_name) partial_update(id, [code], [first_name], [last_name]) delete(id) } # … -
DJANGO - SWAGGER - Why serielizer was put into format of RESPONSE
Obviously, I am using Django to code, and want to document by drf_yasg lib its actually Swagger but the new version (I supposed so) Everything is fine, excepts that swagger automatically assume my OUTPUT or RESPONSE of my API is the Serielizers. As the image below Here is my Serializers.py class Serielizer_RecalculateDeliveryPromise(serializers.ModelSerializer): service_type = serializers.CharField(max_length = 68, min_length = 6, write_only= True) package_type = serializers.CharField(max_length = 68, min_length = 6, write_only= True) origin_handover_point = serializers.CharField(max_length = 68, min_length = 6, write_only= True) destination_handover_point = serializers.CharField(max_length = 68, min_length = 6, write_only= True) class Meta: model = Input_RecalculateDeliveryPromise fields = ['service_type', 'package_type', 'origin_handover_point', 'destination_handover_point'] Here is my models.py class Input_RecalculateDeliveryPromise(models.Model): service_type = models.CharField(max_length = 255, db_index = True, default = ) package_type = models.CharField(max_length = 255, db_index = True) origin_handover_point = models.CharField(max_length = 255, db_index = True) destination_handover_point = models.CharField(max_length = 255, db_index = True) Here is my views.py class recalculate_delivery_promise(generics.GenericAPIView): serializer_class = Serielizer_RecalculateDeliveryPromise def post(self, request): request_data = json.loads(request.body) serializer = self.serializer_class(data=request_data) serializer.is_valid(raise_exception=True) service_type = request_data["service_type"] package_type = request_data['package_type'] origin_hp = request_data['origin_handover_point'] destination_hp = request_data['destination_handover_point'] #some calculation return JsonResponse({'_price':25000}) #just an example Here is my urls.py in project from django.contrib import admin from django.urls import path, include from rest_framework import … -
Django test | DETAIL: Key (id)=(1) is still referenced from table "validation_loyaltydocumentvalidation"
I work on Python 3.7 and the project migrated recently from Django 1.11 to Django 2.0.9. When i run ./manage.py test I encounter the following error : django.db.utils.IntegrityError: update or delete on table "pizzeria_loyaltydocument" violates foreign key constraint "validation_docum_document1_id_94a0a84b_fk_pizzeria" on table "validation_loyaltydocumentvalidation" DETAIL: Key (id)=(1) is still referenced from table "validation_loyaltydocumentvalidation". It seems that issue come from my test setUp() : class PizzaTestCase(TestCase): def setUp(self): self.customer, self.record, self.best_pizza = create_pizzeria_context() # here documents are created using LoyaltyDocument.objects.create() create_loyalty_documents(self.customer) LoyaltyDocument.objects.filter( customer=self.customer, kind='loyalty' ).delete() self.loyalty_document = ProfileDocument.objects.create( customer=self.customer, kind='loyalty' ) def create_loyalty_documents(customer): loyalty_document = ProfileDocument.objects.create( kind="loyalty", customer=customer, ... As mentioned in the comment, a loyalty document with id = 1 is already created within create_loyalty_documents() and if a comment out that part i get no such error but most of my tests fails as i need that document deleted. Why such error appears as it was not the case while on Django 1.11 ? What am I doing wrong / How to overcome that error ? Thanks -
I want to remove some characters from a string in js
I am making an Website with Django (Python Framework). I am passing string like this : Products you ordered: {"pr7":[4,"Mi Phone 8 GB RAM, 128GB ROM",7000],"pr8":[5,"Usha Mixer Grinder (White)",1244],"pr9":[4,"iBall 10000 MAh power bank (Black)",1455]} from my models.py to views.py to my html template but I don't want to my string to be like this my string is : Products you ordered: {"pr7":[4,"Mi Phone 8 GB RAM, 128GB ROM",7000],"pr8":[5,"Usha Mixer Grinder (White)",1244],"pr9":[4,"iBall 10000 MAh power bank (Black)",1455]} I want my string to be like : Products you ordered: Mi Phone 8 GB RAM 128GB ROM,Usha Mixer Grinder (White),iBall 10000 Mah power bank (Black) -
Django query: Order by the number of the overlapped elements of array with a list variable
I have an ArrayField in my postgresql db table. I would like to order my queryset by the number of the overlapped elements with a fixed list variable. I couldn't find a solution using ORM. Then I apply this raw query stated in https://stackoverflow.com/a/51612751: SELECT i.food_list, x.ct FROM main_recipes i , LATERAL ( SELECT count(*) AS ct FROM unnest(i.food_list) uid WHERE uid = ANY('{water,banana}') ) x ORDER BY x.ct desc; The problem now is that I cannot include this solution to my queryset in ORM: qset = Recipes.objects.annotate(val=RawSQL(""" SELECT x.ct FROM main_recipes i , LATERAL ( SELECT count(*) AS ct FROM unnest(i.food_list) uid WHERE uid = ANY(%s) ) x """, (includeList,))).order_by('val') This gives the error: django.db.utils.ProgrammingError: more than one row returned by a subquery used as an expression I much appreciate your any kind of solution ORM or row. -
Django how to get db_column from object_list.values()
I have the following model. class TSample(models.Model): foo1_id = models.DecimalField(max_digits=8, decimal_places=2, db_column='foo1_id__c') foo2_f = models.DateTimeField(null=True) I have used a paginator and read data inside a loop as follows. query = self.model.objects.filter(...).order_by('updated_at') paginator = Paginator(query, self.batch_size) for i in paginator: data = list(i.object_list.values()) encoded_data = json.loads(json.dumps(data, cls=DjangoJSONEncoder)) print(encoded_data) The data I get does not have the db_column I have mentioned in the model. Instead the field name in the model. [{'foo1_id': 1.2, 'foo2_f': '2020-12-07T07:31:25Z'}] Expected data is, [{'foo1_id__c': 1.2, 'foo2_f': '2020-12-07T07:31:25Z'}] How can I get the expected result with the db_column name -
MultiValueDictKeyError in Django Project
View.py if req.method == 'POST': df = DocumentForm.objects.filter(document_id=id) logging.info('LOG: I am here') if df.exists(): for d in df: description = req.POST['{}'.format(d.description, False)] displayName = req.POST['{}'.format(d.displayName, False)] df.update(displayName=displayName, description=description) return redirect('/adboard/upd') HTML File <form class="needs-validation" action="{{id}}" method="POST" enctype="multipart/form-data" novalidate> {% csrf_token %} <div class="row mt-3 mb-3"></div> {% if messages %} <div class="alert alert-danger" role="alert"> {% for message in messages %} {{ message }} {% endfor %} </div> {% endif %} {% for df in data %} <div class="form-group"> <small class="text-muted bold-label m-lower">&#123;{{df.field}}&#125;</small> <label for="validationCustom01">{{df.displayName}}</label> <input type="text" class="form-control" id="validationCustom01" name="{{df.displayName}}" value="{{df.displayName}}" placeholder="Enter Display Name"> <label for="validationCustom01">{{df.description}}</label> <input type="text" class="form-control" id="validationCustom01" name="{{df.description}}" value="{{df.description}}" placeholder="Enter description"> <div class="invalid-feedback"> Please enter required fileds. </div> <!-- <div class="valid-feedback"> Looks good! </div> --> </div> {% endfor %} <button type="submit" class="btn btn-primary btn-red btn-block">SAVE</button> </form> What I am trying to achieve is. Pass a variable form to the user to fill And I get the result. I can't tell what the input id/name would be because it's a variable. But I am finding it difficult getting the value from the view.py file. -
Fill Many to Many field through API
I am trying to implement an API to add Agent. The Agent has Many To Many field, Role. I am using Django and Django Rest Framework. Here is the models : class Role(models.Model): code = models.CharField(max_length=50, primary_key=True) labe = models.CharField(max_length=50) def __str__(self): return '%s %s' % (self.labe, self.code) class Agent(models.Model): firstName = models.CharField(max_length=60) lastName = models.CharField(max_length=60) role = models.ManyToManyField(Role) So I created Serializers : class RegistrationSerializer(serializers.ModelSerializer): class Meta: model = Agent fields = ['email', 'firstName', 'lastName', 'role', 'phoneNumber', 'experienceWorkYeares'], role = serializers.PrimaryKeyRelatedField( many=True, read_only=True) extra_kwargs = { 'password': {'write_only': True}, } def save(self): agent = Agent.objects.create( email=self.validated_data['email'], firstName=self.validated_data['firstName'], lastName=self.validated_data['lastName'], phoneNumber=self.validated_data['phoneNumber'], experienceWorkYeares=self.validated_data['experienceWorkYeares'] role=self.validated_data['role'] // One of my multiple try but doesn`t work. ) agent.save() return agent How can I retrieve the role I sent via Postman and put it in the agent ? for the role I am POSTing role = "CODE1". Thank you so much in advance. Basically what I am trying to do is : For each Agent there one or more role. I trying a lot of thing and I follow documentation but I am not able to do it. -
Scheduler for Django 3.0
I'm in a project where we must schedule some tasks. Most of the time, we just need to launch in background some treatment to end a potentially long http request. We schedule a job that will take some times (but that need to be executed once). We're using Django (version 3.0) and we're using Azure ecosystem for the database/etc. We need a scheduler that: Can schedule jobs to be run asap (these jobs need to access database and django functionalities). Can manage concurency between django application : most likely, our application will be running on multiples workers (Azure web app). Can use database to store results. Can manage retry/failure/etc. I have used django-scheduler, but it doesnt manage concurency well. I have seen about celery but I'm not sure about the usage in these conditions. What are your advices ? Thanks -
Reverse for 'post_share' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<post_id>[0-9]+)/share/$']
show_more.html <p> <a href="{% url 'mains:post_share' post_id %}">Share This Post</a> </p> urls.py path('<int:post_id>/share/',views.post_share,name='post_share'), views.py def post_share(request, post_id): post = get_object_or_404(Post,pk=post_id, status='published') if request.method == 'POST': form = EmailPost(request.POST) if form.is_valid(): else: form = EmailPost() return render(request, 'mains/post_share.html', {'post':post,'form':form}) forms.py class EmailPost(forms.Form): name_subject = forms.CharField(max_length=400) email = forms.EmailField() description = forms.CharField(required=False,widget=forms.Textarea) Reverse for 'post_share' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<post_id>[0-9]+)/share/$']. This error is raising when i click on share the Post. Please help me to solve this Error. I will really appreciate your Help. -
how to access second models field of join operation in django templates
I'm doing a join operation Django. these are two models: in the users app: class User(AbstractBaseUser, PermissionsMixin): ... company = models.CharField(_('company'), default='', max_length=50, null=True, blank=True) ... in contacts app: class Contact(models.Model): owner = models.OneToOneField( User,null=True, blank=True, on_delete=models.CASCADE) ... in my views.py I'm doing a join operation like the following to get contacts distincted by sender_id and I want the company name of the sender. user_contacts = Contact.objects.distinct('sender_id').select_related() in my template I can access the contacts field like {{contact.sender_name}} but how to access the users field? this is my query: print(user_contacts.query) SELECT DISTINCT ON ("contacts_contact"."sender_id") "contacts_contact"."id", "contacts_contact"."owner_id", "contacts_contact"."sender_id", "contacts_contact"."sender_name", "contacts_contact"."chat_id", "contacts_contact"."receiver_id", "contacts_contact"."subject", "contacts_contact"."message", "contacts_contact"."myfile", "contacts_contact"."contact_date", "contacts_contact"."user_id", "contacts_contact"."is_answered", "contacts_contact"."message_id", "contacts_contact"."status", "users_user"."id", "users_user"."password", "users_user"."last_login", "users_user"."is_superuser", "users_user"."first_name", "users_user"."last_name", "users_user"."date_joined", "users_user"."is_active", "users_user"."is_staff", "users_user"."company", "users_user"."address", "users_user"."zipcode", "users_user"."city", "users_user"."country", "users_user"."tel", "users_user"."mobile", "users_user"."fax", "users_user"."email", "users_user"."user_id", "users_user"."title", "users_user"."website", "users_user"."avatar" FROM "contacts_contact" LEFT OUTER JOIN "users_user" ON ("contacts_contact"."owner_id" = "users_user"."id") -
heroku ps:scale web=1 Scaling dynos... Couldn't find that process type (web)
So I am making my portfolio python django website, while deploying I am getting an error I am try to type this heroku ps:scale web=1 and I am getting this error Scaling dynos... ! ! Couldn't find that process type (web). please help me out I want to show my class teacher this portfolio webpage but it would be very shameful to show her a locally hosted website -
Reverse for 'post_share' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<post_id>[0-9]+)/share/$']
show_more.html <p> <a href="{% url 'mains:post_share' post_id %}">Share This Post</a> </p> urls.py path('<int:post_id>/share/',views.post_share,name='post_share'), views.py def post_share(request, post_id): post = get_object_or_404(Post,pk=post_id, status='published') if request.method == 'POST': form = EmailPost(request.POST) if form.is_valid(): else: form = EmailPost() return render(request, 'mains/post_share.html', {'post':post,'form':form}) forms.py class EmailPost(forms.Form): name_subject = forms.CharField(max_length=400) email = forms.EmailField() description = forms.CharField(required=False,widget=forms.Textarea) Reverse for 'post_share' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<post_id>[0-9]+)/share/$']. This error is raising when i click on share the Post. Please help me to solve this Error. I will really appreciate your Help. -
nginx have access to static file but raises 403 permission error for downloading a file
I use django and nginx is the server. nginx has access to static folder and serves all static files. but I've defined a file field like: pp_file_url = models.FileField(, upload_to='app/', default='app/app.apk') and app folder has been created inside static folder which nginx has access to. I can properly upload a file in admin and I can access that file on the server. but when I want to download it through the admin of my website it raises this error: 403 Forbidden nginx/1.14.0 (Ubuntu) I've defined the static folder in .conf and used chmod 777 /static-root/app. It didn't solve my problem. -
Django Change a form structure by user
I am working in Django project that need to have a form that the user can change the structure of the form, for example if the default form is <form> <input type="text" value="3"> </form> the user can change it like <form> <input type="text" value="5"> <input type="text" value="6"> </form> The user can add, edit or delete an input. I have seen on internet the django admin site but it change only the data. Please, Help me -
Reverse for 'post_share' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<post_id>[0-9]+)/share/$'] [ ASKING AGAIN ]
show_more.html <p> <a href="{% url 'mains:post_share' post_id %}">Share This Post</a> </p> urls.py path('<int:post_id>/share/',views.post_share,name='post_share'), views.py def post_share(request, post_id): post = get_object_or_404(Post,pk=post_id, status='published') if request.method == 'POST': form = EmailPost(request.POST) if form.is_valid(): else: form = EmailPost() return render(request, 'mains/post_share.html', {'post':post,'form':form}) forms.py class EmailPost(forms.Form): name_subject = forms.CharField(max_length=400) email = forms.EmailField() description = forms.CharField(required=False,widget=forms.Textarea) I am asking it again but the previous answers didn't solve my problem. So i think i should upload it again with more efficiently. Reverse for 'post_share' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<post_id>[0-9]+)/share/$']. This error is raising when i click on share the Post. Please help me to solve this Error. I will really appreciate your Help. -
django, mod_wsgi and apache: error client denied by server configuration
My apache sites-available configuration is as below. (I already tried many things from other's answers for the same problem) In the browser, it is showing the error forbidden error and in the error log shows client denied by server configuration error. <VirtualHost *:80> #ServerName www.project.com ServerAdmin user_xmaster@localhost #DocumentRoot /var/www/html DocumentRoot /home/user_x/project/django-project Alias /static /home/user_x/project/user_x/static <Directory /home/user_x/project/user_x/static> Require all granted </Directory> <Directory /home/user_x/project/django-project> <Files wsgi.py> Require all granted </Files> </Directory> WSGIApplicationGroup %{GLOBAL} WSGIPassAuthorization On WSGIDaemonProcess user_xenv python-path=/home/user_x/project/django-project python-home=/home/virtualenvs/env WSGIProcessGroup user_xenv WSGIScriptAlias / /home/user_x/project/django-project/wsgi.py ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost>