Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how not allow users to download files in Django
I'm building and online course web application. Is there any way to prevent users not to be able to download video or audio files in Django? -
Django celery - Restart the task when it's completed
@app.task def Task1(): print("this is task 1") return "Task-1 Done" Just take an example I want to restart the task when it's completed -
How to fix heroku app deployment? App runs locally but not online
I'm trying to deploy a dog breed classifier django app on heroku, but for some reason heroku doesn't seem to find the path to the exported pkl model file. Whenever I run locally, everything works fine. I'm using the "path" module's "exist()" method to check for the presence of the file first before importing the module, hence the reason for the exception thrown. Here's the stack trace for the error: Environment: Request Method: GET Request URL: https://mydogbreed.herokuapp.com/ Django Version: 3.2.5 Python Version: 3.9.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'api.apps.ApiConfig', 'corsheaders', 'frontend'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware'] Traceback (most recent call last): File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/base.py", line 167, in _get_response callback, callback_args, callback_kwargs = self.resolve_request(request) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/base.py", line 290, in resolve_request resolver_match = resolver.resolve(request.path_info) File "/app/.heroku/python/lib/python3.9/site-packages/django/urls/resolvers.py", line 556, in resolve for pattern in self.url_patterns: File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/app/.heroku/python/lib/python3.9/site-packages/django/urls/resolvers.py", line 598, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/app/.heroku/python/lib/python3.9/site-packages/django/urls/resolvers.py", line 591, in urlconf_module return import_module(self.urlconf_name) File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, … -
Is there a workaround for Django's `ModelDoesNotExist` error in a situation like this?
So I get a ModelDoesNotExist error when I run manage.py runserver because in a file in my directory, I make a query to a table which has not been populated yet. def __init__(self): self.spotify_object = SocialToken.objects.get(account__provider="spotify") The above is a class instantiated to perform some sort of authentication and the SocialToken table gets populated only after I login. Now, I was wondering if there was a way to escape the error by triggering this part of the code only after I login? I only use the class in an endpoint, and during that period, the table would have been populated but the fact that it is not populated before running the server is causing a DoesNotExist error. Is there a solution to this? Traceback File "C:\Users\Kwaku Biney\Desktop\sparison-1\project\Sparison\views.py", line 4, in <module> from .authentication import SparisonCacheHandler File "C:\Users\Kwaku Biney\Desktop\sparison-1\project\Sparison\authentication.py", line 43, in <module> cache_handler = SparisonCacheHandler() , File "C:\Users\Kwaku Biney\Desktop\sparison-1\project\Sparison\authentication.py", line 25, in __init__ self.spotify_object = SocialToken.objects.get(account__provider="spotify") File "C:\Users\Kwaku Biney\Desktop\sparison-1\project\venv\lib\site- packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Kwaku Biney\Desktop\sparison-1\project\venv\lib\site- packages\django\db\models\query.py", line 429, in get raise self.model.DoesNotExist( allauth.socialaccount.models.DoesNotExist: SocialToken matching query does not exist. In my views.py, I import the class which has the query and the error comes … -
How to display text in input in javascript?
I'm trying to save a price, but the price text doesn't appear in the input box. Where is the problem? How can I save the price? view price = form.cleaned_data['price2'] form price2 = forms.IntegerField(error_messages={'required': "1개 이상 선택 시 참여가 가능합니다."}, label="가격") script function pay_unit_func($par, unit_amount, quantity) { //1번 단 var unit_total_amount = $par.find('.price_amount').text((unit_amount * quantity).toLocaleString()); } function pay_total_func() { //2번 단 var amount_total = 0; var converse_unit = 0; $('.cart_list li').each(function () { converse_unit = $(this).find('.price_amount').text().replace(/[^0-9]/g, ""); amount_total = amount_total + (parseInt(converse_unit) || 0); }); var total_amount_money = $('.cart_total_price').children().find('.item_price').text(amount_total.toLocaleString()); var total_total_price = $('.cart_total_price').children().find('.total_price').text(total_price.toLocaleString()); } ddd <div class="cart_total_price"> <h2 style="font-size: 25px;"><p style="font-size: 19px; margin-top: 35px; margin-bottom: -25px;"><b>총 가격</b></p> <input class="item_price" style="margin-left: 220px; font-size: 23px; margin-bottom: 20px;" name="price2" id="price2" value="0"><span style="font-size: 23px;">원</span></p></h2> </div> -
How can we keep only delete operation in django-simple-history
We can keep the history of insert/update/delete operation in any table with django-simple-history in a Django Application. Is there any setting or configuration to keep only the history of deletion operation in a table with django-simple-history? -
Replace html web page by ajax return data on Django 3.2
I managed to use ajax to change the content of my web page without updating it but the only problem is that I cannot replace the old content with the new one which I return, when I do consol.log (data ) I have the new html, but I can't change it for the user Ajax for send the form <script> $(function() { $("#show_type").submit(function(event) { // Stop form from submitting normally event.preventDefault(); let friendForm = $(this); // Send the data using post let posting = $.post( friendForm.attr('action'), friendForm.serialize() ); // if success: posting.done(function(data) { console.log(data) <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< new html window.alert("success action"); // success actions, maybe change submit button to 'friend added' or whatever }); // if failure: posting.fail(function(data) { window.alert("fail action"); // 4xx or 5xx response, alert user about failure }); }); }); </script> Google chrome new html in console log: its that html i whant display in browser but i dont know how <div class="grid-container"> <div class="grid-item" start_at="10 août 2021 12:46" end_at="10 août 2021 17:45"> <span class="device-title">Dispositif nostart [ID]: C23</span> <div class="device-info"> <span class="left-text-icon map">Lieu: HIDE</span> <span class="left-text-icon start">Début: 10 août 2021 12:46</span> <span class="left-text-icon end">Fin: 10 août 2021 17:45</span> <span class="left-text-icon chief-go">Chef GO: cdcd chieffunc</span> <span class="left-text-icon dchief-go">Adjoin-Chef GO: did … -
Bad Request 400 - Django REST Framework
I have my api in Django and Django REST framework (DRF). Here is my settings file: DEBUG = False ALLOWED_HOSTS = ['http://localhost:3000', 'http://127.0.0.1:3000'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'MyApp.apps.MyappConfig', ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSESS': 'rest_framework.permissions.AllowAny', } # React's Port : 3000 CORS_ORIGIN_WHITELIST = [ 'http://localhost:3000', 'http://127.0.0.1:3000', ] CORS_ORIGIN_ALLOW_ALL = True MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', ] I am getting Bad Request (400) Error: I inspectd Chrome's network tab, here is what I got: Request URL: http://localhost:8000/api/list Request Method: GET Status Code: 400 Bad Request Remote Address: 127.0.0.1:8000 Referrer Policy: strict-origin-when-cross-origin Connection: close Content-Type: text/html Date: Wed, 11 Aug 2021 13:05:24 GMT Server: WSGIServer/0.2 CPython/3.8.1 X-Content-Type-Options: nosniff Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9 Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9 Cache-Control: max-age=0 Connection: keep-alive Host: localhost:8000 sec-ch-ua: "Chromium";v="92", " Not A;Brand";v="99", "Google Chrome";v="92" sec-ch-ua-mobile: ?1 Sec-Fetch-Dest: document Sec-Fetch-Mode: navigate Sec-Fetch-Site: none Sec-Fetch-User: ?1 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Mobile Safari/537.36 In React, I am getting: Access to XMLHttpRequest at 'http://localhost:8000/api/list/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. What is the … -
I want to select multiple data in django raw_id pop-up and add them inline
Nice to meet you, everyone. I'm creating a talent booking system on django admin. The models.py is as follows. I'm new to django. I'm sorry if there is an agenda that has already been resolved. [master models.py] class Talent(models.Model): def __str__(self): return self.name class Meta: verbose_name = _('Talent') verbose_name_plural = _('1-3. Talent') ordering = ['id'] name = models.CharField(_('Talent Name'), max_length=128, blank=False, null=False) class Contract(models.Model): def __str__(self): return str(self.contract_start_d) + '-' + str(self.contract_end_d) class Meta: verbose_name = _('Contract') verbose_name_plural = _('2-0. Contract') ordering = ['id'] model = models.ForeignKey(Talent, on_delete=models.CASCADE, verbose_name='Talent', blank=False, null=False) [event models.py] class Ticket(models.Model): def __str__(self): return str(self.id) class Meta: verbose_name = _('Ticket') verbose_name_plural = _('3-0. Ticket') ordering = ['id'] name = models.CharField(_('name'), max_length=128, blank=True, null=True) class TicketContract(models.Model): def __str__(self): return self.contract.model.name class Meta: verbose_name = _('TicketContract') verbose_name_plural = _('3-5.TicketContract') ordering = ['id'] ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE, verbose_name='Ticket') contract = models.ForeignKey(Contract, on_delete=models.CASCADE, verbose_name='Contract', null=False) [admin.py] class TicketContractInline(admin.TabularInline): model = TicketContract fieldsets = ( (_('Talent'), {'fields': ( 'contract', )}), ) search_fields = ('contract',) raw_id_fields = ('contract',) ordering = ('id',) extra = 1 class TicketAdmin(admin.ModelAdmin): fieldsets = ( (_('Ticket'), {'fields': ( 'name' )}), ) list_display = ( 'id', ) inlines = (TicketContractInline,) I have set models.py and admin.py like this, but … -
Django not updating pie chart on ajax success event?
I want to change the values in the pie chart whenever onchange event in a tag.But whenever onchange happens the piechart just disappears. Here how my ajax code goes: $( "#date" ).change(function() { $form=$('#form'); var datastring = $form.serialize(); var date=$('#month_date').val(); $.ajax({ url : '{% url 'here:pie_charts' %}', type : 'GET', data : { 'date': date, }, dataType:'html', success : function(data) { data: datastring, $('#form').html(data); }, }); return false; }); Django view returns like this: return HttpResponse(render_to_string(form_template, context, request)) My pie chart : I is not updating on ajax success event instead it disappears. var arr = []; // append multiple values to the array //some_value is the value from context . arr.push({{some_value}}, {{some_value}}); var config = { type: "pie", data: { datasets: [ { data:arr, backgroundColor: [""], label: "People", }, ], labels: ["some_labels'], }, options: { responsive: true, maintainAspectRatio: true, }, }; window.onload = function () { var ctx = document.getElementById("pie-chart").getContext("2d"); window.myPie = new Chart(ctx, config); }; </script> -
Django How to make the condition correct on an HTML page - search bar
I try to do a search engine if the word in my DB thah I created then display the word on the HTML page and if not then nothing.. I did it right in VIEW but I can not apply it on the HTML page I searched the internet and did not find an answer I'm sure I fall for something stupid. This is the view def Search_word(request): search = request.POST.get("search") #Grab the search item return render(request,"search_page.html", {"search":search}) this is the html: {%for i in Word.English_word%} {%if search in Word.English_word%} {{search}} {%endif%} {%endfor%} and the urls: path("Search_page",views.Search_word ,name="Search-page"), The problem is that even if the word is valid it does not show me anything .. -
Facing issue in custom manager of django
I am trying to create a custom manager to retrieve all posts with the published status. New to managers!! Thank you in advance <3. models.py class PublishedManager(models.Model): def get_query_set(self): return super(PublishedManager, self).get_query_set().filter(status='published') class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=255) slug = models.SlugField(max_length=255, unique_for_date='publish') author = models.ForeignKey( User, on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField( max_length=10, choices=STATUS_CHOICES, default='draft') objects = models.Manager() published = PublishedManager() class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) views.py def post_list(request): posts = Post.published.all() print(posts) return render(request, 'post/list.html', {'posts': posts}) def post_detail(request): post = get_object_or_404(Post, slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) return render(request, 'post/detail.html', {'post': post}) Error 'PublishedManager' object has no attribute 'all' (views.py, line 6, in post_list) -
Is there any way i can make vs code to format and properly handle django templates?
I tried to use prettier, but it's not handling the Django templates codes properly, is there any alternative to this extension? -
not all my column in 'render_table' are orderable, what can i do?
I use render_table from django_tables2 to write a table that contain 4 headers (Title, Delete, View, and Export), the title is orderable, but the other one are not, the problem is that render_table use class orderable in all elements, how can I edit that ? in HTML I call the function like this : <!-- table --> <div class="mt-3"> {% render_table table %} </div> and this is my table.py script : ENTRIES_TEMPLATE = "<a href='{% url 'form-entries' form=record.pk %}' class='btn btn-outline-info btn-small'><i class='fas fa-file'></i></a>" DELETE_TEMPLATE = "<a href='{% url 'dashboard-topic-delete' pk=record.pk %}' class='btn btn-outline-danger btn-small'><i class='fas fa-trash'></i></a>" VIEW_TEMPLATE = "<a href='{{record.pk}}' class='btn btn-outline-info btn-small'><i class='fas fa-edit'></i></a>" EXPORT_TEMPLATE = """ <div class="btn-group"> <button type="button" class="btn btn-outline-success dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Export </button> <div class="dropdown-menu"> <a class="dropdown-item" href="{{record.get_export_url}}?type=CSV"><i class='fas fa-file-csv'></i> csv</a> <a class="dropdown-item" href="{{record.get_export_url}}?type=XLS"><i class='fas fa-file-excel'></i> xlsx</a> </div> </div> """ # # id = tables.LinkColumn('forms:form-update',kwargs={"pk":A("pk")}) responses = tables.TemplateColumn(ENTRIES_TEMPLATE) delete = tables.TemplateColumn(DELETE_TEMPLATE) view = tables.TemplateColumn(VIEW_TEMPLATE) export = tables.TemplateColumn(EXPORT_TEMPLATE) class Meta: model = Topic template_name = "django_tables2/bootstrap.html" fields = ("Title","view","responses","delete","export") (Only ENTRIES_TEMPLATE need to be Orderable) -
python manage.py loaddata moderation_categories.json having giving me error or FFMPEG not installed
hello i am facing an issue of FFMPEG not istalled i am working on local and on production both working on local python manage.py loaddata moderation_categories.json works fine while on production running the same commands i am having the issue ERRORS: <class 'video_encoding.backends.ffmpeg.FFmpegBackend'>: (video_conversion.E001) ffmpeg binary not found: HINT: Please install ffmpeg. <class 'video_encoding.backends.ffmpeg.FFmpegBackend'>: (video_conversion.E001) ffmpeg binary not found: HINT: Please install ffmpeg. while on running the command docker-compose -f docker-compose-full.yml run --rm webserver python3 manage.py loaddata moderation_categories.json i am having the error traceback: Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/core/serializers/json.py", line 68, in Deserializer objects = json.loads(stream_or_string) File "/usr/local/lib/python3.7/json/__init__.py", line 348, in loads return _default_decoder.decode(s) File "/usr/local/lib/python3.7/json/decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/local/lib/python3.7/json/decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.7/site-packages/modeltranslation/management/commands/loaddata.py", line 61, in … -
Django - Is it possible to use other value than pk for modelform field?
I have a model form and I post the form via AJAX. One of the fields is a manytomany field and I render it as checkboxes. By default django uses PKs of the models in the queryset that is passed in. Is there a way to use another field of the model as value instead of PK values. (I have PK as integer - for a reason. I also have a UUID field which is not PK. I want to use that one for values.) -
context processor in django
To display product categories on the site in several views, I get information about the categories from the database. (Do this in at least 8 views) I use context processor to prevent duplicate codes. Is this method better and more efficient? In fact, by creating a context processor, I only get the category information from the database once and do not write it in any view anymore. Is there a better option? -
Sending emails from my django website, via sendgrid
I want to send account confirmation emails to all the users who sign up on my website, so it has to be an HTML email with the activation link. This is how i am trying to do it: import os from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail def my_view(request): current_site = get_current_site(request) mail_subject = 'Welcome To IIITU Alumni Network' to_email = email ctx = { 'user': user, 'domain': current_site.domain, 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token':account_activation_token.make_token(user), } message = Mail( to_emails = to_email, from_email = '<my email address>', subject = mail_subject, #I made this html page specifically for sending confirmation email #I am not sure if this is the correct way to do it html_content = render_to_string('network/email.html', ctx) ) try: #I have this key as an environment variable sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) #Now this is where the problem is response = sg.send(message) print(response.status_code) print(response.body) print(response.headers) return HttpResponse("A confirmation Email has been sent to your Institute email address. Please Confirm Your email to complete your registration") except Exception as e: print(e.message) return HttpResponse("The Server seems too busy!! Sorry for the inconvenience. Please try again later, or contact administrator if this problem persists.") When this particular view is rendered, it throws the following error message: 'UnauthorizedError' object … -
How to navigate to different routes in VueJs rendered in DJango Templates
I have a separate environment for front end which is written in ViewJS. I am trying to merge it with DJango default url. I have build it and able to render the screen in DJango server url by collectstatic and calling it in Django template. But it is loading all the screens of VueJs at once like below image. Even home screen is displaying without logging in which was working fine in isolated environment. Now even the api call is not triggering. How do I resolve this? main.js import Vue from 'vue' import App from './App.vue' import Router from 'vue-router' import axios from 'axios' import VueAxios from 'vue-axios' import Home from '@/components/Home' import Login from '@/components/Login' Vue.use(VueAxios, axios) Vue.use(Router) Vue.config.productionTip = false const routes = [ { path: '/Home', name: 'Home', component: Home }, { path: '/', name: 'Login', component: Login } ] const router = new Router({ routes, mode: 'history', base: '/test' }) new Vue({ router, render: h => h(App), }).$mount('#app') vue.config.js const path = require('path'); module.exports = { publicPath: '/static/src/vue/dist/', // Should be STATIC_URL + path/to/build outputDir: path.resolve(__dirname, '../static/src/vue/dist/'), // Output to a directory in STATICFILES_DIRS filenameHashing: false, // Django will hash file names, not webpack runtimeCompiler: true, … -
I don't know why Price can't be saved in DB
I am a student learning Django and JavaScript. I am trying to save quantity and price in my code, but no matter how I try, it is not saved. Quantity is stored, price2 is not. Please help me.. I feel like my head is going to explode in a week. Where is the cause? Where do I need to fix it? Where the hell is the problem? I want to display the price in javascript and store the corresponding value as price2. If you could help me, I would really, really, really, really appreciate it. html <form method="POST" action="{% url 'zeronine:join_create' id=product.product_code %}"> <div class="form-group row" style="margin-top: -5px"> <label for="optionSelect" class="col-sm-6 col-form-label"><b>옵션</b></label> <div class="col-sm-6" style="margin-left: -90px;"> <select type="text" class="form-control" name="value_code" id="optionSelect" value="{{ form.value_code }}"> <option value="none">옵션을 선택하세요.</option> {% for option in option_object %} {% if option.option_code.option_code.option_code == value.option_code %} {%if option.product_code == product %} <optgroup label="{{option.name}}"> {% for value in value_object %} {% if value.option_code.option_code == option.option_code %} {%if value.product_code == product %} <option data-price="{{value.extra_cost}}"value="{{value.value_code}}">{{value.name}} (+{{value.extra_cost}}원)</option> {% endif %} {% endif %} {% endfor %} {% endif %} {% endif %} {% endfor %} </optgroup> </select> </div> <div id="selectOptionList" style="margin-top:10px; margin-left: 20px; margin-bottom: -10px;"></div> </div> <script> $().ready(function() { $("#optionSelect").change(function() { … -
Django ModuleNotFoundError: No module named 'views'
In my Django Project market I created an app called main. In main I created urls.py main/urls.py: from django.urls import path import views url_patterns = [ path('home/', views.homepage, name='home'), ] main/views.py: from django.shortcuts import render, HttpResponse # Create your views here. def homepage(request): return HttpResponse("<h1> Hello World </h1>" ) market/urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('main.urls')) ] But when I try to run: Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Python38\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Python38\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Python38\lib\site-packages\django\core\management\base.py", line 419, in check all_issues = checks.run_checks( File "C:\Python38\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Python38\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Python38\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Python38\lib\site-packages\django\urls\resolvers.py", line 412, in check for pattern in self.url_patterns: File "C:\Python38\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python38\lib\site-packages\django\urls\resolvers.py", line 598, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Python38\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python38\lib\site-packages\django\urls\resolvers.py", line 591, in urlconf_module return import_module(self.urlconf_name) File "C:\Python38\lib\importlib\__init__.py", … -
Ajax in django doesnt work, no error and nothing happens
I wrote a django app that has articles and im trying to add a like functionality, I added the code in the bottom and nothing happens. No error just nothing in the database or the html code changes. Any idea what is the problem? The relevent part of the html/javascript code: <head> <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script> </head> <button id='like-button' color = 'black'> Like </button> <script type="text/javascript"> $('#like-button').click(function(){ var article_id = '{{ article.id }}'; var user_id = '{{ user.id }}'; var like_dislike = True; $.ajax( { type:"GET", url: "like-article-commm", data:{ article_id: article_id, user_id: user_id, like_dislike: like_dislike }, success: function( data ) { $('#like-button').css('color', 'blue'); } }) }); </script> The like-article-comm View: def Like_Article_View(request): if request.method == 'GET': article_id = int(request.GET['article_id']) likedarticle = Article.objects.get(id = article_id) user_liked_id = int(request.GET['user_id']) userliked = User.objects.get(id = user_liked_id) like_dislike_0 = request.GET['like_dislike'] like_object_list = Like_Article.objects.filter(article_liked = likedarticle, user_liked = userliked) if like_object_list.count() > 0: existing_like = like_object_list.filter() if existing_like.like_dislike == like_dislike_0: return HttpResponse('success') existing_like.like_dislike = like_dislike_0 existing_like.save() like_new_object= Like_Article(article_liked=likedarticle, user_liked=userliked, like_dislike=like_dislike_0) like_new_object.save() return HttpResponse('success') else: return HttpResponse("unsuccesful") urls.py file: from django.urls import path from . import views from .views import ArticleListView, ArticleDetailView, ArticleCreateView, ArticleUpdateView, ArticleDeleteView urlpatterns = [ path('', ArticleListView.as_view(), name="home-comm"), path('article/<int:pk>/', ArticleDetailView.as_view(), name="article-comm"), path('like_article/', views.Like_Article_View, name='like-article-commm'), … -
I want to save the pdf file from local server to online
I want to save the pdf file generated by weasyprint from the local server to online while my website is running on a local server in Django.. please help -
Celery auto reload Django
I am following ChillarAnand's example on how to reload Celery on change in my Django project, however it doesn't seem to close the previous Celery worker. On reload Celery raises the following error: [2021-08-11 10:42:30,216: WARNING/MainProcess] /Users/someuser/Documents/dev/backoffice/venv/lib/python3.8/site-packages/kombu/pidbox.py:72: UserWarning: A node named celery@someusers-iMac.local is already using this process mailbox! Maybe you forgot to shutdown the other node or did not do so properly? Or if you meant to start multiple nodes on the same host please make sure you give each node a unique node name! warnings.warn(W_PIDBOX_IN_USE.format(node=self)) My code in Django's management > commands celery_worker.py as follows: import shlex import subprocess from django.core.management.base import BaseCommand from django.utils import autoreload class Command(BaseCommand): def handle(self, *args, **options): autoreload.run_with_reloader(self._restart_celery) @classmethod def _restart_celery(cls): cls.run('pkill -f "celery worker"') cls.run('celery -A backoffice worker -B -l DEBUG') @staticmethod def run(cmd): subprocess.call(shlex.split(cmd)) I have tried the following 'Kill' command, which works fine when used in terminal, but when used in the commands script OSX raise an error - "kill: illegal process id: $(ps" kill -9 $(ps aux | grep celery | grep -v grep | awk '{print $2}' | tr '\n' ' ') > /dev/null 2>&1kill -9 $(ps aux | grep celery | grep -v grep | awk '{print … -
Django class based view, save in another model after CreateView
I have a create view (Loan_assetCreateView(generic.CreateView)) where I save if an asset is going to be loaned and when it will be returened in a model called Loan_asset(models.Model). Then I have the asset in a diffrent model Asset(model.Model). I would like to once I have saved my data in my Loan_assetCreateView(generic.CreateView) that is set the value in Asset.is_loaned to True. How can I do that? My models.py: class Asset(models.Model): # Relationships room = models.ForeignKey("asset_app.Room", on_delete=models.SET_NULL, blank=True, null=True) model_hardware = models.ForeignKey("asset_app.Model_hardware", on_delete=models.SET_NULL, blank=True, null=True) # Fields name = models.CharField(max_length=30) serial = models.CharField(max_length=30, unique=True, blank=True, null=True, default=None) mac_address = models.CharField(max_length=30, null=True, blank=True) purchased_date = models.DateField(null=True, blank=True) may_be_loaned = models.BooleanField(default=False, blank=True, null=True) is_loaned = models.BooleanField(default=False, blank=True, null=True) missing = models.BooleanField(default=False, blank=True, null=True) notes = HTMLField(default="") ip = models.CharField(max_length=90, null=True, blank=True) created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) class Loan_asset(models.Model): # Relationships asset = models.ForeignKey("asset_app.Asset", on_delete=models.SET_NULL, blank=True, null=True) loaner_type = models.ForeignKey("asset_app.Loaner_type", on_delete=models.SET_NULL, blank=True, null=True) location = models.ForeignKey("asset_app.Locations", on_delete=models.SET_NULL, blank=True, null=True) # Fields loaner_name = models.CharField(max_length=60) loaner_address = models.TextField(max_length=100, null=True, blank=True) loaner_telephone_number = models.CharField(max_length=30) loaner_email = models.EmailField() loaner_quicklink = models.URLField(null=True, blank=True) loan_date = models.DateField() return_date = models.DateField() notes = HTMLField(default="") returned = models.BooleanField(default=False, blank=True, null=True) created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) class …