Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
redirecting to homepage after user submits a blog post?
I'm very new to using Django and coding in general. So I have figured out how to make the form submit to my database but now when it submits, it just brings you to the blank blog_post view and I'm not understanding how to redirect correctly. here is the views.py: from django.shortcuts import render, redirect from .models import post from django.views import generic, View from django.views.decorators.http import require_GET from django.http import HttpResponse, HttpResponseRedirect from .forms import PostForm # Views for post list class postslist(generic.ListView): model = post queryset = post.objects.filter(status=1).order_by('-created_on') template_name = 'home.html' paginate_by = 4 # view for individual post class postdetail(generic.DetailView): model = post template_name = "post.html" def blog_post(request): form = PostForm(request.POST or None) if request.method == "POST": if form.is_valid(): form.instance.user = request.user form.save() return redirect("blog:success") context = {'form': form, } return render(request, "create_post.html", context) def success(request): return HttpResponseRedirect("home.html") urls.py: from . import views from django.urls import path, include from .views import * urlpatterns = [ # home path('', views.postslist.as_view(), name='home'), # add post path('blog_post/', views.blog_post, name='blog_post'), # success for blog post path('success/', views.success, name='success'), # posts path('<slug:slug>/', views.postdetail.as_view(), name='post_detail'), ] I have tried a few variations of httpresponseredirect and redirect but i just cant wrap my head … -
After setting up ssl I cannot access my site django&apache
I created a demo for my domain www.example.com which only returns the index as you can see below. def index(request): return HttpResponse("This is a demo") urlpatterns = [ path('admin/', admin.site.urls), path("",index), ] I was able to access my site with domain name (I made the "A" dns record in godaddy site) and this was the <VirtualHost *:80> <VirtualHost *:80> ServerName loopingaround.com ServerAlias www.loopingaround.com ErrorLog /django-pro/site/logs/error.log CustomLog /django-pro/site/logs/access.log combine alias /static /django-pro/site/public/static <Directory /django-pro/site/public/static> Require all granted </Directory> alias /media /django-pro/site/public/media <Directory /django-pro/site/public/media> Require all granted </Directory> <Directory /django-pro/src/tutorial> Require all granted </Directory> WSGIDaemonProcess tutorial python-home=/django-pro/venv python-path=/django-pro/src/ WSGIProcessGroup tutorial WSGIScriptAlias / /django-pro/src/tutorial/wsgi.py </VirtualHost> then I used "ssl for free" for creating a ssl certificate for my site and set the files they provided. <VirtualHost *:80> ServerName loopingaround.com ServerAlias www.loopingaround.com Redirect / https://loopingaround.com </VirtualHost> <VirtualHost *:443> ServerName loopingaround.com ServerAlias www.loopingaround.com ErrorLog /django-pro/site/logs/error.log CustomLog /django-pro/site/logs/access.log combine SSLEngine on SSLCertificateFile /etc/ssl/certificate.crt SSLCertificateKeyFile /etc/ssl/private/private.key SSLCertificateChainFile /etc/ssl/ca_bundle.crt alias /static /django-pro/site/public/static <Directory /django-pro/site/public/static> Require all granted </Directory> alias /media /django-pro/site/public/media <Directory /django-pro/site/public/media> Require all granted </Directory> <Directory /django-pro/src/tutorial> Require all granted </Directory> WSGIDaemonProcess tutorial python-home=/django-pro/venv python-path=/django-pro/src/ WSGIProcessGroup tutorial WSGIScriptAlias / /django-pro/src/tutorial/wsgi.py </VirtualHost> now even if I revert the changes I made, I cannot access my site as … -
ModuleNotFoundError: No module named 'webapp.user'
at urls.py, I want to import webapp/user/views.py/ConfirmEmailView. so write code like this > from webapp.user.views import ConfirmEmailView and here is my Directory Structure.. but when I run this, error arises.. daesin_back-django-1 | Traceback (most recent call last): daesin_back-django-1 | File "manage.py", line 24, in <module> daesin_back-django-1 | main() daesin_back-django-1 | File "manage.py", line 19, in main daesin_back-django-1 | execute_from_command_line(sys.argv) daesin_back-django-1 | File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line daesin_back-django-1 | utility.execute() daesin_back-django-1 | File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 440, in execute daesin_back-django-1 | self.fetch_command(subcommand).run_from_argv(self.argv) daesin_back-django-1 | File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 402, in run_from_argv daesin_back-django-1 | self.execute(*args, **cmd_options) daesin_back-django-1 | File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 443, in execute daesin_back-django-1 | self.check() daesin_back-django-1 | File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 475, in check daesin_back-django-1 | all_issues = checks.run_checks( daesin_back-django-1 | File "/usr/local/lib/python3.8/site-packages/django/core/checks/registry.py", line 88, in run_checks daesin_back-django-1 | new_errors = check(app_configs=app_configs, databases=databases) daesin_back-django-1 | File "/usr/local/lib/python3.8/site-packages/django/core/checks/urls.py", line 14, in check_url_config daesin_back-django-1 | return check_resolver(resolver) daesin_back-django-1 | File "/usr/local/lib/python3.8/site-packages/django/core/checks/urls.py", line 24, in check_resolver daesin_back-django-1 | return check_method() daesin_back-django-1 | File "/usr/local/lib/python3.8/site-packages/django/urls/resolvers.py", line 494, in check daesin_back-django-1 | for pattern in self.url_patterns: daesin_back-django-1 | File "/usr/local/lib/python3.8/site-packages/django/utils/functional.py", line 57, in __get__ daesin_back-django-1 | res = instance.__dict__[self.name] = self.func(instance) daesin_back-django-1 | File "/usr/local/lib/python3.8/site-packages/django/urls/resolvers.py", line 715, in url_patterns daesin_back-django-1 | patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) daesin_back-django-1 … -
Getting information from a checkbox in Django
I have a problem getting data from a checkbox in my django project, I have this html instance: {% extends 'mailsinfo/layout.html' %} {% block title %} Add campaign page {% endblock %} {% block content %} <div class="parent"> <div class="child"> <form method="post"> {% csrf_token %} {{ form.name }}<br> {{ form.subject }}<br> {{ form.body }}<br> {{ form.user_guid }}<br> <span>{{ error }}</span> <button class="btn btn-success" type="submit">Save campaign</button> </form> </div> <div class="child"> <table id="table" data-height="540" class="table table-dark"> <thead> <tr> <th data-field="state" name = "selected" data-checkbox="true"></th> <th data-field="id">ID</th> <th data-field="email">Email</th> <th data-field="source">Source</th> <th data-field="created_at">Created at</th> <th data-field="modified_at">Modified at</th> </tr> </thead> </table> <script> var $table = $('#table') $(function() { var data = {{data|safe}} $table.bootstrapTable({data: data}) }) </script> </div> {% endblock %} Actions on this page are handled by this function: def add_campaign(request): error = '' if request.method == 'POST': formCanpaigns = CampaignsForm(request.POST) mails = request.POST.getlist('selected') print(mails) if formCanpaigns.is_valid(): formCanpaigns.save() return redirect('/') else: error = 'Form error' data = list(Emails.objects.values()) for i in data: i['created_at'] = i['created_at'].strftime("%m/%d/%Y, %H:%M:%S") i['modified_at'] = i['modified_at'].strftime("%m/%d/%Y, %H:%M:%S") i.pop("password") form = CampaignsForm() data_ = { 'form': form, 'error': error, 'data': data } return render(request, 'mailsinfo/add_campaign.html', data_) Can you tell me how I can get data from the table where the checkbox is … -
Secure way to use Google Maps autocomplete with Django and React
I am currently building my first React Native app with a Django backend and it needs Google Maps autocomplete. Since GMaps is not a topic I know, I decided to look for some tutorials and so far I am worried since everything I find leaves the GMaps API key in the React app for it to work. The tricky part is that GMAP autocomplete, to the difference of other APIs, has an input component of its own so sending the input value from another input component to the backend, using requests to call the GMAP autocomplete API from there then sending back the results and at last maybe rebuild a list component made of the results will only result in getting the possible choices but not the rest of the input as it should be + I think it would be extremely costly in terms of performance for a React Native app. Does anyone know the right way to send the input request to my backend (where my Key must stay), make the request from there, then finally have the autocomplete working on my frontend? Or any other solution that would not expose my API key? Many thanks -
User account activation email - protocol repeated twice (django)
On this scenario, I am looking for the user to receive an email to activate their account. This email will contain a link for them to click on for the activation. For some reason the protocol "https://" is repeated twice in the email. In this case the code renders: "https://https://sitename.com/..." However, I do not encounter this problem when I run the code on my local host. I am using Django, and deploying on Heroku (just in case it matters). Here is the code. I tried removing rewriting "protocol": 'https' if request.is_secure() else 'http' #to "protocol": '' if request.is_secure() else 'http ' but no success, the protocol is repeated twice. Template {% autoescape off %} Hi, Please click on the link below to confirm your registration: {{ protocol }}://{{ domain }}{% url 'activate' uidb64=uid token=token %} {% endautoescape %} views def activate(request, uidb64, token): User = get_user_model() try: uid = force_str(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except: user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() messages.success(request, "Thank you for your email confirmation. Now you can log in your account.") return redirect('home') else: messages.error(request,"Activation link is invalid") return redirect('home') def activateEmail(request, user, to_email): mail_subject = "Activate your … -
How to get the top rated products in the following case?
I'm using Django==3.2 and Django-rest-framework==3.12.4 . I have two modals with following names Product and ProductRating. As you can see below class Product(models.Model): user = models.ForeignKey(User,related_name='userprofile', on_delete=models.CASCADE) name = models.CharField(("name"), max_length=50,null=True, blank=True) price = models.IntegerField(_("price"),default=0) create_time = models.DateTimeField(_("Create time"), default=timezone.now) class ProductRating(models.Model): user = models.ForeignKey(User, verbose_name=_("user"), on_delete=models.CASCADE,null=True,blank=True) product = models.ForeignKey(Product, verbose_name=_("product"), on_delete=models.CASCADE) stars = models.IntegerField(_("stars"),default=0) is_remove = models.BooleanField(_("is_remove"),default=False) create_time = models.DateTimeField(_("Create time"), default=timezone.now) Now I want to get the top rated products. According to the average rating of each product. the product that has highest rating and most count of reviews should appear first in the query list. I have tried the following thing but that just gave me those products who has any rating element. as you can see below. def get_all_top_rated_projects(self): query = self.filter(productrating__isnull=False) print( query[0].productrating.object.all()) I know its quite tricky case. I have tried to do it by myself. But i'm unable to do that. Anyone expert You can help and pull me out from this situation. Many Thanks In Advance. -
virtualenv env bash: virtualenv: command not found
I have a problem each time I want to start my VM even after Installing on windows ` $ pip install virtualenv Collecting virtualenv Using cached virtualenv-20.16.6-py3-none-any.whl (8.8 MB) Requirement already satisfied: platformdirs<3,>=2.4 in c:\users\samib\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from virtualenv) (2.5.2) Requirement already satisfied: distlib<1,>=0.3.6 in c:\users\samib\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from virtualenv) (0.3.6) Requirement already satisfied: filelock<4,>=3.4.1 in c:\users\samib\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from virtualenv) (3.8.0) Installing collected packages: virtualenv WARNING: The script virtualenv.exe is installed in 'C:\Users\samib\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\Scripts' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. Successfully installed virtualenv-20.16.6 ` I have the error virtualenv env bash: virtualenv: command not found I tried to uninstall and install again but I have the same issue -
Django restframework convert json to model
I am new to Django and creating an API endpoint that will receive an incoming request, parse it, iterate the device list and make a request to another api. I have hardcoded the JSON structure but feel it may be better to user a serializer-type model to build the postbody, however, I have tried a few times and I am not successful or seeing how I would do this? Incoming Request Body: { "username" : "joe123", "devices" : ["iphone13", "laptop"] } The plan is to take this hardcoded example below and then make multiple requests to another API using the devices list requestBody = json.dumps(request.data) rawjson=json.loads(requestBody) print(rawjson['username']) print(rawjson['devices']) for alias in rawjson['devices']: postbody = { "alias": f"{alias}", "user-objects": [ { "name": f"{r['username']}]", "object-type": "byod" } ] } headers = { 'Authorization': 'Basic dGVzdDp0ZXN0Cg==' } response = requests.request("POST", url, headers=headers, data=postbody, verify=False) r_status = response.status_code .... ....etc So I created a serializers.py file and added the following: from rest_framework import serializers class UserObjectsSerializer(serializers.Serializer): username = serializers.CharField() object-type = serializers.CharField() class AliasSerializer(serializers.Serializer): alias = serializers.CharField() user-objects = UserObjectsSerializer(many=True) I am unsure how I correctly map the incoming username and devices list from the json object to this class-based object, so I can … -
python+django-unchecked checkbox returns "none"
I have an HTML form with checkbox: <form action="...function x" method="POST"> {% for x in box %} <tr class="cart_row_{{forloop.counter0}}"name="cart_row_{{forloop.counter0}}"> <td> <input class="form-check-input" type="checkbox"value="-1" checked="0" name="check_{{forloop.counter0}}"> <label class="form-check-label" for="check_{{forloop.counter0}}">Select item</label> </td> </tr> {% endfor %} <input type="submit" value="Checkout"> </form> When the checkbox is checked, everything works fine. When the checkbox isn't checked, django returns this error: TypeError at ...:'NoneType' object is not iterable The cause of the error is that the checkbox value is "none". How can I get over this? -
Django differ JSONField values between lists and objects
I am using django 3.2 with Postgres as DB. I have a model with JSONField: class MyModel(models.Model): data = models.JSONField(default=dict, blank=True) In database there are a lot of records in this table and some data have JSON values as object and others as lists: { "0:00:00 A": "text", "0:01:00 B": "text", "0:02:00 C": "text", } [ {"time": "0:00:00", "type": "A", "description": "text"}, {"time": "0:01:00", "type": "B", "description": "text"}, {"time": "0:02:00", "type": "C", "description": "text"}, ] I need to filter all records which has JSON values as objects. What I tried is to use has_key with time frame "0:00:00" : result = MyModel.objects.filter(data__has_key="0:00:00 A") But I really cant use it because I am not sure what the key with time frame look like completely. Any ideas how to filter JSONField values by object struct? -
How to unregister models from Django admin panel?
I'm trying to remove the default user, django_celery_ beat, etc..., models from the admin page. I tried to use unregister method but it giving an error from django_celery_beat.models import ( IntervalSchedule, CrontabSchedule, SolarSchedule, ClockedSchedule, PeriodicTask, ) admin.site.unregister(SolarSchedule) admin.site.unregister(ClockedSchedule) admin.site.unregister(PeriodicTask) admin.site.unregister(IntervalSchedule) admin.site.unregister(CrontabSchedule) Error: raise NotRegistered('The model %s is not registered' % model.name) django.contrib.admin.sites.NotRegistered: The model SolarSchedule is not registered def INSTALLED_APPS(self): rv = [ 'django.contrib.admin', 'django.contrib.auth', ... 'django_celery_beat', ] How can I solve that? -
drf-spectacular define request content type as 'application/x-www-form-urlencoded'
In drf-spectacular swagger, post method have 3 content types as below application/json application/x-www-form-urlencoded multipart/form-data Is there anyway to make "application/x-www-form-urlencoded" as default content type for my post method. @extend_schema( description='API authentication using login & password', # OpenApiRequestBody('content': "application/x-www-form-urlencoded") ) In extend_schema function, tried to add content type as form-urlencoded. but no luck. Thanks in advance -
How to fetch data by foreign key in Django serializers?
I'm stuck on fetching data with a related foreign key. I am doing some kind of validation in which the create method would be allowed depending on the requesterid to be POSTed. This is my userTable model: class userTable(models.Model): userid = models.UUIDField(primary_key=True, default = uuid.uuid4, editable=False) username = models.CharField(max_length=50, null=False, unique=True) userroleid = models.ForeignKey(roleTable, on_delete=models.CASCADE) def __str__(self): return self.username Another model is the requestTable class requestTable(models.Model): rid = models.AutoField(primary_key=True) requesterid = models.ForeignKey(userTable, on_delete=models.CASCADE) (...) This is my serializer: class RequestCreateSerializer(serializers.ModelSerializer): parts=PartSerializer(many=True) class Meta: model = requestTable fields = ['rid','requesterid', (...)] def create(self, instance, validated_data): if instance.requesterid.userroleid == 3: #how can i fetch my `requesterid` data? parts_data = validated_data.pop('parts') request = requestTable.objects.create(**validated_data) for part_data in parts_data: partsTable.objects.create(request=request, **part_data) return request raise ValidationError("Sorry! Your role has no permission to create a request.") Also, I'm quite confused if I should do validation in serializers, or views. If I do it in views, it just throws the ValidationError, and it doesn't seem to enter the if condition. For reference, here's my views: class RequestListCreateView(ListCreateAPIView): queryset = requestTable.objects.all() serializer_class = RequestCreateSerializer def create(self, request, *args, **kwargs): if request.data.get('requesterid__userroleid') == '3': write_serializer = RequestCreateSerializer(data=request.data) write_serializer.is_valid(raise_exception=True) self.perform_create(write_serializer) headers = self.get_success_headers(write_serializer.data) return Response({"Request ID": write_serializer.instance.requestid, "Parts ID": [p.partsid … -
400 Bad Request error in response to PUT/POST request
My project is to create a twitter style web application. I'm trying to implement a feature whereby a user can edit the content of their posts. Whenever I click 'save' to edit the post I receive: This is the context of my fetch request: const edit_div = document.createElement('div'); edit_div.innerHTML = `<p id="edit" style="color: blue;">Edit</p>`; edit_div.querySelector('#edit').addEventListener('click', () => { post_div.querySelector('#content').innerHTML = ` <textarea id="edited">${post.content}</textarea> `; edit_div.innerHTML = `<button id="change_post">Create change</button>`; edit_div.querySelector('#change_post').addEventListener('click', () => { const new_content = post_div.querySelector('#edited').value; fetch(`/posts/${post.id}`, { method: 'PUT', body: JSON.stringify({ content: new_content }) }) This is my URL in urls.py file path("posts/<int:post_id>", views.post, name="edit_post"), This is what I've created in views.py @csrf_exempt @login_required def post(request, post_id): edited_post = Post.objects.get(id=post_id) return JsonResponse(edited_post) Using POST instead of PUT gets me the same result. I have tried to clear browser cookies and and clear browser cache but to no avail. I have made very similar fetch calls but none of them had this issue. What have I got wrong? -
Not recognizing the user after I receive a request from React
After I send data in json I want to save the data, all the data is received fine, but it does not recognize the user, even though it is indeed connected according to the tests I did. i am getting this error: ValueError: Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x106fd12d0>>": "Vendors.user" must be a "User" instance. but the user is log in. view.py: @csrf_exempt def store_register(request): if request.method == 'POST': form = json.loads(request.body) print(request.user,form) vendor = Vendors.objects.create(user=request.user,store_name=form['storeName'],company_name=form['companyName'],img=form['storeImage'],business_email=form['businessEmail'],pay_pal=form['payPalEmail']) vendor.save() return JsonResponse({'test':'test'}) react: class RegisterBody extends React.Component { constructor (props) { super (props); this.state = { url: '' } } SendInput = () => { const storeName = document.getElementById('storeName').value const companyName = document.getElementById('companyName').value const storeImage = document.getElementById('storeImage').value const businessEmail = document.getElementById('businessEmail').value const payPalEmail = document.getElementById('payPalEmail').value this.setState({storeName:storeName,companyName:companyName,storeImage:storeImage,businessEmail:businessEmail,payPalEmail:payPalEmail}) fetch('/store-register', { method: 'POST', body: JSON.stringify({ 'storeName':storeName, 'companyName':companyName, 'storeImage':storeImage, 'businessEmail':businessEmail, 'payPalEmail':payPalEmail }), headers: { 'Content-type': 'application/json; charset=UTF-8' }, }) } render () { return ( <div> <label>Store Name</label> <input type={"text"} name={"storeName"} id={"storeName"}></input> <br></br> <label>Company Name</label> <input type={"text"} name={"companyName"} id={"companyName"}></input> <br></br> <label>Store Image</label> <input type={"file"} name={"storeImage"} id={"storeImage"}></input> <br></br> <label>Business Email</label> <input type={"email"} name={"businessEmail"} id={"businessEmail"}></input> <br></br> <label>Paypal Email</label> <input type={"email"} name={"payPalEmail"} id={"payPalEmail"}></input> <br></br> <button onClick={() => this.SendInput()}>Register</button> </div> ) } } export default RegisterBody -
How to generate a (html) file from a view in Django
I have a Django-driven website with several applications which are dynamically updated, but not too often, like "About", "Our services", etc. They have a two-level structure of pages, which I want to reflect in the top pop-up menu (see the picture). I could make it as a custom simple_tag called each time from the base.html template. It would generate a menu each time a user opens or reloads a page, but think it is very costly since the app structure is changed seldom (say, once a year). Instead, I want to like to generate an HTML code of the menu each time the app structure is updated. It will be stored as a statical HTML file, so my base.html will include the menu as a ready piece of code. Are there recipes on how to generate an HTML file from the views (CreateView, UpdateView, DeleteView)? -
read csv file from user input in django
ERROR : FileNotFoundError: [Errno 2] No such file or directory: '/media/tableConvert.com_v02pvt.csv' Hello there im trying to read a csv file in django backend where user upload and i dont want to save it to my DB so my best try was this : View : def view_submit_form(request): if request.method == 'POST': text = request.POST.get('smstext') csv_file = request.FILES['csv_file'] file_name = default_storage.save(csv_file.name, csv_file) file_url = default_storage.url(file_name) df = pd.read_csv(r'{}'.format(file_url)) return render(request, 'SubmitForm/form.html',) -
Django site fails with "bytes-like object is required, not 'str'"
I have a django site which I can login fine. However when I click one of the links "Scripts" it fails with the error builtins.TypeError TypeError: a bytes-like object is required, not 'str' . There were no recent changes on this site. Its using python36. The only thing I can think of its not liking the data its pulling from sql server but I cant pin point to it. Also as soon as I get the error, it crashes python manage.py runserver so I have to start it again. File "/opt/hds/base-3.6/base-3.6/lib/python3.6/site-packages/django/contrib/staticfiles/handlers.py", line 63, in __call__ return self.application(environ, start_response) File "/opt/hds/base-3.6/base-3.6/lib/python3.6/site-packages/django/core/handlers/wsgi.py", line 157, in __call__ response = self.get_response(request) File "/opt/hds/base-3.6/base-3.6/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in get_response response = self._middleware_chain(request) File "/opt/hds/base-3.6/base-3.6/lib/python3.6/site-packages/django/core/handlers/exception.py", line 43, in inner response = response_for_exception(request, exc) File "/opt/hds/base-3.6/base-3.6/lib/python3.6/site-packages/django/core/handlers/exception.py", line 93, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/opt/hds/base-3.6/base-3.6/lib/python3.6/site-packages/django/core/handlers/exception.py", line 139, in handle_uncaught_exception return debug.technical_500_response(request, *exc_info) File "/opt/hds/base-3.6/base-3.6/lib/python3.6/site-packages/werkzeug_debugger_runserver/management/commands/runserver.py", line 69, in null_technical_500_response six.reraise(exc_type, exc_value, tb) File "/opt/hds/base-3.6/base-3.6/lib/python3.6/site-packages/six.py", line 686, in reraise raise value File "/opt/hds/base-3.6/base-3.6/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/opt/hds/base-3.6/base-3.6/lib/python3.6/site-packages/django/utils/deprecation.py", line 140, in __call__ response = self.get_response(request) File "/opt/hds/base-3.6/base-3.6/lib/python3.6/site-packages/django/core/handlers/exception.py", line 43, in inner response = response_for_exception(request, exc) File "/opt/hds/base-3.6/base-3.6/lib/python3.6/site-packages/django/core/handlers/exception.py", line 93, in response_for_exception response = handle_uncaught_exception(request, … -
Django celery ModuleNotFoundError: No module named 'config'
I am doing a docker django project with celery in which the project's name for main container is main_config. the main_ms\main_config\celery.py looks like import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings') includedTasks=[] CeleryApp = Celery ('main_config', broker=settings.CELERY_BROKER_URL, backend=settings.CELERY_RESULT_BACKEND,include=includedTasks) CeleryApp.config_from_object('django.conf:settings', namespace='CELERY') CeleryApp.autodiscover_tasks() in docker-compose this containers is like: main_django_ser: container_name: main_django_container build: context: ./main_ms dockerfile: Dockerfile.main command: sh -c " celery -A main_config.celery worker --loglevel=info && python manage.py runserver 0.0.0.0:8000" by starting docker-compose gave the error below: main_django_container | Usage: celery [OPTIONS] COMMAND [ARGS]... main_django_container | Try 'celery --help' for help. main_django_container | main_django_container | Error: Invalid value for '-A' / '--app': main_django_container | Unable to load celery application. main_django_container | While trying to load the module main_config.celery the following error occurred: main_django_container | Traceback (most recent call last): main_django_container | File "/usr/local/lib/python3.9/site-packages/celery/bin/celery.py", line 57, in convertmain_django_container | return find_app(value) main_django_container | File "/usr/local/lib/python3.9/site-packages/celery/app/utils.py", line 384, in find_app main_django_container | sym = symbol_by_name(app, imp=imp) main_django_container | File "/usr/local/lib/python3.9/site-packages/kombu/utils/imports.py", line 56, in symbol_by_name main_django_container | module = imp(module_name, package=package, **kwargs) main_django_container | File "/usr/local/lib/python3.9/site-packages/celery/utils/imports.py", line 105, in import_from_cwd main_django_container | return imp(module, package=package) main_django_container | File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module main_django_container | return _bootstrap._gcd_import(name[level:], package, level) main_django_container … -
how to add playwright docker image to docker compose?
I am building Django app where I want to run Django and playwright images in 1 container in Docker Desktop (locally). Below you can see my docker-compose.yml file: version: '3.8' services: web: build: ./docker_playwright_test command: python manage.py runserver 0.0.0.0:8000 volumes: - ./docker_playwright_test/:/usr/src/docker_playwright_test/ ports: - 8000:8000 Django is running fine on my localhost but I am not sure how to add Playwright image to docker-compose file? Any help or tip will be appreciated. -
Django migration failed due to lack of memory. Query can't be killed
I deleted a column in a large table from a django migration. Due to lack of memory, the migration failed and the database restarted. (Managed database digital ocean mysql v8) After the database restarts, the drop column query runs again, and every time I kill the query through tableplus (mysql), the query restarts again. Meaning that my database runs out of memory every 15 minutes (I was in the process of deleting unnecessary data to free up memory) and restarts again. How can I kill this query for good? -
Django rest framework : custom object permissions doesn't work
My problem is very simple : I'm trying to create some custom permissions for my django rest API. This is my code (permission.py) : class UserPermissions(permissions.BasePermission): def has_object_permission(self, request, view, obj): return obj == request.user I just want that the users can only get, delete and update their own account. The problem is that I think my code is not read by Django. I have try to always return false (without any condition) and it does nothing. I have also try to print some debug message at the beginning of the file and it's does nothing. (My file permissions.py is at the root of my application) -
ImportError: cannot import name 'ParamSpec' from 'typing_extensions' when using Django websockets with channels and twisted libraries
We did not update any lib or new lib added. During deployment of Django web application, got the following error: Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/celery/fixups/django.py", line 118, in django_setup django.setup() File "/usr/local/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.7/site-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/usr/local/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/usr/local/lib/python3.7/site-packages/channels/apps.py", line 4, in <module> import daphne.server File "/usr/local/lib/python3.7/site-packages/daphne/server.py", line 5, in <module> from twisted.internet import asyncioreactor # isort:skip File "/usr/local/lib/python3.7/site-packages/twisted/internet/asyncioreactor.py", line 19, in <module> from twisted.internet.posixbase import ( File "/usr/local/lib/python3.7/site-packages/twisted/internet/posixbase.py", line 16, in <module> from twisted.internet import error, tcp, udp File "/usr/local/lib/python3.7/site-packages/twisted/internet/tcp.py", line 99, in <module> from twisted.internet import abstract, address, base, error, fdesc, main File "/usr/local/lib/python3.7/site-packages/twisted/internet/base.py", line 34, in <module> from twisted.internet import abstract, defer, error, fdesc, main, threads File "/usr/local/lib/python3.7/site-packages/twisted/internet/defer.py", line 42, in <module> from typing_extensions import Literal, ParamSpec, Protocol ImportError: cannot import name 'ParamSpec' from 'typing_extensions' … -
Django rest framework send form data
I have to build a form page with multiple image uploads using CRUD functions that I made. On submit the page should not reload so I'm using ajax to make the request. The serializer keeps throwing an error 400 (Bad request). It might be that FormData stringify some values that shouldn't, bud serializer won't let me add an item. Please help, I'm second day on googling different aproaches to do it and none of them worked. views.py @api_view(['GET']) def index(request): imageform = ImageForm() form = CreateShopItemForm() return render(request, 'main/index.html', {"form": form, "imageform": imageform}) @api_view(['POST']) def create_item(request): shop_item = ShopItemSerializer(data=request.data) print(request.data) if shop_item.is_valid(raise_exception=True): shop_item.save() print('success') return Response(shop_item.data) else: print("invalid") return Response(status=status.HTTP_404_NOT_FOUND) models.py class ShopItems(models.Model): item_name = models.CharField(max_length=100, null=False, blank=False) item_price = models.FloatField(null=False) item_author = models.CharField(max_length=100, null=False, blank=False) date = models.DateField(auto_now_add=True, editable=False) class Image(models.Model): shop_item = models.ForeignKey(ShopItems, on_delete=models.CASCADE, related_name="images") image = models.ImageField() serializers.py class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = ['image',] class ShopItemSerializer(serializers.ModelSerializer): images = ImageSerializer(many=True) def create(self, validated_data): images_data = validated_data.pop("images") shop_item = ShopItems.objects.create(validated_data) for image_data in images_data: Image.objects.create(shop_item=shop_item, song=image_data) return shop_item class Meta: model = ShopItems fields = [ 'item_name', 'item_price', 'item_author', 'date', 'images', ] script.js $("#addItemForm").on("submit", function (e) { e.preventDefault(); let data = new FormData($(this)[0]); $.ajax({ url: …