Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to solve the djongo.exceptions.SQLDecodeError: while trying to run the migrate command
I am creating a DjangoRestful app that uses SimpleJWT for authentication. When I try to add the Blacklist app and make migrations. i.e: py manage.py migrate as suggested in the documentation, I get the error below: Operations to perform: Apply all migrations: accounts, admin, auth, contenttypes, main, sessions, token_blacklist Running migrations: Applying token_blacklist.0008_migrate_to_bigautofield...Not implemented alter command for SQL ALTER TABLE "token_blacklist_blacklistedtoken" ALTER COLUMN "id" TYPE long Traceback (most recent call last): File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\djongo\cursor.py", line 51, in execute self.result = Query( File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\djongo\sql2mongo\query.py", line 784, in __init__ self._query = self.parse() File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\djongo\sql2mongo\query.py", line 876, in parse raise e File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\djongo\sql2mongo\query.py", line 857, in parse return handler(self, statement) File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\djongo\sql2mongo\query.py", line 889, in _alter query = AlterQuery(self.db, self.connection_properties, sm, self._params) File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\djongo\sql2mongo\query.py", line 425, in __init__ super().__init__(*args) File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\djongo\sql2mongo\query.py", line 84, in __init__ super().__init__(*args) File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\djongo\sql2mongo\query.py", line 62, in __init__ self.parse() File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\djongo\sql2mongo\query.py", line 441, in parse self._alter(statement) File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\djongo\sql2mongo\query.py", line 500, in _alter raise SQLDecodeError(f'Unknown token: {tok}') djongo.exceptions.SQLDecodeError: Keyword: Unknown token: TYPE Sub SQL: None FAILED SQL: ('ALTER TABLE "token_blacklist_blacklistedtoken" ALTER COLUMN "id" TYPE long',) Params: ([],) Version: 1.3.6 The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\django\db\backends\utils.py", line 85, in _execute … -
Combining two different querysets with conditions
I have two different models: class Material(models.Model): line = models.ForeignKey('Line') code = models.ForeignKey('Code') quantity = models.FloatField() class Inventory(models.Model): code = models.ForeignKey('Code') .... I'm trying to get a sum of quantity field for each row in Inventory, and also trying to append the related line fields with it. This is what I have: line = Material.objects.all().values('code','line__line_id').annotate(Sum('quantity')) # This gives me the SUM of quantity as required, output: # <QuerySet [{'code': 'abc', 'line__line_id': 134, 'quantity__sum': 15.0}, # {'code': 'abcd', 'line__line_id': 134, 'quantity__sum': 5.0}]> query_set = Inventory.objects.all().annotate(line=Value(F('line__line__line_id'), output_field=CharField())).order_by('code') filter = self.filterset_class(self.request.GET, query_set) In the query_set, I am getting this line annotation as a literal string "F('line__line__line_id')". How can I make it so query_set has values filtered as: WHERE Inventory.code == Material.code? Basically I want to combine the first queryset with the second one, where the code is the same in both querysets. I do not want to use chain() method as I need it to be a QuerySet object so I can use the FilterSet() from django-filters. -
add tax value 0.17 to database when checkbox checked
I'm working on customer form, I just want that if checked box is checked add 0.17 to database field named tax <input type="checkbox" id="tax" name="tax"> <label for="tax">Included Tax</label> view.py if form.is_valid(): form.save() -
Getting "Uncaught (in promise) TypeError: Failed to fetch" in local server (ReactJS)
Description: I have a ReactJS website which I'm currently working on. There's a LoginPage in which I'm sending a POST request with Axios to the backend (Django). I have set CORS_ALLOW_ALL_ORIGINS = True and website works just fine on the computer with no error or warning logs. Problem: When I try to test it on a android phone in the same network (I use vite and I've set everything for allowing connections through local network) I get "Uncaught (in promise) TypeError: Failed to fetch" error. It was a pain in the a$$ to actually see what was the console log in android but by using some third party apps I managed to find out that was the eror log. Expected result: As I set CORS to be allowed from any host and both backend and frontend servers are running and allowing local network connections there shouldn't be such error. Technologies used: ReactJS 17.0.2, Vite 2.9.9, React router dom 6.3.0, Django 4.0.6. Code snippets: LoginPage.jsx import * as React from "react"; import Avatar from "@mui/material/Avatar"; import Button from "@mui/material/Button"; import CssBaseline from "@mui/material/CssBaseline"; import TextField from "@mui/material/TextField"; import FormControlLabel from "@mui/material/FormControlLabel"; import Checkbox from "@mui/material/Checkbox"; import Link from "@mui/material/Link"; import Grid … -
How to know a value for field already exists and it was deleted?
How can we know that a value in field already exists however it does not exists in the table right now?(because we delete the field) e.g. We have a table that has field with name "title". we had value "x" in this "title" field and right now it does not exists and we deleted the value "x" value. So my question is, how can we know that? -
Django-Oscar - Modelling product classes with 2 main attributes each having different sub-attributes
I am working on an online store for a jewellery brand using Django-Oscar. We have 6 product types (Rings, Earrings etc.), each of which has been defined as a Product Class. All of these product classes have 2 common attribute types (Metal Type and Primary Gemstone Type) each of which take a collection of values. Depending on the values they take (eg. Diamond, Ruby etc. for Gemstone Type), they have different sub-attributes (eg. Carat, Clarity, Origin etc. for Diamond). Also, there are attributes (such as Dimensions, Weight etc.) which are common to all product classes. To model these attributes, I am thinking of customising the Django-Oscar framework as follows: Alter the AbstractProduct model to include two fields: metal and primary-gemstone such that every product instance has these two fields To vary attributes depending on the selection for metal and primary-gemstone, create two models Metal and Gemstone comprising of the possible types of metals and gemstones as fields Create a MetalAttribute model and a GemstoneAttribute model with metal, gemstone (PK from Metal and Gemstone models) and attribute-name (eg., for Diamond gemstone type, attribute names could be carat, cut etc.) fields For the possible values of each attribute for each metal/ gemstone, … -
Django data transfer from MySQL To PostgreSQL loaddata command error
When I am run the command for load data from old database of mysql to new database of postgresql get below error how to solve this? Traceback (most recent call last): File "E:\Sreeshanth\Django-projects\Marzomilan\Marzomilan\marzomilanenv\lib\site-packages\django\core\serializers\json.py", line 69, in Deserializer objects = json.loads(stream_or_string) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\json_init_.py", line 346, in loads return _default_decoder.decode(s) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\json\decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\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 "E:\Sreeshanth\Django-projects\Marzomilan\Marzomilan\marzomilan\manage.py", line 22, in main() File "E:\Sreeshanth\Django-projects\Marzomilan\Marzomilan\marzomilan\manage.py", line 18, in main execute_from_command_line(sys.argv) File "E:\Sreeshanth\Django-projects\Marzomilan\Marzomilan\marzomilanenv\lib\site-packages\django\core\management_init_.py", line 425, in execute_from_command_line utility.execute() File "E:\Sreeshanth\Django-projects\Marzomilan\Marzomilan\marzomilanenv\lib\site-packages\django\core\management_init_.py", line 419, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "E:\Sreeshanth\Django-projects\Marzomilan\Marzomilan\marzomilanenv\lib\site-packages\django\core\management\base.py", line 373, in run_from_argv self.execute(*args, **cmd_options) File "E:\Sreeshanth\Django-projects\Marzomilan\Marzomilan\marzomilanenv\lib\site-packages\django\core\management\base.py", line 417, in execute output = self.handle(*args, **options) File "E:\Sreeshanth\Django-projects\Marzomilan\Marzomilan\marzomilanenv\lib\site-packages\django\core\management\commands\loaddata.py", line 78, in handle self.loaddata(fixture_labels) File "E:\Sreeshanth\Django-projects\Marzomilan\Marzomilan\marzomilanenv\lib\site-packages\django\core\management\commands\loaddata.py", line 138, in loaddata self.load_label(fixture_label) File "E:\Sreeshanth\Django-projects\Marzomilan\Marzomilan\marzomilanenv\lib\site-packages\django\core\management\commands\loaddata.py", line 214, in load_label for obj in objects: File "E:\Sreeshanth\Django-projects\Marzomilan\Marzomilan\marzomilanenv\lib\site-packages\django\core\serializers\json.py", line 74, in Deserializer raise DeserializationError() from exc django.core.serializers.base.DeserializationError: Problem installing fixture 'E:\Sreeshanth\Django-projects\Marzomilan\Marzomilan\marzomilan\alldata.json': -
How to show only objects those are not selected in Django admin panel referred by Foreign Key?
I have following models : class Article(models.Model): title = models.CharField(max_length=150, null=True, blank=True) class Product(models.Model): name = models.CharField(max_length=150, null=True, blank=True) class ArticleProduct(models.Model): class Meta: unique_together = ('article', 'product') article = models.ForeignKey(Article, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) In admin.py : class ArticleProductIngredientInline(admin.StackedInline): model = ArticleProduct autocomplete_fields = ['product'] extra = 0 class ArticleAdmin(admin.ModelAdmin): inlines = [ArticleProductIngredientInline] search_fields = ['category', ] class Meta: model = Article @admin.register(ArticleProduct) class ArticleProductAdminModel(admin.ModelAdmin): autocomplete_fields = ['product', 'article'] class ProductAdminModel(admin.ModelAdmin): search_fields = ['product', ] admin.site.register(Product, ProductAdminModel) admin.site.register(Article, ArticleAdmin) I want that, In particular article when I add some product, it should not show again in while adding second product. Is there any way to it ? -
Cannot iterate zipped list in csv writerow()
I tried to generate csv file from zipped list consists of 1 Object and 3 int lists items = zip(object, list1, list2, list3) I looped the zipped list as follows but when I tried download the csv, there are no data: for object, list1, list2, list3 in items: writer.writerow([object.name, object.department, object.section, list1, list2, list3]) I checked if the data cannot be read or missing by using the segment code below, however it can properly print all the data: for object, list1, list2, list3 in items: print(str(object.name) + ": " + str(list1) + "/" + str(list2) + "/" + str(list3)) I'm not sure where's the part went wrong here as it doesn't print any error message. -
How to include CSRF token in the HTTP header of a GraphQL query with aiohttp and Django?
I'm trying to perform GraphQL mutation between two 2 Django projects, one has the gql client using aiohttp transport, and the other has the graphene server. The mutation works fine when django.middleware.csrf.CsrfViewMiddleware is deactivated, but when it is enabled the server throws an error Forbidden (CSRF cookie not set.): /graphql. At the client side, how can I fetch a CSRF token from the server and include it in the HTTP header ? Client side # Select your transport with a defined url endpoint transport = AIOHTTPTransport(url="http://5.22.220.233:8000/graphql", headers={"Authorization": "CSRF_TOKEN_HERE"} ) # Create a GraphQL client using the defined transport client = Client(transport=transport, fetch_schema_from_transport=True) # Provide a GraphQL query query = gql( """ mutation ... """) -
How to give images to right of the the html Table
I have made a Django website and want to display my result like at the top there is a small form.Under that in the left there is a table and i want to add to images and another column in the right if the table. I have made a design to explain better - enter image description here Now I have written the code for the form 1 and table. I will write the backend code too .I want to know how will I write html for the images and form 2 as they are in right of the table.As soon as write any html code it comes under the table. Anyone can help to add pics and form2 on the right of the table. my html code till now is- *{% extends 'login/basic.html' %} {% block title %}Approval of count{% endblock title %} {% block body %} <!-- <div class="container my-5 px-2"> --> <form action="/approval" method="post">{% csrf_token %} <!-- <div class="container" > <div class="form-group mx-5 my-3"> <div class="form-group mx-5 my-3"> <label class="my-3" for="date">Date</label> <input type="date" id="date" name="date"> </div> <label class="form-group mx-5 my-3" for="servers">Choose the server from - {{serverLst}}</label> <div class="form-group mx-5 my-3"> <select name="serverName" id="forserver" size="4" multiple> {% for … -
django media audio currentTime reseting to 0
I'm trying to make a audiobook website with django(3.2.13). But when I try to go back and forth. The currentTime of the audio goes back to 0. I have tryed it in side of console too. It's weird because when the audio file is small it work's!(When I refesh) But if the file is Big It doesn't work. All of the audios are work's good if I don't change the currentTime of the audio. What could be the problem? #djangotemplate <audio class="playing-audio" src="{{ audio.audios.url }}"></audio> #views.py class AudioDetailView(DetailView): model = Audio template_name = "audios/audio_detail.html" pk_url_kwarg = "audio_id" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) audio_id = self.kwargs.get("audio_id") audio = Audio.objects.get(id=audio_id) context["img_url"] = f"/static/img/{audio.category.title}.png" return context -
How can I redirect in the quick_view page after deleting feedback?
My motive is that I want to redirect quick_view.html after deleting particular feedback on a particular product. How can I do it? views.py: def quick_view(request, quick_view_id): quick_view = get_object_or_404(Products, pk=quick_view_id) context = { "quick_view":quick_view, } return render(request, 'quickVIEW_item.html', context) def feedBack(request,quick_view_id): quick_view = get_object_or_404(Products, pk=quick_view_id) if request.method == "POST" and request.user.is_authenticated: try: ProductREVIEWS.objects.create( user=request.user, product=quick_view, feedBACK=request.POST.get('feedBACK'), ) return redirect('quick_view', quick_view_id) except: return redirect('quick_view', quick_view_id) else: return redirect('quick_view', quick_view_id) After deleting the particular feedback, I want to redirect to the quick_view page of that particular product. Now shows below error: def DeleteFeedback(request,id,quick_view_id): ProductREVIEWS.objects.get(pk=id).delete() messages.success(request,"Successfully your feedback deleted.") return redirect('quick_view', quick_view_id) urls.py: path('quick_view/<int:quick_view_id>/', views.quick_view, name="quick_view"), path("feedBack/<int:quick_view_id>/", views.feedBack, name="feedBack"), path("DeleteFeedback/<int:id>/", views.DeleteFeedback, name="DeleteFeedback") error: TypeError at /DeleteFeedback/22/ DeleteFeedback() missing 1 required positional argument: 'quick_view_id' Request Method: GET Request URL: http://127.0.0.1:8000/DeleteFeedback/22/ Django Version: 4.0.4 Exception Type: TypeError Exception Value: DeleteFeedback() missing 1 required positional argument: 'quick_view_id' Exception Location: D:\1_WebDevelopment\17_Ecomerce Website\ecomerce site\env\lib\site-packages\django\core\handlers\base.py, line 197, in _get_response Python Executable: D:\1_WebDevelopment\17_Ecomerce Website\ecomerce site\env\Scripts\python.exe Python Version: 3.9.5 Python Path: ['D:\\1_WebDevelopment\\17_Ecomerce Website\\ecomerce site', 'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39\\python39.zip', 'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39\\DLLs', 'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39\\lib', 'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39', 'D:\\1_WebDevelopment\\17_Ecomerce Website\\ecomerce site\\env', 'D:\\1_WebDevelopment\\17_Ecomerce Website\\ecomerce ' 'site\\env\\lib\\site-packages'] Server time: Sat, 16 Jul 2022 05:49:50 +0000 -
Ajax success event not working in Django templates
Hello I am using Ajax to POST method inside Django template on modal submit $submitButton.click(function(event) { event.preventDefault(); $submitButton.addClass('disabled').prop('disabled', true); $error.prop('hidden', true); if (!$reasonField.val()) { handle_error(`{% trans "Entering a reason is mandatory!" %}`); return; } const reason = $reasonField.val(); $.ajax({ type: 'POST', url: `/staffing/midterm_contract/${reservation_id}/ignore/`, dataType: 'text', data: { comment: reason, }, headers: { 'X-CSRFToken': "{{ csrf_token }}", }, success: function(data) { console.log("Test") if (data) { console.log("Success") close() } else { handle_error(data.message) } }, error: function(jqXHR, textStatus, errorThrown) { handle_error(errorThrown); }, }); }); views.py class IgnoreMidtermContract(SupportUserRequiredMixin, UserPassesAllTestsMixin, View): user_tests = (UserTests.is_support_reservation, ) def dispatch(self, request, *args, **kwargs): self.reservation = get_object_or_404(Reservation, pk=kwargs['pk']) self.ignore_midterm_contract_reason = request.POST.get('comment', None) return super().dispatch(request, *args, **kwargs) def post(self, request, *args, **kwargs): self.reservation.ignore_midterm_contract_reason = self.ignore_midterm_contract_reason self.reservation.midterm_contract_ignored_at = timezone.now() self.reservation.midterm_contract_ignored_by = self.request.user self.reservation.midterm_contract_is_ignored = True self.reservation.save() return JsonResponse({'success': True}) success event inside Ajax POST method not working and not showing any error I tries with many was that was suggested other this kind of questions but still not working I tried to remove dataType: 'text', still not working Is there anything wrong or something add or remove? -
how to count the top_topics based on number of groups created on that topic in django?
I have such models where topic is related with room as shown in code. How can i count the top_topics as i have counted in top_groups. I want to count top_topics based on number of group created on that topic. I hope you get what i mean. Models.py class Topic(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Room(models.Model): admin = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) topic = models.ForeignKey(Topic, on_delete=models.SET_NULL, null=True) group_photo = models.ImageField(null=True, upload_to = 'images/', default='avatar.svg') name = models.CharField(unique=True, max_length=100) description = models.TextField(null=True, blank=True) members = models.ManyToManyField(User, related_name='members', blank=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created'] def __str__(self): return self.name Views.py def home(request): q = request.GET.get('q') if request.GET.get('q') != None else '' groups = Room.objects.filter(Q(topic__name__icontains=q)| Q(name__icontains=q) | Q(description__icontains=q) ) top_groups = Room.objects.alias( num_members = Count('members') ).order_by('-num_members')[:5] group_count = groups.count() topics = Topic.objects.all()[:5] context = {'groups':groups, 'group_count':group_count, 'topics':topics, 'top_groups':top_groups} return render(request, 'base/home.html', context) I am basically confused in relationship. what can be the way i can access Room from Topic? Please help !!!! -
How to add comma separated values in Django Admin
I have these two models, Category, and Subcategory. They look like this: class Category(models.Model): name = models.CharField(max_length=100) class Subcategory(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) name = models.CharField(max_length=100) So far, this all works great! I'm creating all the starter categories and subcategories for my projects and only have about 15 categories, but each category may wind up having tens of subcategories under them... What I need is a way to be able to copy and paste a ton of subcategory values into the admin form via a comma separated list, and create multiple new objects all at once, all with the same category as their foreign key. This will save me hundreds of clicks. How can this be accomplished? -
two (2) django applications on same vps server
I have two django applications deployed on the same server. I wanted to know if the two applications can coexist together without causing problems when the server handles requests with nginx and gunicorn . -
How to limit results with annotate and prefetch_related in django?
I'm have a django query with annotate and prefetch_related. all_questions = Question.objects.all().annotate(is_complete=Case( When( pk__in=completed_questions.values('pk'), then=Value(True) ), default=Value(False), output_field=BooleanField()), votes_difference=Count('like')-Count('unlike'), ).order_by('votes_difference').prefetch_related('tags') I want to limit the result to, let's say 100 objects. I tried this query, all_questions = Question.objects.all().annotate(is_complete=Case( When( pk__in=completed_questions.values('pk'), then=Value(True) ), default=Value(False), output_field=BooleanField()), votes_difference=Count('like')-Count('unlike'), ).order_by('votes_difference')[100].prefetch_related('tags') I got this error message 'Question' object has no attribute 'prefetch_related' I checked the official documentation but can't seem to find any example related to it. Is it possible to do so? -
How to send the value of select while onchange in django?
<main> <section class="topbar"> <select name="category" id="category" onchange="location.href='{% url 'searchbycategory' this.value %}'"> <option value="none">All category</option> <option value="book">Books</option> <option value="notes">Notes</option> <option value="fur">Furniture</option> <option value="draw">Drawing tools</option> <option value="others">Others</option> </select> </section> is there something like this.value to send the current selected value this is my path in url.py: path('searchbycategory/str:category',views.searchbycategory,name="searchbycategory") -
Google cloud and wagtail getting database error on deployed website
I'm deploying django wagtail website on google cloud successfully, but I'm getting: "settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details." error. I even tried hardcoding database values in settings.py like this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'url to sql stuff', 'USER': 'user I register', 'PASSWORD': "my password", 'PORT': '8080', 'HOST': "127.0.0.1" } } I can confirm values are correct and database exists on cloud. Still getting the same error. What should I do? -
How can I implement update and delete in django view?
I am creating a movie review website. In it, I want to be able to allow a User to make one comment on one movie and then Update or Delete that comment. But I am only able to implement POST right now. How do I change the view, html or model? Questions to ask How do I go from here to keep my comments visible so that if one user comments on one movie, I can't comment on it? How can I keep the comments posted by a user at the top of the comment list so that they can be updated and deleted? An example of what we would like to implement is Rotten Tomatoes. class Comment_movie(models.Model): comment = models.TextField(max_length=1000) stars = models.FloatField( blank=False, null=False, default=0, validators=[MinValueValidator(0.0), MaxValueValidator(10.0)] ) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) movie = models.ForeignKey(Movie, on_delete=models.CASCADE) created_at = models.DateTimeField(default=datetime.now) updated_at = models.DateTimeField(auto_now=True) class Meta: unique_together = ('user', 'movie') indexes = [ models.Index(fields=['user', 'movie']), ] def view_movie_detail(request, movie_id): if not(Movie.objects.filter(id=movie_id)): Movie(id = movie_id).save() movie = Movie.objects.get(id=movie_id) if request.method == "POST": form = Comment_movie_CreateForm(request.POST) if form.is_valid(): Comment_movie( comment = form.cleaned_data['comment'], user = request.user, stars = form.cleaned_data['stars'], movie = movie ).save() return redirect('view_movie_detail', movie_id=movie_id) else: form = Comment_movie_CreateForm() data = requests.get(f"https://api.themoviedb.org/3/movie/{movie_id}?api_key={TMDB_API_KEY}&language=en-US") … -
Django & AJAX to show DB objects upon user's input submission
I'm pretty new in the Web development world, have been using Django so far. I've been trying to figure out how to render data back to page after clicking on a submit button, so I see I'll need to use AJAX for that purpose. I've created a very simple app just to understand the basics of AJAX. However, googling, I couldn't really find a basic straight-forward implementation so I kinda got lost... What I'm trying to achieve: I have a model called Country: class Country(models.Model): name = models.CharField(primary_key=True, max_length=35) continent = models.CharField(max_length=10) capital = models.CharField(max_length=35) currency = models.CharField(max_length=10) And a super simple main page that asks the user to insert some country name. The idea is to bring to the page all the info from the DB. So it would look like this: main page snapshot Main page HTML body: <body> <h2><em>Please type a country name:</em></h2><br><br> <div class="container"> <form id="get_info" method="post"> {{ form }} {% csrf_token %} <input id="submit_button" type="submit" name="submit" value="Get info"> </form> </div> </body> views.py: from django.shortcuts import render from country_trivia import forms def main_page(request): get_info_form = forms.GetInfo() return render(request, 'country_trivia/index.html', {'form': get_info_form}) forms.py: from django import forms class GetInfo(forms.Form): country_name = forms.CharField(label="") I've seen some examples using … -
django-cqrs No model with such CQRS_ID: X
i'm trying to use CQRS design on django using the library "django-cqrs", something is not right, cause i've followed the documentation very closely, but it throws me this error No model with such CQRS_ID: categoria. ('CQRS is failed: pk = 6 (categoria), correlation_id = None, retries = 0.',) No model with such CQRS_ID: categoria. Model for cqrs_id categoria is not found. my models of both the master and the replica, are with the CQRS_ID completely the same, I have copied the entire line of the master model to place it in the replica model, and still throws me the error Here are the models code Master: from dj_cqrs.mixins import MasterMixin from django.db import models class Categoria(MasterMixin, models.Model): CQRS_ID = 'categoria' nombre = models.CharField(null=False, max_length=200) Replica: from dj_cqrs.mixins import ReplicaMixin from django.db import models class CategoriaRef(ReplicaMixin, models.Model): CQRS_ID = 'categoria' id = models.IntegerField(primary_key=True) nombre = models.CharField(null=False, max_length=200) So it's kind of curious, i don't know where the error is -
django allauth login callback going to server behind firewall
My django instance is behind a firewall and there is a front facing proxy that exposes it. Whenever a login request (to google) comes from a user using the proxy website, the callback uri is to the server behind the firewall, and since that server isn't exposed, the login fails. This happens regardless of what servers I have enabled in the google oauth portal. -
Testing redirects to parameterized URLs when creating object
I have a view for creating blog posts which redirects the user to a form to fill the blog post content like this: from django.views import View from app.models import BlogPost class CreateBlogPost(View): def post(): new_post = BlogPost.objects.create() return redirect(reverse('post_edit'), args=[new_post.id]) class EditBlogPost(View): ... And my urls are the following: from django.urls import path from app.views import CreateBlogPost urlpatterns = [ path('post', CreateBlogPost.as_view(), name='post_create'), path('post/<int:pk>/edit', EditBlogPost.as_view(), name='post_edit') ] I would like to: test the CreateBlogPost by asserting that it redirects to post/<some_id>/edit. I've tried: using the method assertRedirects from django's SimpleTestCase, but couldn't find a way to make this work. I'm also using pytest-django, in case that's relevant.