Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest framework router ModelViewSet
I want to use ModelViewSet in router. But I want to choose list retrieve destroy. views class UsersView(ModelViewSet): ... I know it can views class UsersView(mixins.RetrieveModelMixin, mixins.DestroyModelMixin, mixins.ListModelMixin, GenericViewSet): ... urls router = DefaultRouter() router.register(r'users', UsersView) urlpatterns += router.urls Is there a better way? -
AttributeError: module 'django.db.models' has no attribute 'BigAutoField'
so i'm following the Django project in the textbook "Python crash course 2nd ed" and i'm into the mapping URLS section for those who know, and when i try my system cant seem to runserver anymore, i'm encountering the following error: AttributeError: module 'django.db.models' has no attribute 'BigAutoField' if anyone can help, it would be great, thanks already. i'm fairly new to django and trying my way around it but i don't really know what or where to find the error.. it worked actually fine before i added the two urls.py: from django.urls import path, include from django.contrib import admin urlpatterns = [ path('admin/', admin.site.urls), path('', include('learning_logs.urls'), name='learning_logs'), ] and """Defines url patterns for learning_logs.""" from django.urls import path from . import views app_name = 'learning_logs' urlpatterns = [ # Home page. path('', views.index, name='index'), ] -
Django Rest Framework Jwt + router
I want the front end to display token and refresk url. Is there a way to add Jwt in the router? I now use urlpatterns = [ path('token/', TokenObtainPairView.as_view(), name='my_jwt_token'), path('refresh/', TokenRefreshView.as_view(), name='token_refresh'), ] I want to do something like this. router = DefaultRouter() router.register(r'token', TokenObtainPairView) router.register(r'token', TokenRefreshView) urlpatterns += router.urls -
If i have many different virtual enviroments in my computer, how to make sure a django project is using a specfic one of them?
Think I have established 5 virtual enviroments in a folder using commandlines, and than start a django project outside of the folder how can i make sure which virtual env i am using in this django project, if the project is not using any virtual env in the folder, how can i change (make some configurations) the project's virtual env to a specific one in the folder? pycharm pro will automaticlly establish the link between django project and virtual env, but what if i am using a community version, how can i make it clear that which django project is using which virtual env? I think i have the same problem in this question from stackoverflow: How to make sure that my django project is using virtual environment that i created for it? if anyone know this and could give me some explaination that would be great, thank a loooooot ahead~ -
Add model data to anohter model with 2 forms in same html with django
Im new in Django and im stuck in one of the main features of a small project im working in, in a few words this is like an ecommerce webpage where users can create lists or categories and then create and add products to them, in the publish template where I'm stuck the user can do all of that, if the user doesn't have a list he can create one with a popping modal or select where he wants to add the product, this is the layout, so you can get a better idea! html publish layout Next i share my model.py code segment: class List(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=40 class Product(models.Model): list = models.ForeignKey(List, on_delete=models.CASCADE) title = models.CharField(max_length=40) description = models.TextField() price = models.IntegerField() My forms.py code segment : class NewList(ModelForm): class Meta: model = List fields = ['title'] class NewProduct(ModelForm): class Meta: model = Product fields = ['title', 'description', 'price'] And finally my views.py segment, which only allows me to create a list: @login_required(login_url='log') def test(request): data = List.objects.filter(user=request.user) listForm = NewList(request.POST) if listForm.is_valid(): l = listForm.save(commit=False) l.user = request.user l.save() context = { 'data': data, 'listForm': listForm } return render(request, "test.html", context) I already … -
Why is django returning my html code when using a variable with the value retained from a filter?
im a beginner at learning django and i have a website with a part that allows you to list down your uncompletetd task so far i only want to display it and whenever i use filter with this second variable({"items":todos} that i want to be displayed in the template it returns the html skeleton *Everything works fine when i dont add this variable in the return statement.I have even tried printing the result from the filter and it works perfectly def dashboard(response): print(response.user.username) if response.method == 'POST': form = CreateNewList(response.POST) if form.is_valid(): n = form.cleaned_data['name'] t = ToDoList(name=n) t.save() response.user.todolist.add(t) else: form = CreateNewList() todos = ToDoList.objects.filter(user=response.user) print(todos) return render(response, 'classy_main/dashboard.html',{"items": todos},{"form":form}) return render(response, 'classy_main/dashboard.html',{"form":form, "list": t}) -
Cant update specific quantity in Django shopping cart
I am trying to update my shopping cart to a specific value that is being passed in by a form under the name "num". I am not sure how I can take this value and update my cart to a specific number. I also have an add to cart button on my mainpage that doesnt include a number input. videogame.html <form action="{% url 'add-to-cart' videogame.pk%}" method='get'> <input name='num' type="number" placeholder="Select Amount" value=1> <a href="{% url 'add-to-cart' videogame.pk%}"> <button class='button submit'>Add to Cart</button> </a> </form> views.py def add_to_cart(request, pk): number = 0 if request.GET.get('num'): number = request.GET.get('num') print(number) videogame = get_object_or_404(Videogame, pk=pk) order_item, created = OrderItem.objects.get_or_create( videogame=videogame, user=request.user, complete=False) order_qs = Order.objects.filter( user=request.user, complete=False) if order_qs.exists(): order = order_qs[0] if order.items.filter(videogame__pk=videogame.pk).exists(): order_item.quantity += 1 order_item.save() else: order.items.add(order_item) else: order = Order.objects.create(user=request.user) order.items.add(order_item) return redirect('cart') -
Django queryset order by another model field without foreignkey
I want Foo.objects.all() order by Bar.order Two tables connect by ryid fields without foreign key. The database I got like this, I cannot set ryid it to foreign key. class Foo(models.Model): lsid = models.AutoField(db_column='Lsid', primary_key=True) ryid = models.IntegerField(db_column='Ryid', blank=True, null=True) class Bar(models.Model): lsid = models.AutoField(db_column='Lsid', primary_key=True) ryid = models.IntegerField(db_column='Ryid', blank=True, null=True) order = models.IntegerField(db_column='Wzpx', blank=True, null=True) -
Django forms - can I post objects to a form, import the form to Views, and re-use it by calling from other functions?
1. Summarize the problem: I am building a Django application, and I'm hoping to create objects that I can post to a form. I envision then importing Forms to Views in Django, and then passing the object to another web page via a definition in Views. 2. Describe what you’ve tried. I'm still in the planning stage, though I've tried a few versions of this with URLs and text. I've been able to create a form to upload new items to a list, for example, and then post that to another web page. 3. When appropriate, show some code. I envision something like the below, but before I get too far down the road, I'd like some expert eyes and advice: def metrics(request, pkid): chart = Metricspage.objects.get(pk=pkid) return render(request, "MyApp/reports/metrics.html", {"chart": chart}) -
Django DetailView: switches me to a different user
I have two user types, a student and a tutor.. and I have this ListView of tutors rendering their name, profile headline and bio, which works successfully, and I also put a link to those three fields redirecting to the detailed view of their profile. Now, I used cbv DetailView for rendering a detailed view of their profile, which also works fine.. but the only problem is, whenever I click on those link as a student, it switches my profile or my user type to that specific tutor, but when I click home or any pages of the website it switches back to normal. Could someone help me with this, please? Because I have search a solution for this problem since yesterday but I couldn't find a problem that similar to mine. Sorry for my english btw. This is the list of tutors, and as you can see on the upper right, I am logged in as a student. Here, you can see on the upper right that it switches me to joss's profile. this is my models class User(AbstractUser): is_student = models.BooleanField(default=False) is_tutor = models.BooleanField(default=False) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.EmailField(max_length=100) phone_number = models.CharField(max_length=11, blank=False) current_address … -
how to configure django-redis and django
I am working on an ec2 instance ubuntu and i installed redis normally and it works. Now the issue is that i subscribed for redis paid version and created a database on their website redis.com, after creating the database they gave me an endpoint url that look like this redis-21890.us-xx.ec2.cloud.redislabs.com:21890. Using the default config below, django works fine... settings.py CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } } but i want to connect to the database i paid for so i changed it to CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://redis-21890.us-xx.ec2.cloud.redislabs.com:21890/", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "PASSWORD": "redisDatabasePassord", } } } and now django is failing with the error below: redis.exceptions.AuthenticationError: Authentication required Is there something that i am doing wrong here? because when i try to connect to the redis-cli -p port -h host -a password with the same credentials it works. -
URL lookup not working with update and retrieve
In the url /users/*username I should be able to access each user by its username, the problem is that it isn't working how it's supposed to, doesn't matter what I write in *username it will update/delete the current logged user. Here it's the User View with the methods that are not working the way I intended: class UserViewSet(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet): serializer_class = UserSerializer lookup_field = 'username' queryset = User.objects.all() def get_permissions(self): if self.action in ['signup', 'login',]: permissions = [AllowAny] elif self.action in ['retrieve', 'update', 'destroy']: permissions = [IsAuthenticated, IsSameUser] else: permissions = [IsAuthenticated] return [p() for p in permissions] def retrieve(self, request, *args, **kwargs): response = super(UserViewSet, self).retrieve(request, *args, **kwargs) data = response.data return Response(data=data, status=status.HTTP_200_OK) def update(self, request, *args, **kwargs): serializer = UserModelSerializer(request.user, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) -
How to construct an autocomplete page field based on Pint's units and prefixes
I want to be able to enter "Mpa" in a page field and have "MegaPascal" returned as an autocomplete selectable item using Pint's ureg units and prefixes. The main issue is that MegaPascal isn't an actual ureg element, it's the "Mega" prefix combined with the "Pascal" ureg unit. I assume that pint's ureg unit names and abbreviations can be loaded into a Javascript arrays via an api url when the page loads These arrays could then be searched JQuery UI autocomplete using a function as the source. But I can't see how to extract Pint's prefixes from Pint or how to integrate them into the autocomplete source function lookup. My current solution is to load all pint units and abbreviations into a Django model and use django's autocomplete function. -
adding table with Django and report lab
The following code works for pdf creation, what I wanted is put the data to a table def pdf_view(request): enc = pdfencrypt.StandardEncryption("pass", canPrint=0) buf = io.BytesIO() c = canvas.Canvas(buf, encrypt=enc) width, height = A4 textob = c.beginText() textob.setTextOrigin(inch, inch) textob.setFont("Helvetica", 14) lines = [] users = User.objects.filter(is_staff=False) for user in users: lines.append(user.username) lines.append(user.email) lines.append(user.first_name) for line in lines: textob.textLine(line) c.drawText(textob) c.showPage() c.save() buf.seek(0) return FileResponse(buf, as_attachment=True, filename='users.pdf') I tried to append the data to a table, what I tried is as follows def pdf_view(request): enc = pdfencrypt.StandardEncryption("pass", canPrint=0) buf = io.BytesIO() c = canvas.Canvas(buf, encrypt=enc) width, height = A4 textob = c.beginText() textob.setTextOrigin(inch, inch) textob.setFont("Helvetica", 14) lines = [] users = User.objects.filter(is_staff=False) for user in users: lines.append(user.username) lines.append(user.email) lines.append(user.first_name) table = Table(lines, colWidths=10 * mm) table.setStyle([("VALIGN", (0, 0), (-1, -1), "MIDDLE"), ("ALIGN", (0, 0), (-1, -1), "CENTER"), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black)]) table.wrapOn(c, width, height) table.drawOn(c, 0 * mm, 5 * mm) styles = getSampleStyleSheet() ptext = "This is an example." p = Paragraph(ptext, style=styles["Normal"]) p.wrapOn(c, 50 * mm, 50 * mm) # size of 'textbox' for linebreaks etc. p.drawOn(c, 0 * mm, 0 * mm) # position of text / where to draw c.save() buf.seek(0) return FileResponse(buf, … -
Django: pass information between apps
I've two models in two different apps, In the firs one I'm asking my user biography information in the second one they have question to answer. I'd like to save in my database not only the answers but also the id code created in the account models file and use the userinformation answer to create the string name to use in the database but it gives me error "'ImportError: cannot import name 'name' from 'accounts.models' " even if I've imported the modules- This is my code: **accounts.models** class UserInformation(models.Model): name = models.CharField(max_length=250) lastname = models.CharField(max_length=250) phone = models.CharField(max_length=250) birthday = models.DateField() age = models.CharField(max_length=2) id = models.CharField(max_length=250) def __str__(self): self.name + '_' + self.lastname + '_' + str(self.birthday.year) if self.id_code =="": self.id_code = self.name + '_' + self.lastname + '_' + str(self.birthday.year) self.save() super(UserInformation, self).save(*args, **kwargs) **accounts.forms.py** class UserInformationForm(forms.ModelForm): class Meta: model = UserInformation fields = ('name', 'lastname', 'birthday', 'phone') **accounts.views.py** def add_information(request): if request.method == 'POST': form = UserInformationForm(request.POST, request.FILES) if form.is_valid(): form.instance.user = request.user form.save() return redirect('home') else: form = UserInformationForm() return render(request, 'add_information.html', {'form': form}) **question.models.py** from accounts.models import name class QuestionOne(models.Model): question_1a = models.CharField(max_length=250, choices=point) question_2a = models.CharField(max_length=250, choices=point) question_3a = models.CharField(max_length=250, choices=point) id_code = models.CharField(max_length=250) … -
In Django Admin changelist view, how to make a foreign key column sort by a value other than primary key?
I have a table with a Many-to-One relationship to itself, facilitating a tree structure: class Medium(models.Model): label = models.CharField(max_length=30) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True) def __str__(self): return self.label In the Django Admin changelist view, I would like show a second column with the parent medium's label for context - and I would like the column to be able to sort based on the label. However, if I use list_display to add field 'parent', that column sorts by the primary key. Demonstration: @admin.register(Medium) class MediumAdmin(admin.ModelAdmin): list_display = ('label', 'parent', 'parent_id') What's the correct or most elegant way of accomplishing this? I've seen suggestiongs to do it by adding a custom method to MediumAdmin that returns the parent label, and then apply the @admin.display(ordering='parent__label') decorator to it, but I feel like I'm missing a more correct way, since this is surely a common need. -
Field 'id' expected a number but got 'The Complete JavaScript' when i try to create a course i get this error
Here is my course model. class Course(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL,\ related_name='courses_created', on_delete=models.CASCADE) subject = models.ForeignKey(Subject,related_name='courses', on_delete=models.CASCADE) title = models.CharField(max_length=200) pic = models.ImageField(upload_to="course_pictures") slug = models.SlugField(max_length=200, unique=True,blank=True) overview = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) enroll = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name='enrollment',blank=True) class Module(models.Model): course = models.ForeignKey(Course, related_name='modules', \ on_delete=models.CASCADE) title = models.CharField(max_length=200) description = models.TextField(blank=True) order = OrderField(blank=True, for_fields=['course']) class Meta: ordering = ['course'] class Content(models.Model): module = models.ForeignKey(Module,related_name='contents', on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType,on_delete=models.CASCADE,\ limit_choices_to={'model__in':('text', 'video','image','file')}) object_id = models.PositiveIntegerField() item = GenericForeignKey('content_type', 'object_id') order = OrderField(blank=True, for_fields=['module']) Here is my function base view for creating course, When i try making a post request to create a course django throws the except ValueError Field 'id' expected a number but got 'The Complete JavaScript'. I wonder where this error is coming from, can anyone be of help. def course_create(request,*args,**kwargs): id = kwargs.get('id') if request.method =="POST": subject = request.POST['title'] course = request.POST['title'] overview = request.POST['overview'] front_pic = request.POST['pic'] title = request.POST['title'] desc = request.FILES.get('description') owner = Account.objects.get(username=request.user.username) course,create = Course.objects.get_or_create(title=course, owner=owner, subject=subject) subject,create = Subject.objects.get_or_create(title=subject) module,create = Module.objects.get_or_create(course=course, description=desc, title=title, order=id) data = Course(owner=owner, title=course, subject=subject, pic=front_pic, desc=desc, overview=overview, order=id, module=module.id) data.save() return redirect('course:main') return render(request,'manage/module/formset.html') -
Setting an initial value in a Django Form
I have to setup an initial value in a form and somehow is not working, it is extremely strange as I have exactly the same code in another view, but in this case my approach is not working: views.py @login_required def add_lead(request): if request.method == 'POST': lead_form = LeadsForm(request.POST) if lead_form.is_valid(): lead_form.save() messages.success(request, 'You have successfully added a new lead') return HttpResponseRedirect(reverse('add_lead')) else: messages.error(request, 'Error updating your Form') else: user = {"agent":request.user} lead_form = LeadsForm(request.POST or None, initial = user) return render(request, 'account/add_lead.html', {'lead_form': lead_form} ) forms.py class LeadsForm(forms.ModelForm): class Meta: model = Leads fields = ('project_id','company','agent','point_of_contact','services','expected_licenses', 'expected_revenue','country', 'status', 'estimated_closing_date' ) widgets = {'estimated_closing_date': DateInput(), } Essentially, the agent is the logged user, so I'm passing request.user as a variable, but I have not succeeded, which is very strange because I have that same logic in another form Any help will be appreciated -
Django check if ManyToManyField has connection
I have the following model: class Party(models.Model): participants = models.ManyToManyField(User, related_name='participants') How can I check if a user is participating the party? I've tried many lookups, but none are working. I'd like to have something like this in my views.py: def get_queryset(self): qs = models.Party.objects.all() qs.filter(participants__in=self.request.user.pk) return qs -
Simple internal server error because running uwsgi keeps on deleting the .sock file
I'm trying to deploy my first django app by following these steps. The problem I have is that, for some reason, running uwsgi --emperor venv/vassals/ --uid www-data --gid www-data after activating my venv just seems to delete the .sock file in my root dir. I assume this is causing the problem because looking at the nginx logs at /var/log/nginx/error.log suggest so: 2021/10/11 22:09:57 [crit] 4281#4281: *6 connect() to unix:///var/www/dolphin/dolphin.sock failed (2: No such file or directory) while connecting to upstream, client: 81.102.82.13, server: example.com, request: "GET /favicon.ico HTTP/2.0", upstream: "uwsgi://unix:///var/www/dolphin/dolphin.sock:", host: "example.com", referrer: "https://example.com/ Here is my config file in /etc/nginx/sites-available (symlinked to sites-enabled): ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # the upstream component nginx needs to connect to upstream django { server unix:///var/www/dolphin/dolphin.sock; #server unix:/var/www/dolphin/dolphin.sock; } # configuration of the server server { listen 443 ssl; server_name example.com; charset utf-8; # max upload size client_max_body_size 75M; # Django media and static files location /media { alias /var/www/dolphin/app/media; } location /static { alias /var/www/dolphin/app/static; } # Send all non-media requests to the Django server. location / { uwsgi_pass django; include /var/www/dolphin/uwsgi_params; } } My dolphin_uwsgi.ini file: [uwsgi] # full path to Django project's root directory chdir = /var/www/dolphin/ # Django's wsgi file … -
Django - Installed Django in virtualenv but cannot import it on git-bash
I am installing Django on virtualenv using git-bash However, I cannot import it to python. I tried to run django also keep getting ImportError Any idea why? -
Django automatic remove user if is no verified in time
I have a flag in django is_verified and i override User to CreateUser now i want automatic remove from db user if flag > 10 min == False, but when True nothing do. I created something like this in class CreateUser but this didn't work. def remove_user_time(self): user = super().objects.get(email=self.email) register_time = user.date_joined ten_minutes_later = (register_time + timedelta(hours=0.16)) if ten_minutes_later == datetime.now(): if user.is_verified == False: user.delete() -
Trying to autoassign a django group to users created by AAD/SSO process
I've spent the past 4 hours looking through so many resources trying everything to solve this and nothing with success. The short is that I'm trying to add a default group to all new users created. Users are created the first time they authenticate via AAD/SSO, but when they come in, they have no Auths. I'd like to have them receive a default group when the SSO process creates the user (e.g. from the post-save receiver of the User object). I've looked through dozens of examples using something very similar to the below code. OK fine, the process runs, never generates any errors, and successfully creates the CustomUserProfile record, but the user never gets assigned the default group. 110% chance the group exists and the get finds the group (have done exercises to confirm this). What do I have wrong on this?? Why won't this process create the group assignment (or hit the error process to tell me what's going on here)? using django 3.2.8, Python 3.8.7 @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): try: if created: instance.groups.add(Group.objects.get(name='Basis - Standard Access')) CustomUserProfile.objects.create(user=instance).save() except Exception as err: print('Error creating basis user profile!') print(err) -
Include paramquery into django application
Any idea why pqgrid from paramquery is not working? I tried import local files or link online files and it does not matter still not working. I think it is a problem when I am loading files into django project, but I don't know why. Any help? Here it is HTML template: {% load static %} <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Django Girls</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script> <link href="https://unpkg.com/jquery-ui-pack@1.12.2/jquery-ui.css" rel="stylesheet" /> <link href="https://unpkg.com/jquery-ui-pack@1.12.2/jquery-ui.structure.css" rel="stylesheet" /> <link href="https://unpkg.com/jquery-ui-pack@1.12.2/jquery-ui.theme.css" rel="stylesheet" /> <script src="https://unpkg.com/jquery-ui-pack@1.12.2/jquery-ui.js"></script> <link href="https://unpkg.com/pqgrid@8.1.1/pqgrid.min.css" rel="stylesheet" /> <link href="https://unpkg.com/pqgrid@8.1.1/pqgrid.ui.min.css" rel="stylesheet" /> <link href="https://unpkg.com/pqgrid@8.1.1/themes/steelblue/pqgrid.css" rel="stylesheet" /> <script src="https://unpkg.com/pqgrid@8.1.1/pqgrid.min.js"></script> <script src="https://unpkg.com/pqgrid@8.1.1/localize/pq-localize-en.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/2.5.0/jszip.min.js"></script> <script src="https://unpkg.com/file-saver@2.0.1/dist/FileSaver.min.js"></script> <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"> <link rel="stylesheet" href="{% static 'css/blog.css' %}"> </head> <body> <div class="page-header"> {% if user.is_authenticated %} <a href="{% url 'post_new' %}" class="top-menu"><span class="fa fa-plus" aria-hidden="true"></span></a> <a href="{% url 'post_draft_list' %}" class="top-menu"><span class="fa fa-edit"></span></a> <p class="top-menu">Hello {{ user.username }} <small>(<a href="{% url 'logout' %}">Log out</a>)</small></p> {% else %} <a href="{% url 'login' %}" class="top-menu"><span class="fa fa-lock"></span></a> {% endif %} <h1><a href="/">Django Girls Blog</a></h1> </div> <div class="content"> <div class="row"> <div class="col"> <div id="grid_json" style="margin:100px;"></div> {% block content %} {% endblock %} </div> </div> </div> </body> </html> Settings files: # Static files … -
Loading and parsing a local JSON-file
I have a fully working function for displaying external JSON data from an URL def object_api(request): url = 'https://ghibliapi.herokuapp.com/vehicles' response = requests.get(url) data = response.json() arr = [dic for dic in data ] context = { 'data': arr, } return render(request, 'output.html', context) Now I need to load a local file, e.g. example.txt filled with JSON-data. How do I load such a file? My current problem is the transformation of data to a proper "context"-variable.