Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Anyone knows how to configure organization pages in richie lms?
I have configured successfully RICHIE LMS in my local machine successfully but it was showing me an error when I want to add any organization or course page in there. It was showing me "ypu have to create parent page and revese the parent page id to current page". Anyone configure richie in local machine?If so please help me with that.Thanks in advance. -
Show blogpost suitable to the current category
I want to filter my database based on the menuItem or category of my blog posts. With self.request.path I get something like '/py/' what represents one of my categories. By now I do this way and it works fine, but is there a better way? Should I create for each category a different app and write it's own IndexView with fix queryset filter? If there is a better solution to my problem than I would happy to know :) Here my CategoryIndexView: class CategoryIndexView(ListView): model = Post template_name = 'blog/category_index.html' # context_object_name = 'category' def get_queryset(self): category = self.request.path[1:-1] if category.lower() == 'ml': query_set = Post.objects.filter(category=0) elif category.lower() == 'py': query_set = Post.objects.filter(category=1) elif category.lower() == 'kt': query_set = Post.objects.filter(category=2) elif category.lower() == 'cpp': query_set = Post.objects.filter(category=3) else: query_set = Post.objects.filter(category=0) return query_set Here a snippet of my urlpatterns: urlpatterns = [ path('about/', genViews.about, name='about'), path('imprint/', genViews.imprint, name='imprint'), path('admin/', admin.site.urls), path('',genViews.HomeView.as_view(), name='home'), path('ml/',blogViews.CategoryIndexView.as_view(), name='machine_learning'), path('py/',blogViews.CategoryIndexView.as_view(), name='python'), path('kt/',blogViews.CategoryIndexView.as_view(), name='android'), path('cpp/',blogViews.CategoryIndexView.as_view(), name='cpp') ] -
Creating a printful order using the API with Django python
i am trying to create order with printful API, i don't understand where i am wrong. the error that comes out of me is: {"code":400,"result":"Invalid request: missing order element","error":{"reason":"BadRequest","message":"Invalid request: missing order element"}} this is the code, for those who have already integrated it what is the variant_id and how can I find it? Someone help me please import requests import json @login_required def test(request): # variabili per connessione token = "4XYO4WBEGWtpQoTtRBh1xF4ulQnt8dLKfyjXpxFt" url = "https://api.printful.com/" header = {'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json'} # dati ordine payload = { "recipient": { "name": "John Smith", "address1": "Via milano 55", "city": "Arese", "state_name": "Milano", "country_code": "IT", "zip": "20020" }, "items": [ { "variant_id": 1, "name": "Digital Tech", "quantity": 1, "retail_price": "40.00", } ] } crea = requests.post(url + 'orders', params = payload, headers = header) ottieni = requests.get(url + 'store/products', headers = header) context = {'test': ottieni.json(), 'crea': crea.text} return render(request, 'test.html', context) -
Django Template Tag - Get count from related models
How are you! I'm listing in html a list of registers (RegAcceso) and I want to include in each of them the amount of registers (Registros) connected to it through a foreign key. Models class RegAcceso(models.Model): reg_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) fecha = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.id} - {self.reg_user} - {self.fecha.strftime("%d/%m/%Y")}' class Meta: ordering = ['-fecha'] class Registro(models.Model): id_reg = models.ForeignKey(RegAcceso, on_delete=models.CASCADE) cuil = models.BigIntegerField() deduccion = models.CharField(max_length=50) tipo = models.CharField(max_length=50) dato1 = models.CharField(max_length=50) dato2 = models.CharField(max_length=50, blank=True, null=True) porc = models.CharField(max_length=3, blank=True, null=True) def __str__(self) -> str: return f'{self.id_reg.reg_user} - {self.id_reg.fecha.strftime("%d/%m/%Y")} - {self.cuil}' Views @login_required def siradig_view(request): listado = {} query_historia = RegAcceso.objects.filter(reg_user=request.user) if request.method == 'POST' and request.FILES.get('upload'): # TODO: Validar form listado = lista_zip(request.FILES['upload']) dire = lista_zip_ex(request.FILES['upload']) archivo_path = os.path.join(settings.TEMP_ROOT, 'ultima_carpeta.txt') with open(archivo_path, 'w') as f: f.write(dire) else: # Borro los archivos en carpeta temporal clean_folder(settings.TEMP_ROOT) my_context = { 'listado': listado, 'query_historia': query_historia, } return render(request, 'reader/home.html', my_context) Template {% if query_historia %} <div class="card" style="width: 80%;"> <ul class="list-group list-group-flush"> {% for registro in query_historia %} <li class="list-group-item text-center"> <a href="{% url 'historico' registro.id %}">{{ registro.fecha|date:"d/m/Y h:i a" }}{{ registro.count }}</a> </li> {% endfor %} </ul> </div> {% endif %} I'm stuck in the {{ registro.count }} … -
What is the correct way of viewing images from your backend(database) to your frontend(html)
I have being stuck on this for a while. The images are not displaying when ever i use this line of code. {% load static %} {% block content %} {% for product in product %} Product Name: {{ product.name }} Price: {{ product.price }}<br> Picture: <img src="{{ product.image.url }}" alt="..."> {% endfor %} {% endblock %} instead i am getting this error "('ImageFieldFile' object is not subscriptable)" -
django filter with related name
I have a model looks like this clas AModel(models.Model): name = models.CharField(max_lentght=100) reply = models.ForeignKey('SomeModel') class BModel(models.Model): a_model = models.ForeignKey(AModel, related_name='amodel') user = models.ForeignKey(User) tag = models.ForeignKey(TagModel) I have queryset of AModelViewSet then def get_queryset(self): q = super().get_queryset() q = q.filter(amodel__user_id=self.request.user) if self.request.GET.get('tag'): q = q.filter(amodel__tag_id=self.request.GET.get('tag')) retrun q.distinct() in this queryset after if self.request.GET.get('tag') filter not working it returns all objects which have different tags but does not return specific objects related to current user but if I query follow if self.request.GET.get('tag'): q = q.filter(amodel__tag_id=self.request.GET.get('tag'), amodel__user=self.request.user) retrun q.distinct() it works perfectly but I do not understand why the second method is working but not the first one. in the first line, I filter by a user and if a tag is given again I will filter again with the returned query but it is not working can anyone help me understand this, please? thank you in advance -
How to combine python file in pycharm and link with vscode files when creating web app
Connecting html and css files in vscode with python file in pycharm to create web app -
API to serve rapidly updating JSON data
I am building a fun practice project to scrap data from a site and then serve it in a nicer format. My favorite frameworks are Next and Django. I will probably want to be able to run the scraper from the client on demand or at least a couple times a day on auto. Wondering if my API should run off a json file or if I should move it into a database? Is there any case for keeping it in a JSON file? File size is about 5MB with like 7000 objects. If I am using Scrapy, is that a strong case for using Django? I was planning on using Next-MongoDB but in this case I would go full Django. -
cannot Assign Value , must be an instance django
I am getting below error when inserting values through request.post.get method Cannot assign "'1'": "Faculty_Feedback.department" must be a "Department" instance. The model in which i want to insert data is class Faculty_Feedback(models.Model): department = models.ForeignKey(Department,on_delete=models.CASCADE) program = models.ForeignKey(Program,on_delete=models.CASCADE) resp1 = models.IntegerField(default=1) resp2 = models.IntegerField(default=1) resp3 = models.IntegerField(default=1) resp4 = models.IntegerField(default=1) resp5 = models.IntegerField(default=1) resp6 = models.IntegerField(default=1) resp7 = models.IntegerField(default=1) resp8 = models.IntegerField(default=1) resp9 = models.IntegerField(default=1) resp10 = models.IntegerField(default=1) resp11 = models.IntegerField(default=1) resp12 = models.IntegerField(default=1) resp13 = models.IntegerField(default=1) I am inserting department and program values into template from below code departments = Department.objects.all() programs= Program.objects.all() context = { "departments":departments, "programs":programs } Below is the template code <div class="form-group"> <label for="text">Department</label> <select style="width: 90%" class="form-control" name="department" id="department"> {% for department in departments%} <option value="{{department.pk}}">{{department.dept}}</option> {% endfor%} </select> </div> <div class="form-group"> <label for="text">Program</label> <select style="width: 90%" class="form-control" name="program" id="program"> {% for program in programs%} <option value="{{program.pk}}">{{program.program}}</option> {% endfor%} </select> </div> I am inserting data of feedback by getting values through request.post.get method def feedback(request): if request.method == "POST": dept = request.POST.get('department') prog = request.POST.get('program') q1 = request.POST.get('f1') q2 = request.POST.get('f2') q3 = request.POST.get('f3') q4 = request.POST.get('f4') q5 = request.POST.get('f5') q6 = request.POST.get('f6') q7 = request.POST.get('f7') q8 = request.POST.get('f8') q9 = request.POST.get('f9') q10 = … -
how can i change security name in django swagger specticuler?
enter image description here in settings.py SPECTACULAR_SETTINGS = { 'TITLE': 'title', 'VERSION': '1.0.0', 'SERVE_INCLUDE_SCHEMA': False, 'CONTACT': {'name':'name','email':'noreplay@gmail.com'}, 'SCHEMA_PATH_PREFIX_TRIM': True, 'SERVERS': [{'url': env('SWAGGER_SERVER')},], 'PREPROCESSING_HOOKS': ["custom.url_remover.preprocessing_filter_spec"], } in django by default schema and swagger generation i am not able to solve this issue -
Django display list of dictionary in template - dict key as variable
I am using Django 4.0 to display a frontend page which source data is a list of dict. I want to order the keys of the dict and then display all dict in the list in the same order. Here is my views.py: def UserGoalstatus(request, promise_token): print("__UserGoalstatus__") from cmd_utils import Retrieve_goal data = Retrieve_goal(promise_token) keys = set() for item in data: keys.update(set(item)) key_order = sorted(keys) context = { "data": data, "key_order": key_order, } return render(request, 'json_table.html', context) Here is the content of my 'data' variable: [ {'goal_key': '286815', 'goal_type': 'hotelreservation', 'goal_id': 16149845, 'promise_token': '9ba51cbc-830b-64d603904099', 'campaign_id': 1002204, 'properties': {'price': 100, 'created': '2022-06-13 10:48:34', 'checkout': '2022-06-13', 'currency_code': 'USD', 'completed_booking_status': 1}}, {'goal_key': '1208107', 'goal_type': 'hotelreservation', 'goal_id': 16149846, 'promise_token': '9ba51cbc-830b-64d603904099', 'campaign_id': 1002204, 'properties': {'price': 100, 'created': '2022-06-13 10:48:35', 'checkout': '2022-06-13', 'currency_code': 'USD', 'completed_booking_status': 1}} ] Here is my html file which I would like to print all content in data in the order of 'key_order' <table id="dtBasicExample" class="table table-hover table-striped table-bordered" cellspacing="0" width="100%"> <thead> <tr> {% for key in key_order %} <th>{{ key }}</th> {% endfor %} </tr> </thead> <tbody> {% for item in data %} <tr> {% for key in key_order %} <td>{{ item.get(key) }}</td> {% endfor %} </tr> {% endfor %} </tbody> … -
I am trying to make an api request to another app in django but in the same project, how do i pass the url to my api view, local deployment is working
``` def getpk(request, pk): current_user = request.user obj = LetterBody.objects.get(id=pk) company = obj.company_details.short_code location = obj.company_details.location.short_code datetime = str(date.today()) token = Token.objects.get(user=current_user.id) url = request.build_absolute_uri(reverse('create')) payload={ 'company':company, 'location':location, 'date':datetime } headers = { 'Authorization': f'token {token}', 'Content-Type': 'application/json' } if obj.reference_code: return redirect('letters') else: response =requests.request( 'POST',url, headers=headers, data=json.dumps(payload)) data = json.loads(response.text) objid =data.get('id') obj.reference_code = str(location) + "/" + company + "/" + str(datetime) + "/" + str(objid) obj.save() return redirect('letter_detail', obj.id) local production is working just fine but once i deploy the api is not working.create is the name to my create url in the api aplication -
chart bars not showing
am trying to display a chart using plotly in django project, the chart appears fine in the page, yet i can't see the bars even though data exist in the database. please help in views.py import pandas as pd from plotly.offline import plot import plotly.express as px def viewReport(request): attendance = Attendance.objects.all() graph_data = [ { 'Student': x.student_id, 'Start': x.date, 'Finish': x.date, 'Course': x.course_id } for x in attendance ] graph_frame = pd.DataFrame(graph_data) figure = px.timeline( graph_frame, x_start="Start", x_end="Finish", y="Student", color="Course" ) figure.update_yaxes(autorange="reversed") gantt_plot = plot(figure, output_type="div") # print(attendance) attendfilter = AttendanceFilter(request.GET, queryset=attendance) attendance = attendfilter.qs context = {'attendance': attendance, 'attendfilter': attendfilter, 'gantt_plot':gantt_plot} return render(request, 'LogInApp/ViewReport.html', context) model.py, the model am retrieving data from class Attendance(models.Model): ATTENDANCE = ( ('absent', 'Absent'), ('present', 'Present') ) student_id = models.CharField(max_length=100, null=True) course_id = models.CharField(max_length=100, null=True) date = models.DateField(auto_now_add=True, null=True) time = models.TimeField(auto_now_add=True, null=True) #week_num = models.CharField(max_length=2, blank=True) attendanceState = models.CharField(max_length=20, null=True,choices=ATTENDANCE) def __str__(self): return '{}'.format(self.student_id) viewattendance.html {% block content%} <div> {% autoescape off %} {{ gantt_plot }} {% endautoescape%} </div> {% endblock content%} </div> -
Printful django connection for creating orders
i want to make a link between django and printful via API to create an order within the printful store. I am looking at the documentation site but I think it is done badly, could someone who is familiar with or has already done this thing could help me? I'm not super expert in API and connections I'm trying to learn, so please if you can show me how you do it or link me some tutorials or useful resources you would do me a great favor @login_required def test(request): # variabili per connessione token = "Fqtsbpy18lIl5DHKCtrKRAm4CNu1fNZnr9V551QZ" url = "https://api.printful.com/" # dati ordine { "external_id": "4235234213", "shipping": "STANDARD", "recipient": { "name": "John Smith", "address1": "Via milano 55", "city": "Milano", "country_code": "IT", "country_name": "Italy", "zip": 20020, "email": "email@gmail.com", }, "items": [ { "id": 1, "quantity": 1, "price": "13.00", "name": "Enhanced Matte Paper Poster 18×24", } ], "retail_costs": { "currency": "EUR", "subtotal": "10", "shipping": "5.00", "total": "15" }, } header = {'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json'} test = requests.get(url + 'orders', headers = header) print('---------------', test, '------------') context = {'test': test.json()} -
Django-rest-auth : How refresh Token?
I'm using Django-rest-auth for authentication (https://django-rest-auth.readthedocs.io). but when I register a new account, the api sent back to me a Token who never change after. For more security, how can I do to have a new token every time I login ? -
Django+Haystack query does not find substrings in model's attributes
I am using haystack + whoosh in my app. And I have a model like this: class Person(models.Model): name = models.CharField(max_length=64) surname = models.CharField(max_length=64) and search index like this: class PersonIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) name = indexes.CharField(model_attr='name') surname = indexes.CharField(model_attr='surname') def get_model(self): return Person def index_queryset(self, using=None): return self.get_model().objects.all() and here's my case: when I am looking for person 'Krzysztof' (it's polish name) it finds it, but when I search for 'rzysztof' there is no result. So how can I fix it so it could search for substrings in model attrs? -
Field 'id' expected a number but got <WSGIRequest: GET '/r/1/'>
i tried to make a project which would convert long url to short. take input url from html page and save it to database and redirect it to long url though my new url but got an error and the index.html looks like <h1>short any url here</h1> <form method="POST"> {% csrf_token %} <input type="url" name="url" placeholder="enter your url here"> <input type="submit" value="submit"> </form> {% for urlconverter in urlconv %} <li><a href="{% url 'shorturl:redirect' urlconverter.id %}">{{ urlconverter.short }} </a></li> {% endfor %} urls.py from django.urls import path from .import views app_name='shorturl' urlpatterns=[ path('shorturl/',views.indx,name='home'), path('r/<int:urlconverter_id>/',views.redirect,name='redirect'), ] the models.py from django.db import models # Create your models here. class urlconverter(models.Model): url=models.CharField(max_length=1000) short=models.CharField(max_length=100) def __str__(self): return self.url views.py from django.shortcuts import render,redirect,get_object_or_404 from django.http import HttpResponse from django.template import loader from .models import urlconverter # Create your views here. def indx(request): template=loader.get_template('urlconverter/index.html') urlconv=urlconverter.objects.all() if request.method=='POST': a=request.POST.get('url') b=urlconverter.objects.all() c=b.count() nwurl='/r/'+str(c) s=urlconverter(url=a,short=nwurl) s.save() context={ 'urlconv':urlconv } return HttpResponse(template.render(context,request)) def redirect(request,urlconverter_id): obj=get_object_or_404(urlconverter,pk=urlconverter_id) org_url=obj.url return redirect(org_url,request) and i got this error TypeError at /r/1/ Field 'id' expected a number but got <WSGIRequest: GET '/r/1/'>. Request Method: GET Request URL: http://127.0.0.1:8000/r/1/ Django Version: 4.0.5 Exception Type: TypeError Exception Value: Field 'id' expected a number but got <WSGIRequest: GET '/r/1/'>. … -
Static files and Images won't update on Django
I'm learning the Django, I just tried making a simple blog to see how it works out. Initially, when I started it was very responsive (even though I had to ctrl-f5 to refresh the changes on my chrome browser) there wasn't any problem I was facing. I decided to add an image in the background it wouldn't update not only the image but other edits like the font size and the colour etc. save the file on vscode and then ctrl f5 on the browser still it wouldn't show up. Stuck with this since then. tried to find solutions over the web but none of them worked. I'm still not sure if it's the problem with the code or the browser just won't load it any help is appreciated thanks! body { /* Typography Declarations */ color: #222222; font-size: 2em; font-size: unset; font-family: "Open Sans", "Helvetica Neue", sans-serif; } .content-footer, .masthead-heading, .masthead-intro { text-align: center; } .masthead { padding: 6em 0; background-image: url('/blog/static/blog/css/img/pat.jpg'); /* background-size: cover; background-repeat: no-repeat; */ border-top: solid 1em lightseagreen; } .masthead-intro { /* Layout Declarations */ margin-bottom: 0.1em; /* Typography Declarations */ font-family: "Gentium Book Basic", Georgia, serif; font-size: 20em; } .masthead-heading { /* Layout Declarations … -
Python Django regular expression filter
Only python knowledge is sufficient for this as i can convert it to django myself. I have few values in db for a column "customer_id".Values are of three types: Ben-t-3000386247-R123 Ben-t-3000386247-P123 Ben-t-3000386247-123 I only need to filter out this entries where there is a digit after last "-".Here it is "Ben-t-3000386247-123". Please help me out. Python regular expression code or django filter code. Thankyou all in advance In django we use "customer_id__iregex" as filters. -
Django - Convert UUID back to default ID
Is it possible to convert back from UUID to Django's default ID? Could there be any impact in the existing data? If I delete this line in my Model, Django could automatically add a field to hold the primary key? Any thoughts on this or previous experience? id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) Thanks, -
Recursion error caused by __init__ method
I have a model Folder which has a ForeignKey refering to itself in order to represent a folders structure : class Folder(models.Model): folder_name = models.CharField(max_length=200) parent_folder = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True') def __init__(self, *args, **kwargs): super(Folder, self).__init__(*args, **kwargs) if self.pk is not None: self.initial_filepath = self.filepath() def filepath(self): if not self.parent_folder: return f'media/scripts/{self.folder_name}' else: return f'{self.parent_folder.filepath()}/{self.folder_name}' The issue is, when deleting a folder that has childrens, a recursion error occurs. I was able to determine that it was coming from the filepath method called in the __init__ one. However, what I don't understand, is why this is happening as I don't really understand how the __init__ method work. I'd be glad if someone could help me understand how I could go about dealing with this issue, as I'm currently lost as to what to do. Here's a glimpse of the unending traceback : Traceback (most recent call last): File "C:\Users\stephane.bernardelli\Documents\ScriptsApp\.env\lib\site-packages\django\db\models\fields\related_descriptors.py", line 187, in __get__ rel_obj = self.field.get_cached_value(instance) File "C:\Users\stephane.bernardelli\Documents\ScriptsApp\.env\lib\site-packages\django\db\models\fields\mixins.py", line 15, in get_cached_value return instance._state.fields_cache[cache_name] KeyError: 'parent_folder' During handling of the above exception, another exception occurred: **Exact same error repeating till a recursion error occurs** And when the recursion error occurs, I have a long message (too long for me … -
Cryptocurrency chart to reflect the last 7 day performance
I am trying to generate the last 7 days performance for a number of tokens in Django. Please refer to the coinmarketcap.com which shows the performance of a token for last 7 days. I am getting the real-time price data from Coinbase API. I donot want to store huge historical data in order to generate the chart below. I am looking into the number of APIs which provides the summary of historical data to generate the line chart below. Any idea/pointers would be really helpful. As a solution, I am planning to display the same chart as in coinmarketcap: https://s3.coinmarketcap.com/generated/sparklines/web/7d/2781/1.svg -
Django website not showing dictionary values
I am using VS code for django. I am not sure why but the default django website is not showing the expected output. The output is ignoring the dictionary values. from django.shortcuts import render from django.http import HttpResponse def index(request): context = { 'name': 'Patrick', 'age' : 23, 'nationality':'British', } return render(request, 'index.html', context) ``` <h1> Welcome, {{name}}<br> You are {{age}} years old. </h1> (output in server website) Welcome, You are years old. -
Filter queryset in django select2 widget
Is it possible to filter queryset in Django Select2 forms? I got a form that sends a direct message to the user and I want to have the possibility to filter users. s2forms.ModelSelect2Widget, as I see, selects all instances of User model Now I need t to implement a flag to the User model (allow_direct_messages), and if the user allows sending direct messages, so I need to filter them accordingly. class DirectMessageCreateForm(forms.ModelForm): class Meta: model = DirectMessage fields = ("author", "recipient", "content") labels = { "author": "", } widgets = { "recipient": UsersWidget, "content": forms.Textarea(attrs={ 'class': 'block p-3 w-full text-md bg-gray-50 rounded-lg border border-gray-300 focus:ring-blue-500' ' focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 ' 'dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500', 'placeholder': "Type your message here..." }), "author": forms.TextInput, } class UsersWidget(s2forms.ModelSelect2Widget): search_fields = [ "name__icontains", "email__icontains", ] Maybe someone knows how to make a custom queryset inside ModelSelect2Widget form? Thanks in advance -
Get last object of ManytoMany connected table in Django
I have a Django model like the following: class RFIDInventorySerials(models.Model): serial = models.CharField(max_length=50, blank=True, null=True, default=0) coordinate = models.CharField(max_length=100, blank=True, null=True, default=0) timestamp = models.DateTimeField(default=datetime.now) class RFIDInventory(models.Model): reference_number = models.IntegerField(default=0) serials = models.ManyToManyField(RFIDInventorySerials) and a list of serial such as : s = ['a', 'b', 'c', 'd', 'e'] for every serial I want to get the last time_stamp. How can I do that ? I did: last_seen = [] for i, v in df_hr1['Miss'].iteritems(): last = RFIDInventorySerials.objects.filter(serial=v).last() print("last", last) last_seen.append(last.start) But if the list becomes longer then the loop won't be a solution to this