Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django download return
simple question please, my POST in the views returns a json format dictionary nested_data = { 'name': cleaned_data3['theme_name'], 'visualStyles': { 'barChart': { '*': { 'general': [{ 'responsive': cleaned_data2['responsive'], 'keepLayerOrder': cleaned_data2['maintain_layer_order'] }], 'legend': [{ 'show': cleaned_data['show'], 'position': cleaned_data['position'], 'showTitle': cleaned_data['show_title'], 'labelColor': { 'solid': { 'color': '#666666' } }, 'fontFamily': cleaned_data['font'], 'fontSize': cleaned_data['font_size'] }], } } } } then I am returning the code formatted into json using: return JsonResponse(nested_data) This shows me the json rendered in the browser, but how do I download this return? In my index.html the submit button is rendering the return from the view, but I need to submit the forms and to download the content into .json file, something needs to be put into the href? <input type="submit" value="Submit"> <a href="{{ xxx }}" download>DOWNLOAD</a> -
Could there be any issues naming a Django model "Model"?
I am looking through a new client's code and they named one of their Django models "Model." Could this cause any issues since all models are considered models or no? -
Updating django "notes" section with ajax
I've looked at docs and watched videos and asked another question on stack overflow but just can't understand how to use ajax with my django project. Essentially I have a list of territory managers that are returned from a for loop (here's the models.py, views.py and detail.html showing that): models.py class TM(models.Model): #Change this to territory manager and delete database and recreate Name = models.CharField(max_length = 200,null=True) Cell = models.CharField(max_length= 200, null=True) EmailAddress = models.EmailField(null=True) Notes = models.CharField(max_length=500, null=True) Distributor = models.CharField(max_length=200,null=True) State = models.CharField(max_length=200,null=True) Brand = models.CharField(max_length=200,null=True) def __str__(self): try: if self.Distributor is not NullBooleanField: return self.Name + ' - ' + self.Distributor + ' - ' + self.State except TypeError: return self.Name views.py def detail(request): try: if request.method == 'POST': state = request.POST['state'] brand = request.POST['brand'] territory_manager = TM.objects.filter(State__icontains=state).filter(Brand__icontains=brand) return render(request,'homepage/detail.html', {'state': state, 'territory_manager':territory_manager}) else: state = request.POST['state'] brand = request.POST['brand'] return render(request,'homepage/detail.html', f"No Results for {state} or {brand}") except TM.DoesNotExist: raise Http404("Info Does Not Exist") table in detail.html <table class= "content-table"> <thead> <tr> <th>Name</th> <th>Distributor</th> <th>State</th> <th>Brand</th> <th>Cell</th> <th>Email</th> <th>Notes</th> <th></th> </tr> </thead> <tbody> <tr> {% for tm in territory_manager %} <td style="white-space:nowrap;">{{ tm.Name }}</td> <td style="white-space:nowrap;">{{ tm.Distributor }}</td> <td style="white-space:nowrap;">{{ tm.State }}</td> <td style="white-space:nowrap;">{{ tm.Brand }}</td> … -
Ajax Post Request isn´t working in django
I have a problem with django. I have researched so much on other questions but their answers don´t work for me. I need to send a base64 string of an image to my view so that i can store the string instead of the image in my database. So, I want to send data via ajax to my django view. Due to whatever reason, the form gets already submitted by django automatically and i tried to stop it, but then ajax isn´t firing too. I would really appreciate help because it already has cost me so much time. add.html <form method="post" enctype="multipart/form-data" onsubmit="submitdata()"> {% csrf_token %} <input type="text" name="dish" required id="id_dish" placeholder="Rezeptname"> <img ><input type="file" name="image" required="" id="id_image" accept="image/*"> <div class="image-upload"><img id="img_id" src="#" style="display:none; height: 100%; width: 100%;"> </div><button type="submit">Upload</button> </form> <script> function submitdata() { $.ajax({ type: "POST", contentType: "application/json", url: "/add", data: JSON.stringify({ "dish": "test", "image": dataurl, "recipe": document.getElementsByName("recipe")[0].value, "caption": document.getElementsByName("caption")[0].value }), dataType: "json", }); } </script> views.py @login_required(login_url="login") def add(response): if response.method == "POST": form = AddForm(response.POST, response.FILES) if form.is_valid(): print(response.POST) current_user = Client.objects.get(id=response.user.id) current_user.post_set.create(poster=response.user.username, dish=form.cleaned_data.get("dish"), image=response.POST.get("image"), caption=form.cleaned_data.get("caption"), recipe=form.cleaned_data.get("recipe")) messages.success(response, "You successfully added a post.") return redirect("home") else: form = AddForm() return render(response, "main/add.html", {"form":form}) forms.py class AddForm(forms.ModelForm): … -
django rest framework return processed image url saved
The image has been received and processed by Django rest framework and saved to postgres. I can view the file saved locally, how can I send the URL of the image location back? Here is my views class ImageViewSet(viewsets.ModelViewSet): queryset = Image.objects.all().order_by('-uploaded') serializer_class = ImageSerializer @api_view(['POST']) def analyze_image(request): image_uploaded = request.data['picture'] ....#some processing img_model = Image() new_image = BytesIO() processed_image.save(new_image , format='PNG') img_model.analyzed_picture.save("fileName", content=ContentFile(new_image.getvalue()), save=False) # Above image is saved succesfully and I can view it locally return Response(img_model.data, status=status.HTTP_200_OK) I get AttributeError: 'Image' object has no attribute 'data' How can I fix the return statement so it returns the saved object information? -
Django - Unit test object's delection does not work as expacted
For 2 of my models, Users and Groups, I have a view to delete objects. The code is almost the same for each of them, it works in the application but unit test have different results: it works for users, not for groups. Thanks in advance for your advises. Here are the unit tests: class TestAdmUsers(TestCase): def setUp(self): self.company = create_dummy_company("Société de test") self.user_staff = create_dummy_user(self.company, "staff", admin=True) self.usr11 = create_dummy_user(self.company, "user11") self.usr12 = create_dummy_user(self.company, "user12", admin=True) self.usr13 = create_dummy_user(self.company, "user13") self.client.force_login(self.user_staff.user) def test_adm_delete_user(self): test_usercomp_id = self.usr13.id usrcomp = UserComp.objects.get(user__username="user13") self.assertEqual(usrcomp.id, test_usercomp_id) url = reverse("polls:adm_delete_user", args=[self.company.comp_slug, test_usercomp_id]) response = self.client.get(url) self.assertEqual(response.status_code, 302) with self.assertRaises(User.DoesNotExist): User.objects.get(id=test_usercomp_id) with self.assertRaises(UserComp.DoesNotExist): UserComp.objects.get(id=test_usercomp_id) class TestAdmGroups(TestCase): def setUp(self): self.company = create_dummy_company("Société de test") self.user_staff = create_dummy_user(self.company, "staff", admin=True) self.usr11 = create_dummy_user(self.company, "user11") self.usr12 = create_dummy_user(self.company, "user12", admin=True) self.usr13 = create_dummy_user(self.company, "user13") self.usr14 = create_dummy_user(self.company, "user14") user_list = [self.usr11.id, self.usr12.id, self.usr13.id, self.usr14.id] users = UserComp.objects.filter(id__in=user_list) self.group1 = UserGroup.create_group({ "company": self.company, "group_name": "Groupe 1", "weight": 40, }, user_list=users) def test_adm_delete_group(self): test_group_id = self.group1.id grp = UserGroup.objects.get(group_name="Groupe 1") self.assertEqual(grp.id, test_group_id) url = reverse("polls:adm_delete_group", args=[self.company.comp_slug, test_group_id]) response = self.client.get(url) self.assertEqual(response.status_code, 302) with self.assertRaises(UserGroup.DoesNotExist): UserGroup.objects.get(id=test_group_id) The test runs fine for users, but I have this fali for groups: Traceback (most recent … -
How to export a database's data to a new one(python/mysql)
lets say I have an old database in mysql and i want to export all of its data to a new mysql database with python(or Django). How can I do that? consider that the old database might not have some fields of some tables of the new database(for example there is a table called "product" in the old database, we have the same table in the new database but with an extra field called 'address'. so the old data base doesnt have the field address but the new one does). I just want to transfer the data, tables already exist in the new database -
Django: Heroku Failing to launch, at=error code=H10 desc="App crashed" path="/"
When I try to deploy the project to Heroku, It gives the application error. I tried to go through the log file but I can't identify the problem correctly. This is the repository that I tried to push https://github.com/sachin96Boy/covid-predict any help is appreciated. Thanks -
I'm getting an error message when making migration to db in django
hello guys I'm doing a django tutorial and i missed a change the instructor did in models.py so i fix it but when trying to make the migration to the db it gives me a code that I don't understand or i don't know what to do, here is what it says Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py -
How to send email with cpanel in django
I'm trying to send email from a django app. Normally I use sendgrid but my client insists that there is no need for an extra service with Cpanel. Below are my settings after creating an email with cpanel according to this blog. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'mail.mydomain' EMAIL_PORT = 465 DEFAULT_FROM_EMAIL = 'email created as above' EMAIL_HOST_USER = 'email created as above' EMAIL_HOST_PASSWORD = 'the email's password' EMAIL_USE_TLS = True However, i get this error in development: gaierror at /contact-us/, [Errno -2] Name or service not known. Any suggestions are very welcome. -
Django on Google App Engine: how to connect to cloud database to run makemigrations?
I have been following this tutorial to create Django cloud app. I have been stuck on the 'Run the app on your local computer' part of the tutorial. Before running cloud_sql_proxy.exe command, I have created .env file and pasted its contents into Permissions on Google Cloud, so theoretically, after running set GOOGLE_CLOUD_PROJECT=PROJECT_ID, I could delete this .env file from repository as it would recognize it anyway. But for now, I left it. What is more, I activate env correctly in the project dir when I ran command in this location, gcloud sql instances describe INSTANCE_NAME it works OK and displays database info. Then, I have opened new Cloud SDK and ran command: cloud_sql_proxy.exe -instances="PROJECT_ID:REGION:INSTANCE_NAME"=tcp:5434. The result is: 2021/11/08 17:11:11 Listening on 127.0.0.1:5434 for PROJECT_ID:REGION:INSTANCE_NAME 2021/11/08 17:11:11 Ready for new connections 2021/11/08 17:11:11 Generated RSA key in 116.9931ms The reason behind why it is 5434 and not 5432 and 5433 as that these ports were busy. I must say that I have also downloaded postgresql and specified these: information. After running in env (Google SDK) respectively: set GOOGLE_CLOUD_PROJECT=PROJECT_ID set USE_CLOUD_SQL_AUTH_PROXY=true python manage.py makemigrations , this error occurs: C:\Users\User\Desktop\cloud\python-docs-samples\appengine\standard_python3\django\env\lib\site-packages\django\core\management\commands\makemigrations.py:105: RuntimeWarning: Got an error checking a consistent migration history performed for database connection … -
Django query, annotate a chain of related models
I have following schema with PostgreSQL. class Video(models.Model): title = models.CharField(max_length=255) created_at = models.DateTimeField() disabled = models.BooleanField(default=False) view_count = DecimalField(max_digits=10, decimal_places=0) class TopVideo(models.Model): videos = (Video, on_delete=models.CASCADE, primary_key=True) class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) video = models.ForeignKey(Video, related_name="comments", on_delete=models.CASCADE) The reason I have a TopVideo model is because I have millions of videos and querying them takes a long time on a cheap server, so I have a secondary model that is populated by a celery task, and flushes and re-populates on each run, which makes the homepage load time much faster. The task runs the query that you see next, and saves them into the TopVideo model. This way, the task may take long to run, but user doesn't have to wait for the expensive query anymore. Before having the TopVideo model, I ran this query for my homepage: videos = ( Video.objects.filter(created_at__range=[start, end]) .annotate(comment_count=Count("comments")) .exclude(disabled=True) .order_by("-view_count")[:100] ) This worked perfectly and I had access to "comment_count" in my template, where I could easily show the number of comments each video had. But now that I make this query: top_videos = ( TopVideo.objects.all().annotate(comment_count=Count("video__comments")) .select_related("video") .order_by("-video__view_count")[:100] ) and with a simple for-loop, videos = [] for video in top_videos: videos.append(video.video) … -
How to force a value when creating with django-rest-framework ModelViewSet?
I have an api where users can create different objects. If the user is part of the staff, he can create the object with all the values he wants. However, if the user is not part of the staff, I want to force the value of a particular field. I added the following code to a viewset that works well: @swagger_auto_schema(responses={201: CategoryProductSerializer}) def create(self, request, *args, **kwargs): if not self.request.user.is_staff: request.data['client']=request.user.profil.client.pk print(request.data) serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) def perform_create(self, serializer): serializer.save() How can I "generalize" this to all my modelviewsets? The important part of this create that must be common to all my viewsets is : if not self.request.user.is_staff: request.data['client']=request.user.profil.client.pk -
custom form error messages for too many images
I have a form that allows a user to upload bulk images. I Set a limit so the users can only upload a certain number of images. The code works but I use an exception, I want a custom error message in the template. From my research it seems that I need to use the clean method. However I cannot figure out how to use in in a function based view. How would I go about solving this issue. def createPostView(request): currentUser = request.user postForm = PostForm() if request.method == 'POST': postForm = PostForm(request.POST, request.FILES) if len(request.FILES.getlist('images')) > 3: raise Exception("Only three images allowed") else: if postForm.is_valid(): PostFormID = postForm.save(commit=False) PostFormID.author = request.user PostFormID.save() for f in request.FILES.getlist('images'): test = PostImagesForm(request.POST, request.FILES) if test.is_valid(): instance = test.save(commit=False) instance.post_id = PostFormID.id instance.images = f instance.save() return redirect('post-detail', PostFormID.pk) return render(request, 'blog/post_form.html', {'postForm': postForm, 'PostImagesForm':PostImagesForm}) -
Django Error: polls.Choice: (models.W042) Auto-created primary key
What should I do to fix this problem I am using vscode on Django 3.2 and I am currently following This project polls.Choice: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the PollsConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'. polls.Question: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the PollsConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'. -
How to update the one attribute of model once form is validated in Django?
I have a model class Tutor(models.Model): name = models.CharField(max_length=100) qualification = models.CharField(max_length=100) experience = models.CharField(max_length=200) tution_fee = models.CharField(max_length=100) about = models.CharField(max_length=1000) demo_classes_link = models.CharField(max_length=1000) contact_number = models.CharField(max_length=10) email_id = models.EmailField(null=True, blank=True) material = models.CharField(max_length=1000) status = models.BooleanField(null=True, blank=True) and a form class GeeksForm(forms.ModelForm): # specify the name of model to use class Meta: model = Tutor fields = "__all__" Now I have captured all the data using POST API form is validated. def registration(request) : form = GeeksForm(request.POST) # Check if the form is valid: if form.is_valid(): number = request.POST['contact_number'] print(number) r = requests.get('http://apilayer.net/api/validate?access_key=f29c72ac6f62b868e124651dc170a145&number=7042092067&country_code=+91&format=1', params=request.GET) if r.status_code == 200: form['status'] = 1 # I want to update this once is form is validated, django throws an error. form.save() return HttpResponse('Yay, it worked') currentID = form.auto_id print(currentID) # form = GeeksForm() else : print("Invalid") return render(request, 'Tutorform.html', {'form': form}) How do I update status parameter of model in django after form validation is successful ? -
Multiple Django variables in React
I am currently doing projct that includes Django and React. Post model in django models.py class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset()\ .filter(status='published') class Post(models.Model): STATUS = ( ('project', 'Project'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField( max_length=250, unique_for_date='publish') author = models.ForeignKey( User, on_delete=models.CASCADE, related_name='messages') 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=15, choices=STATUS, default='projekt') objects = models.Manager() published = PublishedManager() class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse("frontend.views.post_detail", kwargs={'year': self.publish.year, 'month': self.publish.month, 'day': self.publish.day, 'slug': self.publish.slug}) views.py def post_list(request): posts = Post.published.all() serializer = PostSerializer(posts, many=True) json_data = json.dumps(serializer.data) return render(request, 'frontend/index.html', {'posts': json_data}) def post_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) return render(request, 'frontend/index.html', {'post': post}) I want to get the 'posts' from post_list and 'post' from post_detail to index.html which is start point for React. index.html <!DOCTYPE html> <html lang="en"> <head> [..] <script> const posts = {{ posts|safe }}; const post = {{ post|safe }}; </script> <link rel="stylesheet" href="{% static "css/style.css" %}" type="text/css"> </head> <body> <div id="root"></div> <script src="{% static "frontend/main.js" %}"></script> </body> </html> The variables works perfectly fine when there's only one variable in script tag; … -
django rest framework return image url
I am trying to uplaod an image to the API and get the URL of the images back in response: Here is my views.py class ImageViewSet(viewsets.ModelViewSet): queryset = edited_image.objects.all() serializer_class = ImageSerializer @api_view(["POST"]) def manipulate_image(request): greenChannel, blueChannel= manip(request.data["picture"]) image = Image.objects.create(green=ContentFile(greenChannel.tobytes()), blue=ContentFile(blueChannel.tobytes()), ) return Response(data=image, status=status.HTTP_201_CREATED) TypeError: Object of type Image is not JSON serializable My model is: # Create your models here. class edited_image(models.Model): green= models.ImageField(upload_to="green_image", blank=True) blue= models.ImageField(upload_to="blue_image", blank=True) -
Django Graphene (GraphQL) Filter on ManyToMany
I am working on an application using Django. We've exposed the models using Graphene. We have the following models: class Agent(models.Model): id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) name = models.CharField( max_length=MAX_LENGTH, null=True, blank=True, help_text="Name of the agent" ) teams = models.ManyToManyField( 'Team', blank=True, help_text="The teams of which the user is part" ) class Team(models.Model): id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) name = models.CharField( max_length=MAX_LENGTH, help_text="Name of the team" ) Now I am trying to perform a filter on a ManyToMany field. But I can't seem to get it to work. I am trying to reproduce the following Django Query in GrapQL: teams = [ Team.objects.get(id="6d6d1d4d-c1b4-485a-9269-f7e9d06d862a"), Team.objects.get(id="7e082abf-584b-4858-b510-4c71fc295e2f"), ] agents = Agent.objects.filter(teams__in=teams).distinct() I tried to achieve this by enabling the 'in' filter on the node. class AgentNode(DjangoObjectType): class Meta: model = Agent filter_fields = { "teams": ["in"] } Then I tried to execute the following query, but that didn't work as expected: query getAllAgents{ allAgents(teams_In:["6d6d1d4d-c1b4-485a-9269-f7e9d06d862a, 7e082abf-584b-4858-b510-4c71fc295e2f"]) { id name teams { id name } } } This gives me the following error: { "errors": [ { "path": [ "allAgents" ], "message": "'list' object has no attribute 'split'", "locations": [ { "column": 3, "line": 2 } ] } ], "data": { "allAgents": null … -
Razorpay Django Integration with Callback URL (CSRF token missing or incorrect.)
I am trying to Class Based View with Razor Pay, Everything working Perfectly. But When i am POST data too same view it is giving error Forbidden (CSRF token missing or incorrect.): /buy-coin. I am having two question here How we can exempt CSRF Token for post method In Razorpay Javascript Code, can we add csrf token in callback url. Razorpay Python Integration Link - https://razorpay.com/docs/payment-gateway/server-integration/python/ View.py class BuyCoinPageView(LoginRequiredMixin, View): def get(self, request, *args, **kwargs): client = razorpay.Client(auth=("scretKey", "secretKey")) data = { "amount": 10000, "currency": "INR", "receipt": "order_rcptid_11" } payment = client.order.create(data=data) print('Razor Pay - ', payment['id']) return render(request, "pricing-page.html", {'payment': payment}) def post(self, request, *args, **kwargs): data = request.POST print(data) return render(request, "pricing-page.html") HTML FILE <a href="#" id="rzp-button1" class="btn-buy">Buy Now</a> <script src="https://checkout.razorpay.com/v1/checkout.js"></script> <script> var options = { "key": "rzp_test_hwAkAHZlKJdgee", // Enter the Key ID generated from the Dashboard "amount": "50000", // Amount is in currency subunits. Default currency is INR. Hence, 50000 refers to 50000 paise "currency": "INR", "name": "Acme Corp", "description": "Test Transaction", "image": "https://example.com/your_logo", "order_id": "{{payment.id}}", //This is a sample Order ID. Pass the `id` obtained in the response of Step 1 "callback_url": "{% url 'buy_coin' %}", "prefill": { "name": "Gaurav Kumar", "email": "gaurav.kumar@example.com", "contact": "9999999999" }, … -
DRF The serializer field might be named incorrectly and not match any attribute or key on the `str` instance
I am trying to make a multiple objects saving and i get the following error: AttributeError: Got AttributeError when attempting to get a value for field answer on serializer TestSerializer. The serializer field might be named incorrectly and not match any attribute or key on the str instance. I Checked the database , migrations are all correct. Below are my models , serializer and view. Model: class TestResponse(models.Model): id = models.AutoField(primary_key=True) answer = models.ForeignKey('Answer', on_delete=models.DO_NOTHING) View: @action(methods=['post'], detail=False) def create_multiple(self, request, *args, **kargs): serializer = self.get_serializer(data=request.data, many=True) serializer.is_valid(raise_exception=True) self.perform_create(serializer) return Response(serializer.data, status=status.HTTP_201_CREATED) Serializer: class TestResponseSerializer(serializers.ModelSerializer): class Meta: fields = ('id', 'answer') model = models.TestResponse Post body: [ { "answer": 1 }, { "answer": 2 } ] -
django.core.exceptions.ImproperlyConfigured: SQLite 3.9.0 or later is required (found 3.7.17) Error Observed in Apache Logs
I'm getting below error in apache error logs. ''' django.core.exceptions.ImproperlyConfigured: SQLite 3.9.0 or later is required (found 3.7.17) ''' I verified the sqlite3 version both in virtual environment and also in non virtual environment(standard). I can see the latest sqlite3 in both the python. ''' $ python3.7 Python 3.7.12 (default, Nov 8 2021, 09:02:58) [GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux Type "help", "copyright", "credits" or "license" for more information. from sqlite3 import dbapi2 as Database Database.sqlite_version_info (3, 36, 0) ''' Below is the error logs from apache web server. [Mon Nov 08 15:02:33.698244 2021] [wsgi:error] [pid 1459] [remote 192.168.0.105:62615] backend = load_backend(db['ENGINE']) [Mon Nov 08 15:02:33.698249 2021] [wsgi:error] [pid 1459] [remote 192.168.0.105:62615] File "/home/rafiq/myprojectenv/lib/python3.7/site-packages/django/db/utils.py", line 111, in load_backend [Mon Nov 08 15:02:33.698252 2021] [wsgi:error] [pid 1459] [remote 192.168.0.105:62615] return import_module('%s.base' % backend_name) [Mon Nov 08 15:02:33.698257 2021] [wsgi:error] [pid 1459] [remote 192.168.0.105:62615] File "/usr/local/lib/python3.7/importlib/__init__.py", line 127, in import_module [Mon Nov 08 15:02:33.698260 2021] [wsgi:error] [pid 1459] [remote 192.168.0.105:62615] return _bootstrap._gcd_import(name[level:], package, level) [Mon Nov 08 15:02:33.698265 2021] [wsgi:error] [pid 1459] [remote 192.168.0.105:62615] File "/home/rafiq/myprojectenv/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 73, in <module> [Mon Nov 08 15:02:33.698267 2021] [wsgi:error] [pid 1459] [remote 192.168.0.105:62615] check_sqlite_version() [Mon Nov 08 15:02:33.698273 2021] [wsgi:error] [pid 1459] [remote … -
How to get multiple fetch functions execute in order?
I created an IG like button where the number of like changes after a click. I added 2 fetch functions - one with PUT. I tried multiple ways but the results are same - the GET fetch is getting executed first. How can I prevent that? function liking(tweetid) { let l = document.querySelector('#numlikes-' + tweetid); fetch(`tweets/${tweetid}`, { method: 'PUT', body: JSON.stringify({ tweet_like: 1 }) }); fetch(`tweets/${tweetid}`) .then(response => response.json()) .then(post => { l.innerHTML = post.likes; }); } -
How to override delete method (generics class) in Django Rest Framework? [duplicate]
I am trying to override delete method in generics.RetrieveUpdateDestroyAPIView class using the followings code snippet. :- In views.py class ArtistView(generics.RetrieveUpdateDestroyAPIView): serializer_class = ArtistSerializer queryset = Users.objects.filter(user_type='artist') In serializers.py class ArtistProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ('profile_pic_url','cover_pic_url','full_name','genre','location') class ArtistSerializer(serializers.ModelSerializer): profiles = ArtistProfileSerializer(many=False) class Meta: model = Users fields = ['id','user_type', 'email', 'profiles','username'] def delete(self, instance, *arg, **kwargs): profile = instance.profiles profile.delete() In urls.py urlpatterns = [ path('all-artist/', views.ArtistListView.as_view()), path('all-artist/<int:pk>', views.ArtistView.as_view())] How can I do it? -
there is a way to use it managing the table Manytomany Filter_horizontal
I have the following model managing the intermediate table guia = models.ManyToManyField( Fisico, through= 'Planilla', blank = True, null = True ) I want to see it horizontally since admin.StackedInline it does not serve me for what I require