Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django_heroku.settings(locals()) KeyError: 'MIDDLEWARE' and 'MIDDLEWARE_CLASSES'
settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ALLOWED_HOSTS = ['my-app.herokuapp.com', '127.0.0.1:8000', 'localhost'] django_heroku.settings(locals()) STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'build/assets') ] error (2 exceptions) remote: Traceback (most recent call last): remote: File "/app/.heroku/python/lib/python3.9/site-packages/django_heroku/core.py", line 97, in settings remote: config['MIDDLEWARE_CLASSES'] = tuple(['whitenoise.middleware.WhiteNoiseMiddleware'] + list(config['MIDDLEWARE_CLASSES'])) remote: KeyError: 'MIDDLEWARE_CLASSES' remote: django_heroku.settings(locals()) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django_heroku/core.py", line 99, in settings remote: config['MIDDLEWARE'] = tuple(['whitenoise.middleware.WhiteNoiseMiddleware'] + list(config['MIDDLEWARE'])) remote: KeyError: 'MIDDLEWARE' I am trying to deploy my web app but I am getting this error everytime, cannot find a solution anywhere... nothing wrong with the Procfile, requirements.txt and runtime.txt, any help is appreciated! -
Creating Multible IDs for multible Buttons in one <Input> Tag
I'm working on a TicTacToe game using Django/Djangotemplates, Python and a bit Javascript. I've come across a problem tho. i only have one Button which is for-looped 9 times. its ID is its index. Now I'm not certain how to add the {{index}} which i defined in the for loop in the javascript onclick function. here the html template <div class="grid-container"> {% for index in object.board %} <div class="grid-item"> <input onclick="change(button.id)" class="buttonsize btn-outline-purple" type="submit" value="" name="button" id="{{index}}"> </div> {% endfor %} </div> </div> </article> </form> <script> function change(inputid){ console.log("test") var elem = document.getElementById(inputid); if (elem.value=="") elem.value = "X" } </script> here the models.py class TicTacToe(models.Model): player1 = models.ForeignKey(User, on_delete=models.CASCADE, default="X", related_name="tictactoe_as_player1") player2 = models.ForeignKey(User, on_delete=models.CASCADE, default="O", related_name="tictactoe_as_player2") current_player = models.ForeignKey(User, on_delete=models.CASCADE, related_name="tictactoe_current_player") title = models.CharField(max_length=100) board = models.CharField(max_length=9, default="012345678") def __str__(self): return self.title def get_absolute_url(self): return reverse('tictactoe-detail', kwargs={'pk': self.pk}) and here the views.py class TicTacToeCreateView(LoginRequiredMixin, CreateView): model = TicTacToe template_name = 'website/newgame_form.html' fields = ['player1', 'player2', 'current_player', 'title', 'board'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) class TicTacToeDetailView(UpdateView): model = TicTacToe fields = ['player1', 'player2', 'current_player', 'title', 'board'] def clean(self): if 'button0' in self.data: print('button0') i also got a database but there is really not much in there except … -
File Uploading in deployed Django applications
Where to store the images when a Django application is deployed through "Heroku" if I need to upload images using the same application after deployment ? Amazon S3 services provide a solution but the file accessing urls has a certain expiry period, so after maximum of 7days I cannot access the file using the same URL -
Save multiple values in foreign key django
I wanted to save multiple relational objects in a foreign key but unfortunately, I'm getting an error which I attached below. I already have the object with ID of 189 in my DB error: { "tags": [ "Invalid pk \"189\" - object does not exist." ] } views.py queryset = PackageRoom.objects.all() serializer = PackageRoomSerializer(queryset, many=True) return Response(serializer.data) serializers.py class PackageRoomSerializer(serializers.ModelSerializer): tags = serializers.PrimaryKeyRelatedField(queryset=PackageRoom.objects.all(), many=True) class Meta: model = PackageRoom fields = ['id', 'name', 'description', 'tags'] models.py class Tag(models.Model): name = models.CharField(max_length=255, default='') description = models.CharField(max_length=255, default='') singleline = models.ManyToManyField(Singleline) class Meta: db_table = 'tags' class PackageRoom(models.Model): name = models.CharField(max_length=255, default='') tags = models.ForeignKey(Tag, on_delete=models.PROTECT) class Meta: db_table = 'package_rooms' -
Django cuts off values from the char fields in Model after save() method?
I've been trying to wrap my head around the following: whenever I submit a form that involves some text input in Django, a character is missing when the transaction is fulfilled. I am not only having the same problem with my own forms, but also those managed by allauth (the email always has the first letter missing when user registers). When I use the debugger to see what values are being passed in through the model, it all looks good. What happense after save() is called? Could it be sqllite causing the issue? Appreciate any pointers! Here is the code (I included some debug screenshots): @login_required def create_recurring_task(request): new_task = RecurringTask.objects.create(name=request.POST['name'], cloned_task_notion_id=request.POST['id'], cloned_task_url=request.POST['url'], database_id=request.POST['database-id'], owner=request.user) tasks = request.user.tasks.filter(database_id=request.POST['database-id'] return render(request, "tasks/partials/recurring-user-tasks-list.html", {'tasks': tasks}) -
Does the permission check the group or individual permissions?
so I have been having a small confusion regarding permissions. All my tables are made in the app called app. And each admin user is assigned to a specific group, which is shown below. Similarly for every page, depending on the user's permission they would be able to access different pages. And for every view, there is a custom decorator as shown. Which has the code written in a separate decorators.py file. def permissions_allowed(allowed=[]): def decorator(view_func): def wrapper_func(request, *args, **kwargs): if not request.user.is_staff: messages.warning(request, "403 FORBIDDEN: You are not authorized to view the admin page!") return redirect('home') for perm in allowed: if not request.user.has_perm(perm): messages.warning(request, "You don't have the permissions to complete this action. Please contact the admin!") return redirect ('adminHome') return view_func (request, *args, **kwargs) return wrapper_func return decorator So my questions: Is my syntax to check the permission correct? (as shown in the 2nd pic) When I use request.user.has_perm() does it check the group permissions? the individual permissions? or both of them? Please let me know what I am doing wrong since the code isn't running the way I want it to. Thanks! -
CSRF verification failed after adding a filefield on model
I'm having a weird problem. So I have an application where my model was completely fine until I added a Filefield on it. Now I'm getting a CSRF-Verification failed error, even if I don't try to upload a file and leave it blank, it gives me the error below. This is my model: class Municipality(models.Model): activate_date = models.DateField() deactivate_date = models.DateField() code = models.CharField(max_length=200) name = models.CharField(max_length=200) alt_name = models.CharField(max_length=200, blank=True, null=True) logo = models.FileField( upload_to='Logo/muni', max_length=200, blank=True, null=True) My Application is set up on AWS using AWS Lambda, S3, and other needed services My S3 bucket (where my file should be uploaded to) is defined in my settings.py file with the env variable that has been defined on AWS Lambda environment variables AWS_STORAGE_BUCKET_NAME = env('AWS_STORAGE_BUCKET_NAME', default=None) I don't get why my model won't save even if I don't include a file. The weird thing about it is that when I'm working locally, it doesn't give me this error. And I can save this model with or without uploading a file. Other models where no Filefield or Imagefield is defined are perfectly working online and locally. Any reasons why I'm getting this error whenever I try to add a Filefield … -
Django ModelAdmin join two models using QuerySet for view both columns
In my django application i have two models: class Results(models.Model): device = models.ForeignKey(Device, null=True, on_delete=models.SET_NULL) proj_code = models.CharField(max_length=400) res_key = models.SlugField(max_length=80, verbose_name="Message unique key", primary_key=True, unique=True) read_date = models.DateTimeField(verbose_name="Datetime of vals readings") unit = models.ForeignKey(ModbusDevice, null=True, on_delete=models.SET_NULL) and class VarsResults(models.Model): id = models.AutoField(primary_key=True) key_res = models.ForeignKey(Results, related_name="keyres", on_delete=models.CASCADE) var_id = models.ForeignKey(ModbusVariable, null=True, on_delete=models.SET_NULL) var_val = models.CharField(max_length=400, blank=True) var_val_conv = models.CharField(max_length=100, blank=True, null=True) base_byte_order = models.CharField(max_length=15) var_hash = models.CharField(max_length=400) has_error = models.BooleanField(default=False) Well i would in my admin.py create a ModelAdmin that can use both fields from two models in view: @admin.register(Results) class ModbusAdmin(admin.ModelAdmin): list_display = ('res_key', 'proj_code', 'read_date', 'unit' ...HERE I WOULD ALSO MY VarsResults MODEL FIELDS) list_filter = ('proj_code', 'unit') search_fields = ('proj_code', ) ordering = ('-read_date', 'proj_code') list_display_links = None readonly_fields = () def has_add_permission(self, request): return False def has_delete_permission(self, request, obj=None): return False def save_model(self, request, obj, form, change): pass def delete_model(self, request, obj): pass def save_related(self, request, form, formsets, change): pass How can i use for example a queryset from my two models instead a single model in my ModelAdmin for use both fields? So many thanks in advance -
Django and Angular communication failure
I have developed a small Angular app with a service script to add a consumer form info to a MongoDB database: const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) } @Injectable() export class DbService { baseMongodbApiUrl = "http://localhost:8000/api/apdjango"; constructor(private httpClient: HttpClient) { } addConsumerMongodb(consumer: Post): Observable<Post> { return this.httpClient.post<Post>(`${this.baseMongodbApiUrl}` + `/handle_consumer`, consumer, httpOptions); } } I have also written this Django method in my views.py file to add a consumer: @csrf_exempt @api_view(['GET', 'POST', 'DELETE']) def handle_consumer(request): if request.method == 'POST': try: consumer_data = JSONParser().parse(request) consumer_serializer = ConsumerModelSerializer(data=consumer_data) if consumer_serializer.is_valid(): consumer_serializer.save() print(consumer_serializer.data) response = { 'message': "Successfully uploaded a consumer with id = %d" % consumer_serializer.data.get('id'), 'consumers': [consumer_serializer.data], 'error': "" } return JsonResponse(response, status=status.HTTP_201_CREATED) else: error = { 'message': "Can not upload successfully!", 'consumers': "[]", 'error': consumer_serializer.errors } return JsonResponse(error, status=status.HTTP_400_BAD_REQUEST) except: exceptionError = { 'message': "Can not upload successfully!", 'consumers': "[]", 'error': "Having an exception!" } return JsonResponse(exceptionError, status=status.HTTP_500_INTERNAL_SERVER_ERROR) and of course I have put the url pattern in my urls.py: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/apdjango$', handle_consumer), url(r'^.*', TemplateView.as_view(template_name="home.html"), name="home") ] When I use postman to Post to http://localhost:8000/api/apdjango, it goes through and I see the success message, but when I invoke my Angular service method, I … -
403 Response when I use requests to make a post request
My core code is as follows: import requests url='https://www.xxxx.top' #for example data=dict() session = requests.session() session.get(url) token = session.cookies.get('csrftoken') data['csrfmiddlewaretoken'] = token res = session.post(url=url, data=data, headers=session.headers, cookies=session.cookies) print(res) # <Response [403]> The variable url is my own website, which is based on Django. I know I can use @csrf_exempt to disable CSRF, but I don't want to do that. However, it return 403 response when I use requests to make a post request. I wish someone could tell me what was wrong with my approach. -
Django download files directly from S3 bucket to browser downloads folder
At the moment I am downloading files directly to my desktop from Django, it is possible to change the code so that when a user accesses my report the files will download directly into their browser downloads folder? My code below s3.Bucket(bucket_name).download_file(item, f'/Users/user_name/Desktop/filename.txt') -
Django Error while trying to migrate model on Postgres/Geoserver
I have a doubt similar to Django Error while trying to migrate model on Postgre DB. However I cannot solve my issue. I get the same error django.db.utils.DataError: NUMERIC precision 65535 must be between 1 and 1000 LINE 1: ...RIMARY KEY, "geom" geometry(POINT,4326) NULL, "x" numeric(65... And this is a part of the models.py class Water43262(models.Model): geom = gis_models.PointField(blank=True, null=True) x = models.FloatField(blank=True, null=True) y = models.FloatField(blank=True, null=True) sample = models.FloatField(blank=True, null=True) t_1 = models.FloatField(db_column='t - 1', blank=True, null=True) # Field renamed to remove unsuitable characters. ph_1 = models.FloatField(db_column='ph - 1', blank=True, null=True) # Field renamed to remove unsuitable characters. turb_1 = models.FloatField(db_column='turb - 1', blank=True, null=True) # Field renamed to remove unsuitable characters. -
how to let a superuser fill some forms for other users
I want to create a Django app that has two types of users. A regular user can register and fill in some contact and personal info on their profile page. The staff users have the ability to edit or add some additional info for the regular users. To be more specific, they need to fill a scientific survey for every user. Firstly, I need a page that shows all the users sorted by those who have the survey object and those who don't, and finally, by clicking on their name, the staff user gets redirected to the survey form related to that specific user. Do you guys have any suggestions on how am I supposed to do this? I created a model like this: class ScientificSurvey(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) info1 = models.CharField(max_length=24, choices=SURVEY_CHOICES) info2 = models.CharField(max_length=24, choices=SURVEY_CHOICES) info3 = models.CharField(max_length=24, choices=SURVEY_CHOICES) info4 = models.CharField(max_length=24, choices=SURVEY_CHOICES) info5 = models.CharField(max_length=24, choices=SURVEY_CHOICES) Users themselves cannot access this model and only the staff user is allowed to create or edit one for the users. I couldnt find anything on the web that could help me. -
Image uploading in django application for in production
(1) I'm trying to upload images through my django application, I upload the images into a folder and store its address/url (media url) into the database. I deployed the application in heroku, but uploading cannot be done with error "read-only file system". (2)So I moved to AWS S3 bucket services, where I can store the images in a bucket, but the image accessing urls created while uploading has expiry period of maximum 7 days, which is not good website for production because i can't use the uploaded images after 7 days. The problem arises in to situations, please provide feasible solution/alternative. -
Foregin key value in Django Rest Framework serializer
serializers.py class CarsCreateSerializer(serializers.ModelSerializer): class Meta: model = Car fields = '__all__' class RatesCreateSerializer(serializers.ModelSerializer): car_id = serializers.CharField(source='car.id', read_only=True) class Meta: model = Rate fields = ['car_id', 'grade'] models.py class CarsCreateSerializer(serializers.ModelSerializer): class Meta: model = Car fields = '__all__' class RatesCreateSerializer(serializers.ModelSerializer): car_id = serializers.CharField(source='car.id', read_only=True) class Meta: model = Rate fields = ['car_id', 'grade'] views.py class RateCar(APIView): def post(self, request): serializer = RatesCreateSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def get(self, request): rates = Rate.objects.all() serializer = RatesCreateSerializer(rates, many=True) if serializer: return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_204_NO_CONTENT) I am new to Django Rest Framework and checked some tutorials. Now I am trying to create my own structure which is like following. I want to use POST method with arguments above and I can't manage to save card_id. When I send POST method my result is : -
Save multiple relational objects in foreign key django
I want to make one to many relation between models and in Django, we need to use ForeignKey for it. I will multiple IDs of the relational objects in an array from the frontend but I'm confused that how will I save these multiple relational object in it? each package room can have multiple tags but the tags will have only one package room. models.py class Tag(models.Model): name = models.CharField(max_length=255, default='') description = models.CharField(max_length=255, default='') singleline = models.ManyToManyField(Singleline) class Meta: db_table = 'tags' class PackageRoom(models.Model): name = models.CharField(max_length=255, default='') tags = models.ForeignKey(Tag, on_delete=models.PROTECT) class Meta: db_table = 'package_rooms' the JSON object I will receive from the frontend { "name": "Test Room", "tags": [1, 2, 3, 4, 5] // IDs of Tags } -
Sending a emqil with an attachment from django
djando gurus! I need your help! I have an app. It should get the file from the form, then save it to the database and send it by email. I made a model, a form and a view. It seems that everything works fine, the file is saved in the database, a message with an attachment is sent. But the file size in the email attachment = 0 bytes and there is nothing to open it in any email client. What am I doing wrong? Here is a bit of my code: models.py: class Email(models.Model): ... email = models.EmailField(default='...', verbose_name='Email') forms.py: class EmailForm(forms.ModelForm): class Meta: model = Email fields = [..., 'time', 'file', ...] widgets = { ... 'file': forms.FileInput(), } views.py: def sender(request): if request.method == 'POST': form = EmailForm(request.POST, request.FILES) if form.is_valid(): email_save = form.save() ... email_date = request.POST.get('date', '') html_content = render_to_string('email_sender/email_tmpl.html', { ... }) txt_content = strip_tags(html_content) email = EmailMultiAlternatives( email_title, txt_content, settings.EMAIL_HOST_USER, [email_adress] ) email.attach_alternative(html_content, 'text/html') if request.FILES: email_file = request.FILES['file'] email.attach(email_file.name, email_file.read(), email_file.content_type) email.send() return redirect(sender) -
Adding "Did you mean?" feature in Django app
I am working on a simple django app. I have searchbar in which user enters text and then presses search (or enter) and then another page opens with picture of searched word. If user enters wrong word (which is not in dictionary), nothnig happens. I want that, after entering wrong word, new page opens where would be did you mean feature: there would be corrected word which user probably wanted to write and link on picture of that word. I use Norvig's spelling corrector (https://norvig.com/spell-correct.html) I have Index.html: <!DOCTYPE html> <head> <title>Autocomplete with Datalist</title> </head> <body> <h1>DropDown List Autocomplete</h1> <hr /> <!-- horizontal line --> <input list="ddlcomplete" name="q" placeholder="Search fruit name" /> <datalist id="ddlcomplete"> {% for result in autocomplete%} <option>{{result.naziv}}</option> {% endfor %} </datalist> {% if voce.image %} <img src="{{ voce.slika.url }}" class="img-responsive" /> {% else %} <p>No image to preview</p> {% endif %} </body> </html> Spell.py (Norvig's corrector) (in big.txt are all words from dictionary - words that are possible to search for): import re from collections import Counter def words(text): return re.findall(r'\w+', text.lower()) WORDS = Counter(words(open('big.txt').read())) def P(word, N=sum(WORDS.values())): "Probability of `word`." return WORDS[word] / N def correction(word): "Most probable spelling correction for word." return max(candidates(word), key=P) def … -
Login data in token authentication
I used to get this data when i was using session authentication. This data is created when user login from different browser. (on new session object) How do i create this data in token authentication? Since token remains same for all user i cant use post_save / if created signals. Also how do i logout specific user like we used to delete session in session authentication. Thanks in advance! -
Running celery worker on ECS Task and using SQS as a broker
I am building a web application that requires some long running tasks to be on AWS ECS using celery as a distributed task queue. The problem I am facing is that my celery worker running on ECS is not receiving tasks from SQS even though it seems to be connected to it. Following are the logs from ECS task. /usr/local/lib/python3.8/site-packages/celery/platforms.py:797: RuntimeWarning: You're running the worker with superuser privileges: this is absolutely not recommended! Please specify a different user using the --uid option. User information: uid=0 euid=0 gid=0 egid=0 warnings.warn(RuntimeWarning(ROOT_DISCOURAGED.format( -------------- celery@ip-xxx-xxx-xxx-xxx.us-east-2.compute.internal v5.0.1 (singularity) --- ***** ----- -- ******* ---- Linux-4.14.252-195.483.amzn2.x86_64-x86_64-with-glibc2.2.5 2021-12-14 06:39:58 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: emptive_portal:0x7fbfda752310 - ** ---------- .> transport: sqs://XXXXXXXXXXXXXXXX:**@localhost// - ** ---------- .> results: disabled:// - *** --- * --- .> concurrency: 2 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> emptive-celery2.fifo exchange=sync(direct) key=emptive-celery.fifo [tasks] . import_export_celery.tasks.run_export_job . import_export_celery.tasks.run_import_job [Errno 2] No such file or directory: 'seq_tokens/emptive-staging_web_sequence_token.txt' [Errno 2] No such file or directory: 'seq_tokens/emptive-staging_web_sequence_token.txt' 2021-12-14 06:39:58 [INFO] Connected to sqs://XXXXXXXXXXXXXXXXX:**@localhost// [Errno 2] No such file or directory: 'seq_tokens/emptive-staging_web_sequence_token.txt' [Errno 2] No … -
How to run multiple Django projects on Apache webserver (CentOS)?
I have a Apache webserver and deployed multiple Django projects. So I want to know that what should do if somehow server shutdown or unable to connect with server. How to start or restart services to run my projects. For now, when I am closing my Kitty screen then projects are also not running. Please help me regarding how to run my django projects if I close Kitty session too. I am attaching screenshot below. -
Django UpdateView: Can't update order informations
in my application, I have a template where I should update the order's infos, I succeeded to get two forms in the same template, but I need to update the order's information once I submit it, and here where is the issue. models.py class Order (models.Model): product = models.ManyToManyField(Product, through='OrderProduct') customer = models.ForeignKey(Customer, on_delete=models.CASCADE,) quantity = models.IntegerField(default=1) status = models.TextField(choices=ORDER_STATUS, default='Pending') class Customer(models.Model): full_name = models.CharField(max_length=150) address = models.CharField(max_length=1500, null=True) phone = models.CharField(max_length=20) city = models.CharField(max_length=100) email = models.EmailField(null=True) def __str__(self): return self.full_name views.py class OrderUpdateView(LoginRequiredMixin, RedirectToPreviousMixin, UpdateView): model = Order form_class = OrderManageForm second_form_class = CustomerForm template_name = 'dashboard/order_details.html' login_url = '/login/' def get_object(self): return Order.objects.get(id=self.kwargs['order_id']) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) customer = Customer.objects.get(order__id=self.kwargs['order_id']) context['customer'] = self.second_form_class(instance=customer) return context -
Get list of fileds from reverse relationship
I am trying to get the list of count of a field based on date so I can plot stacked bar graph on frontend. These are my models: class BaseModel(models.Model): id: int created_at = models.DateTimeField(verbose_name="Created", auto_now_add=True) updated_at = models.DateTimeField(verbose_name="Last Updated", auto_now=True) class Meta: abstract = True class A(BaseModel): name = models.CharField(max_length=512, null=True, blank=True) class B(BaseModel): a = models.ForeignKey(A, on_delete=models.CASCADE) class C(BaseModel): b = models.ForeignKey(B, on_delete=models.CASCADE) I am trying to get the count (as list) of B and C when getting the list of A for last 7 days. But I am getting count instead not an object. Using recharts on frontend, my desired output format will be (using sample data from internet): { "items": [ { "name": "android app", "chart_data": [ { "name": "A", "x": 12, "y": 23, "z": 122 }, { "name": "B", "x": 22, "y": 3, "z": 73 }, { "name": "C", "x": 13, "y": 15, "z": 32 } ] }, { "name": "My", "chart_data": [ { "name": "A", "x": 12, "y": 23, "z": 122 }, { "name": "B", "x": 22, "y": 3, "z": 73 }, { "name": "C", "x": 13, "y": 15, "z": 32 } ] } ] } -
Django Schedule task at particular time periodically from user's order in app (without celery)
I am creating a Django App where the user can schedule some tasks to happen at a particular time. for example. in google calendar we tell google what we will be doing tomorrow and then at right time it sends us a notification. similarly here I want it to be flexible, for instance, the user can tell Django the time and function to run. Django will wait for the time and then run the function. like he said turn off lights at 12 pm then Django will do it. or for example:- user says remind me to go to gym in 30 minutes And then after 30 minutes he gets notification. (only Django method without celery or something will be appretiated) Thanks! -
Reverse for 'entrypage' with no arguments not found. 1 pattern(s) tried: ['wiki/(?P<title>[^/]+)$']
VIEWS.PY from django.shortcuts import render from django.shortcuts import redirect from django.urls import reverse from django.http import HttpResponseRedirect from django import forms import markdown2 from . import util class AddPageForm(forms.Form): title = forms.CharField(max_length=20) content = forms.CharField(widget=forms.Textarea( attrs={ "class": "form-control", "placeholder": "Tell us more!" }) ) def add_page(request): if request.method == "POST": form = AddPageForm(request.POST) entries = util.list_entries() if form.is_valid(): title = form.cleaned_data['title'] content = form.cleaned_data['content'] util.save_entry(title, content) for entry in entries: if title.upper() == entry.upper(): return render(request, "encyclopedia/errorpage.html") else: return HttpResponseRedirect(reverse('encyclopedia:entrypage')) else: return render(request, "encyclopedia/addpage.html", { "form": AddPageForm() }) URLS.PY app_name = "encyclopedia" urlpatterns = [ path("", views.index, name="index"), path("wiki/<str:title>", views.entry_page, name="entrypage"), path("search", views.search, name="search"), path("add_page", views.add_page, name="addpage"), ] ADDPAGE.HTML <form action="{% url 'encyclopedia:addpage' %}" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit" class="btn btn-secondary"> </form> LAYOUT.HTML <div> <a href="{% url 'encyclopedia:addpage' %}">Create New Page</a> </div> <div> I have tried updating the urls and the views to this but i keep getting error responses path("add_page/<str:title>", views.add_page, name="addpage"), def add_page(request, title): Please advise where this error response could be coming from as the above edits is what i saw in some other stackoverflow responses to clear the error but this didn't work for me. Thank you