Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django error 'context must be a dict rather than DataFrame'
I'm working on a translator program. I want the result to appear at the bottom of the original page when the user presses the 'Submit' button. I created a function in 'views.py' and returned the result in the form of a DataFrame (I checked that this Python code itself is fine) and I got an error called 'context must be a dictator than data frame'. I tried several ways to change it to dict format, but it only caused other errors. This is my 'views.py' code and 'urls.py' code. Please let me know if there is anything wrong. views.py class Postview(View): @csrf_exempt def success(request): content = request.POST.get('content') dict = pd.read_csv("C:\\Users\\user\\jeju-dialect-translation\\jeju\\dialect\\dict2.csv", sep=",", encoding='cp949') hannanum = Hannanum() okt = Okt() nouns = hannanum.nouns(content) stem = okt.morphs(content, stem = True) tempt=[] for i in range(0, len(stem)): if (len(stem[i]) == 1): tempt.append(stem[i]) adjective = list(set(stem) - set(tempt)) results = pd.DataFrame(columns = {'siteName', 'contents'}) for i in nouns: x = dict[dict['siteName'] == i] x = x[['siteName', 'contents']] results = pd.concat([results, x], axis = 0) for i in adjective: y = dict[dict['siteName'].str.match(i)] results = pd.concat([results, y], axis = 0) context = results.drop_duplicates() return render(request, 'dialect/trans_suc.html', context) urls.py urlpatterns = [ path('admin/', admin.site.urls), path('dialect/', views.Postview.as_view(), name='main_page'), path('trans/', … -
Best way to change the primary key for a table in an existing project?
I have an existing Django project with some important data in the database. But I would like to change the primary key of the main table. How should I do it? (I am new to Django, so any newbie advice would be appreciated). I can do it the very manual way of: creating a new table as I wanted it to be create a python script importing models library and my specific models create a loop to copy all the entries from the old model into the new do the same with linked models that rely on the old primary key (updating the relation through the new primary key) delete old tables rename new updated tables to match old tables Is my approach correct? or is there a simpler way? Some questions: I know I can create custom "migration files" but I feel like doing it manually with Django creating the migration files would be easier. is that fine? would old connection (relying on unchanged keys) tables automatically recognize the new renamed table? or will something break if I delete the old table? if doing the above, should I remove the "on delete cascade" to avoid linked entries being deleted … -
How to fix home page rendering not working?
So I have urls to redirect the user to certain pages (form and home). I have one which you can click at the top of the home page which successfully redirects you to the form page and I have the same system to bring you back to the home page from the form page except it doesnt seem to work and displays an error. Error Image Here is my home html file which works : <div class="page-title-add-button-div"> <a class="page-title-add-button-link" href="/form"> + </a> </div> Here is my form file which doesnt work : <div class="page-title-add-button-div"> <a class="page-title-add-button-link" href="/home"> + </a> </div> Here is my views file : def home(request): litinfo = info.objects.all() return render(request, 'home.html', {'litinfo': litinfo}) def form(request): return render(request, 'form.html') And finally here is my urls.py file : urlpatterns = [ path('', views.home, name='home'), path('form', views.form, name='form'), ] Thanks in advance for any solutions, im new to django and just not too sure on how to fix this issue. Edit : I've figured out that when I click on the URL in the form page it sends me to "http://(Numbers, not sure if confidential)/home" instead of "http://(Numbers, not sure if confidential)" which means it doesnt bring me back to … -
Django Subquery is redoing all the work, how to reuse subqueries in django?
The resulting query of the following is horrible. Is there a way to reuse the query or create a raw sql for the same? watches = foo_fighters.annotate(pickup_id=Subquery(boo_event.values("id")[:1]), latest_customs_status=Subquery(boo_event.values("customs_status")[:1]), latest_customs_status_label=Subquery(boo_event.values("customs_status_label")[:1]), latest_hopping_line_status=Subquery(boo_event.values("hopping_line_status")[:1]), latest_hopping_line_status_label=Subquery(boo_event.values("hopping_line_status_label")[:1]), latest_tmf_status=Subquery(boo_event.values("tmf_status")[:1]), latest_tmf_status_label=Subquery(boo_event.values("tmf_status_label")[:1]), latest_lol_status=Subquery(boo_event.values("lol_status")[:1]), latest_lol_status_label=Subquery(boo_event.values("lol_status_label")[:1]), latest_bright_status=Subquery(boo_event.values("bright_status")[:1]), latest_bright_status_label=Subquery(boo_event.values("bright_status_label")[:1]), latest_ctf_status=Subquery(boo_event.values("ctf_status")[:1]), latest_ctf_status_label=Subquery(boo_event.values("ctf_status_label")[:1]), latest_love_status=Subquery(boo_event.values("love_status")[:1]), latest_love_status_label=Subquery(boo_event.values("love_status_label")[:1]), ) -
Django pages with similar structure but different components
I have a main webpage that displays and lists all the fruits (with description, price, etc) I sell. Now, I would like to have another page .../discount which displays and list all the fruits which are True for is_discount in one of my models. Essentially, the .../discount page is just a subset of the main page. They have the same page structure and everything, except the listings in .../discount page are discounted fruit items, whereas the mainpage can have discounted and non-discounted fruit items. How would I go about tackling this problem? Thanks in advance. -
Reverse for 'edit_blog_post' with arguments '('',)' not found
I am trying to create a way to edit individual blog posts from their individual html. Here are the relevant files and trace back. I am somewhat understanding that the issue lies in blog_post.id being due to the fact that blog_post has not carried over from the for loop on blog_posts.html. I have read up on others having this issue and they all structured their pages to have the edit button being inside the original for loop, which makes sense in hindsight. BUT now that I have run into this issue, I'm determined to understand how I can solve it without going back and restructuring my pages to align with the others I saw. urls.py from django.urls import path from . import views app_name = 'blogs' urlpatterns = [ # Home page path('', views.index, name='index'), path('blog_posts/', views.blog_posts, name='blog_posts'), path('blog_posts/<int:blog_post_id>/', views.blog_post, name='blog_post'), path('new_blog_post/', views.new_blog_post, name='new_blog_post'), path('edit_blog_post/<int:blog_post_id>/', views.edit_blog_post, name='edit_blog_post'), ] views.py from .models import BlogPost from .forms import BlogPostForm def index(request): """Home page for Blog.""" return render(request, 'blogs/index.html') def blog_posts(request): """Show all Blog Posts.""" blog_posts = BlogPost.objects.order_by('date_added') context = {'blog_posts': blog_posts} return render(request, 'blogs/blog_posts.html', context) def blog_post(request, blog_post_id): """Show details of an individual blog post.""" blog_post = BlogPost.objects.get(id=blog_post_id) title = blog_post.title id … -
How to make the a variable within a Django template's conditional show up every time it needs to?
I have a Django template with text that surrounds a variable. I want both the text and variable to show up when a listing is within the CloseListing model or if request.POST.get('close') has occurred. Currently, the variables show up once request.POST.get('close') has occurred but disappears if you go to another page within the web application and then return. The text surrounding it is always visible. I think the problem is with my logic but am unsure how to fix this. Does anyone know how to fix this? views.py @login_required(login_url='login') def listing(request, id): #gets listing listing = get_object_or_404(Listings.objects, pk=id) sellar = listing.user #close listing code if sellar == request.user: closeListingButton = True else: closeListingButton = False closeListing = '' try: has_closed = get_list_or_404(CloseListing, Q(user=request.user) & Q(listings=listing)) except: has_closed = False if has_closed: closeListing = False else: closeListing = True if request.method == "POST": #close listing code if request.POST.get('close'): CloseListing.objects.create(user=request.user, listings=listing) closeListing = True closeListingButton = False add_or_remove_watchlist = True winning_bid = Bids.objects.aggregate(Max('bid')) winning_bid = Bids.objects.latest('bid') winner = winning_bid.user return render(request, "auctions/listing.html",{ "auction_listing": listing, "comments": comment_obj, "bids": bid_obj, "closeListingButton": closeListingButton, "closeListing": closeListing, "closedMessage": "This listing is closed.", "winner": winner }) return render(request, "auctions/listing.html",{ "auction_listing": listing, "closeListingButton": closeListingButton, "closeListing": closeListing }) html {% … -
My ajax request in django redirects to another page containing my response data after submit
after submiting my ajax request, it redirects me to another empty page containing my returned data i wanted it to remain in the same page after submiting the form. here is my view VIEWS.PY def LikePost(request,pk,slug): model=Post post=Post.objects.get(pk=pk,slug=slug) #if request.is_ajax(): is_like=False for like in post.post_likes.all(): if like == request.user: is_like=True break if not is_like: post.post_likes.add(request.user) if is_like: post.post_likes.remove(request.user) notify=Notification.objects.create(notification_type='LP',user=post.publisher,sender=request.user,text_preview=" some one liked your post") notify.save() likes_count=post.post_likes.count() data={ 'likes_count':likes_count, } return HttpResponse(json.dumps(data),content_type='application/json' ) and my form <form method="POST" class="likeForm" action="{% url 'like-post' post.id post.slug %}" > {% csrf_token %} <input type="hidden" value="{{ request.path }}" name="next"> <button type='submit'>like</button> and my ajax call $.each('.likeForm').on('submit', function(event){ event.preventDefault(); event.stopPropagation(); $.ajax({ type:'POST', url:$('.likeForm').attr('action'), data:{ csrfmiddlewaretoken:"{{ csrf_token }}", datatype:'json', cache:false, async:true, }, success:function(data){ $.each('.counter').text(data.likes_count) }, failure: function(){ } }) return false }) keeps redirecting to an empty page any help for this? -
How can show categories products in home page?
I want to show my all products row by row on the home page category-wise. Suppose, before starting a new row will have a heading(category name) and then will show all products according to the product category and then again will be starting a new row with a heading according to category. How can I do it? I applied the 3/4 methods but didn't work. Bellow, I've shown one of the methods. It doesn't work properly. Please help me. views.py: def home(request): all_products = Products.objects.all() context ={ "all_products":all_products, } return render(request,'home.html', context) model.py: class Category(models.Model): title = models.CharField(blank=True, null=True, max_length = 100) def __str__(self): return str(self.title) class Products(models.Model): product_image = models.ImageField(blank=True, null=True, upload_to = "1_products_img") product_title = models.CharField(blank=True, null=True, max_length = 250) product_price = models.IntegerField(blank=True, null=True) offer_price = models.IntegerField(blank=True, null=True) created_date = models.DateTimeField(blank=True, null=True, auto_now=True) product_category = models.ForeignKey(Category, related_name="categoty_related_name", on_delete=models.CASCADE, blank=True, null=True) context_processors.py: from .models import Category def categories(request): return {"categories":Category.objects.all()} template: {% for products in all_products %} <h4 class="text-start montserrat_alternates_font ">{{products.product_category}}</h4> <hr> <!--- product card ---> <div class="col mb-5"> <div class="card h-100"> <!-- Sale badge--> {% if products.offer_price != None %} <div class="badge bg-dark text-white position-absolute" style="top: 0.5rem; right: 0.5rem"> SALE </div> {% endif %} <!-- Product image--> <img … -
Django admin: filter by min and max value
I would like to add a filter to my Django admin to filter based on a floating point with range in [0, 1]. Consider the following model: class Color(models.Model): label = models.CharField(max_length=255, unique=True) confidence = models.FloatField(null=True) The value of confidence is always between 0 and 1. I found pretty easy to add a filter based on the label attribute: class AnnotationAdmin(admin.ModelAdmin): list_filter = ( ("color__label", custom_titled_filter('Color')), # ("color__confidence", custom_titled_filter('Color Confidence')), ) How can I add a filter to select the maximum and minimum values for the color confidence? E.g. select all the colors with confidence between 0.5 and 0.6. As of now, the only solution I found is to create two different filter classes extending admin.SimpleListFilter and use one to select the maximum and another one to select the minimum. Is there anything easier, maybe supported by django out of the box? -
Error in making POST request to django API
From post man, I'm trying to make POST request to an order API created using django restframework but I'm getting the following error: product = Product.objects.get(id=i['product']) TypeError: string indices must be integers The specific point where the error is located is specified in the error but I find difficulty constructing VALID json for the request body. Here is how I'm making the request on postman: { "orderItems":{ "product": {"name":"abc", "brand":"def", "image"www.example.com/img", "description":"xyz", "price":"50"}, "qty":"2", "price":"200" }, "shippingAddress": { "address":"abc", "city":"B", "postalCode":"12345", }, "paymentMethod":"monify", "itemPrice":"100" } Here is the program: class Product(models.Model): category = models.CharField(max_length=50, choices=Categories.choices, default=Categories.medications) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name="user_product", null=True) name = models.CharField(max_length=150) brand = models.CharField(max_length=255, default="brand") productClass = models.CharField(max_length=50, null=True, blank=True) image = models.ImageField(upload_to="images/products/") label = models.CharField(max_length=254, default='', blank=True, null=True) price = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True) stock = models.IntegerField(null=True, blank=True, default=0) dateCreated = models.DateTimeField(auto_now_add=True) class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name="user_order", null=True) paymentMethod = models.CharField(max_length=200, null=True, blank=True) dateCreated = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.dateCreated) models.py class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) image = models.CharField(max_length=200, null=True, blank=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200, null=True, blank=True) qty = models.IntegerField(null=True, blank=True, default=0) price = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True) def __str__(self): return str(self.name) The view I', trying to … -
Django: name 'filter_name__icontains' is not defined
I am working on custom filter in my Django (DRF) app. Basic filtering (iexact) is working: queryset = queryset.filter(**{filter_name: term.get(filter_name)}) # OK But I want to filter CharFields with icontains logic: queryset = queryset.filter(**{filter_name__icontains: term.get(filter_name)}) # ERROR Error text NameError: name 'filter_name__icontains' is not defined Question: how can I support icontains filtering in my function? My code from django.db.models import QuerySet, CharField from rest_framework.filters import BaseFilterBackend from rest_framework.request import Request class AbstractFilterBackend(BaseFilterBackend): @staticmethod def __execute_default_filters(queryset, terms: list): for term in terms: filter_name = next(iter(term.keys())) if hasattr(queryset.model, filter_name): if queryset.model._meta.get_field(filter_name).__class__ is CharField: queryset = queryset.filter(**{filter_name__icontains: term.get(filter_name)}) else: queryset = queryset.filter(**{filter_name: term.get(filter_name)}) return queryset -
Django nested forms for foreign keys
I have the following Django models: class Color(models.Model): label = models.CharField(max_length=255, unique=True) class ColorAnnotation(models.Model): color = models.ForeignKey(Color) confidence = models.FloatField() def __str__(self): return f"{self.color.label} {round(self.confidence, 2) if self.confidence else None}" class Annotation(models.Model): color = models.ForeignKey(ColorAnnotation) Since I have a lots of records, Django Admin got really slow when loading a single record of the model Annotation because it tried to load all the possible values of __str__ for ColorAnnotation. I optimized using prefetch_related and select_related but it didn't work. I solved this creating a custom froms.ModelForm: class AnnotationForm(forms.ModelForm): color = forms.ChoiceField(required=False, choices=Color.objects.values_list('id', 'label')) class Meta: model = Annotation fields = '__all__' class AnnotationAdmin(admin.ModelAdmin): list_display = ("id", "color") list_filter = ( ("color__color__label", custom_titled_filter('Color')) ) form = AnnotationForm def get_queryset(self, request): queryset = super().get_queryset(request) return queryset.prefetch_related( 'color__color', ).select_related( 'color', ).all() This works well, but it doesn't show the attribute confidence of the ColorAnnotation instance of a given Annotation: . I would like to change this so that I have the dropdown menu for the Color, but with option of changing the confidence too. I was wondering if there is a way to create a custom forms.ModelForm for the model ColorAnnotation and use it as a nested form into AnnotationForm. -
Bundle input validation and business logic errors
We recently started to replace a long-running application with a new app using a modern technology stack, drf in the backend. So, everything is new, we were justin starting, but most reqirements are old. Today we got the requirement, that the client should display all field-validation errors and business logic validation errors (if possible to process) at the same time to the user when he was trying to do write operations. Additional note is that further validations are still to come and all need to run in one call. In summary: one post/put operation with a single response, which was heavily processed and contains all validation and business logic errors. Sounded uncomfortably to me or is this easy to implement? First thought was that we can write a custom_exception_handler which waits for a ValidationError, runs all business validations and enriches the response. But this handler will grow with each endpoint which needs extra validation. (And the current application is big.) Is there a better way? How do you feel about it? Does this violate good practices? Maybe the client should do field validation too and do async calls to extra validation endpoints so that it can guide the user to … -
get name attr value for formset with appropriate prefix and formset form index
I am manually displaying modelformset_factory values in a Django template using the snippet below. One of the inputs is using the select type and I'm populating the options using another context value passed from the view after making external API calls, so there is no model relationship between the data and the form I'm trying to display. view my_form = modelformset_factory(MyModel, MyModelForm, fields=("col1", "col2"), extra=0, min_num=1, can_delete=True,) template {{ my_form.management_form }} {% for form in my_form %} <label for="{{ form.col1.id_for_label }}">{{ form.col1.label }}</label> {{ form.col1 }} <label for="{{ form.col2.id_for_label }}">{{ form.col2.label }}</label> <select id="{{ form.col2.id_for_label }}" name="{{ form.col2.name }}"> <option disabled selected value> ---- </option> {% for ctx in other_ctx %} <option value="{{ ctx.1 }}">{{ ctx.2 }}</option> {% endfor %} </select> {% endfor %} The other_ctx populating the select option is a List[Tuple] I am trying to get the name value for the col2 input using {{ form.col2.name }} but only col2 is getting returned instead of form-0-col2. I could prepend the form-0- value to the {{ form.col2.name }} but wondering if: I could do the above automatically? I'm assuming the formset should be aware of the initial formset names with appropriate formset index coming from the view. Is there … -
Django Assign json to model object
I have this function: # create a function to upload an object one to one given a json def upload_object_values(model, json_values): if json_values: # the json values contain key value that match to the model # use a copy to avoid runtime error dictionary changing size for json_value in json_values.copy(): # remove all ids in model copy if json_value[-3:] == '_id' or json_value == 'id': json_values.pop(json_value) # copy the object values only # TODO: ASSIGN json_values to the model object # save # model.save() sample json_values: {'id': 1, 'notes': 'hello', 'name': 'world', 'phone': None, 'foreign_id': 2} sample cleanedjson_values (removed id and foreign keys): {'notes': 'hello', 'name': 'world', 'phone': None} How do I assign these values to the model that I have with each key being a field with the same name in my model? -
Code inside Django template if statement appears all the time
I have a Django template that contains a message with a variable, but the words that are not in the variable appear all the time. I think it has something to do with the conditional if closeListing == True. I explicably state when I want it to be True, so I don't know what's happening. views.py @login_required(login_url='login') def listing(request, id): #gets listing listing = get_object_or_404(Listings.objects, pk=id) sellar = listing.user #close listing code if sellar == request.user: closeListingButton = True else: closeListingButton = False closeListing = '' try: has_closed = get_list_or_404(CloseListing, Q( user=request.user) & Q(listings=listing)) except: has_closed = False if has_closed: closeListing = False else: closeListing = True if request.method == "POST": #close listing code if request.POST.get('close'): CloseListing.objects.create(user=request.user, listings=listing) closeListing = True closeListingButton = False add_or_remove_watchlist = True winning_bid = Bids.objects.aggregate(Max('bid')) winning_bid = Bids.objects.latest('bid') winner = winning_bid.user return render(request, "auctions/listing.html",{ "auction_listing": listing, "comments": comment_obj, "bids": bid_obj, "closeListingButton": closeListingButton, "closeListing": closeListing, "closedMessage": "This listing is closed.", "winner": winner }) return render(request, "auctions/listing.html",{ "auction_listing": listing, "closeListingButton": closeListingButton, "closeListing": closeListing }) listing.html {% if closeListing == True %} <div>{{ closedMessage }} <br> {{ winner }} has won the auction! </div> {% endif %} -
Setting the expiry of access token using drf-social-oauth2
So I am using DRF, React and drf-social-oauth2 for Google Login and I want to set the expiry time of the access token given after Google login. I tried using the same settings as OAuth Toolkit OAUTH2_PROVIDER = { 'ACCESS_TOKEN_EXPIRE_SECONDS': 10, 'OAUTH_SINGLE_ACCESS_TOKEN': True, 'OAUTH_DELETE_EXPIRED': True } which means expiry should be 10 seconds, but the response is, access_token: "d2UAuxY5uv9sEtlE60pgMeuLqTuJV1" expires_in: 33352.043033 refresh_token: "fhm8Zy88HaitJF6q3QEwmSEd3bC1wU" scope: "read write" token_type: "Bearer" the expires_in is wierd. What does this mean? And how do I set the expiry for drf-social-oauth2, can't find any help regarding this anywhere -
NFT payment gateway django
How to accept NFTs on django site? Right now there are two models: class Product(models.Model): ''' Product represents what a user can purchase to fund their wallet''' TYPE_CHOICES = ((-1, "NONE"),(0,"BTC"),(1,'NFT'), (2, "FIAT"), (3, "DUMB")) type = models.IntegerChoices(choices = TYPE_CHOICES, default = -1, blank = False) price = models.FloatField(default = 0.00, null=False, blank=False) title = models.CharField(max_length=50) # TODO qr_code = models.ImageField(upload_to='qr_codes', blank=True) description = models.TextField() # active = models.BooleanField Whether a product is active or not objects = ProductManager() class Invoice(models.Model): ''' The invoice represents a transaction when a user purchases a product''' STATUS_CHOICES = ((-1,"Not Started"),(0,'Unconfirmed'), (1,"Partially Confirmed"), (2,"Confirmed"), (3, "Wallet Credited")) user = models.ForeignKey(User, on_delete = models.CASCADE) product = models.ForeignKey("Product", on_delete=models.CASCADE) status = models.IntegerField(choices=STATUS_CHOICES, default=-1) order_id = models.CharField(max_length=250) address = models.CharField(max_length=250, blank=True, null=True) btcvalue = models.IntegerField(blank=True, null=True) received = models.IntegerField(blank=True, null=True) txid = models.CharField(max_length=250, blank=True, null=True) rbf = models.IntegerField(blank=True, null=True) created_at = models.DateField(auto_now=True) objects = InvoiceManager() We want to accept NFTs as one sort of product such that users are able to send us NFTs and the backend credits their accounts with those NFTs. Is there a good package/service that does this? -
DRF SERILAZATION
I serialize the field named "product" with ProductSerializer() inside OrderItemSerializer(). That's what I want. class OrderItemSerializer(serializers.ModelSerializer): product = ProductSerializer() class Meta: model = models.OrderItem fields = ('id','order', 'product', 'quantity') The output is; But when I try to request with POST Method needs to send Product as a dictionary, just giving the id value is not enough. How can I POST by sending only the id value? -
Template not rendering Django (NoReverseMatch)
I am not exactly sure what the issue is but I have this code in my project that once I select a date it will bring up a table with the name of students in my classroom but Django keeps telling me that there isnt NoReverseMatch. i have double check and everything is fine but not sure why it not working. ERROR SHOWN Reverse for 'attendance-page' with arguments '('',)' not found. 1 pattern(s) tried: ['attendance/(?P[0-9]+)\Z'] urls.py path('attendance_class', views.attendance_class, name='attendance-class'), path('attendance/<int:classPK>', views.attendance, name='attendance-page'), path(r'attendance/<int:classPK>/<str:date>',views.attendance, name='attendance-page-date'), path('save_attendance', views.save_attendance, name='save-attendance'), views.py @login_required def attendance_class(request): classes = Room.objects.all() context = {} context['classes'] = classes return render(request, 'school/attendance_page.html', context) @login_required def attendance(request, classPK=None, date=None): _class = Room.objects.get(id=classPK) students = Student.objects.filter(id__in=ClassStudent.objects.filter(classIns=_class).values_list('student')).all() context = {} context['class'] = _class context['date'] = date att_data = {} for student in students: att_data[student.id] = {} att_data[student.id]['data'] = student if not date is None: date = datetime.strptime(date, '%Y-%m-%d') year = date.strftime('%Y') month = date.strftime('%m') day = date.strftime('%d') attendance = Attendance.objects.filter( attendance_date__year=year, attendance_date__month=month, attendance_date__day=day, classIns=_class).all() for att in attendance: att_data[att.student.pk]['type'] = att.type print(list(att_data.values())) context['att_data'] = list(att_data.values()) context['students'] = students return render(request, 'school/attendance_control.html') def save_attendance(request): resp = {'status': 'failed', 'msg': ''} if request.method == 'POST': post = request.POST date = datetime.strptime(post['attendance_date'], '%Y-%m-%d') year = … -
Django Backend with two different data sources
I am working on a react web app ( I am a begginer) that'll enable the user to store new data rows and edit/udpate old data rows. The reference data, for the react form, is stored in ADLS Gen1 parquet format and The app will write data to a different ADLS location in parquet format. The question is: How can I setup the django backend with these two different data source, I want to read some reference data from ADLS Gen1 and write and edit into another ADLS in parquet format. Any help,litreture or blog-post related to this would be appreciated? Thanks -
Is it posible to listen to an MQTT server and publish with Websocket (endpoint) from our own server
I have got an mqtt consumer that listens to a topic and based on that, I used to send a response on another topic. However now I would like to create a Websocket Secure wss endpoint where i could stream this processed information. Could you tell me if it is possible to do that wth mqttasgi library, if yes how. Here I leave the code of my consumer. from mqttasgi.consumers import MqttConsumer from mqtt_handler.tasks import processmqttmessage import json class MyMqttConsumer(MqttConsumer): async def connect(self): await self.subscribe('application/+/device/+/event/up', 2) await self.channel_layer.group_add("stracontech", self.channel_name) async def receive(self, mqtt_message): print('Received a message at topic:', mqtt_message['topic']) print('With payload', mqtt_message['payload']) print('And QOS:', mqtt_message['qos']) dictresult = json.loads(mqtt_message['payload']) jsonresult = json.dumps(dictresult) processmqttmessage.delay(jsonresult, mqtt_message['topic']) pass async def publish_results(self, event): data = event['result'] await self.publish("stracontech/procesed/"+event['result']['device_id']+"/result", json.dumps(data).encode('utf-8'), qos=2, retain=False) async def disconnect(self): await self.unsubscribe('application/+/device/+/event/up') Pd: @Santiago Ivulich maybe you can help me with that. -
django queryset sorting by fields
i have this model: class ProgrammingQuestionAnswer(models.Model): programming_question = models.ForeignKey(ProgrammingQuestion, on_delete=models.CASCADE, related_name='programming_question_a', null=True, blank=True) time = models.DateTimeField(default=timezone.now) score = models.IntegerField(null=True, blank=True, default=0) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='writer_answer_programming_question', null=True, blank=True) accept = models.BooleanField(default=False) file = models.FileField(upload_to=content_file_name) result = models.TextField(null=True, blank=True) file_name = models.CharField(max_length=500, null=True, blank=True) max_score = models.IntegerField(null=True, blank=True, default=0) I want to write a query for get users who solve more questions(have more accept=True) and those who are equal are sorted by time(time field) Thanks -
django the print() is not working in the terminal
I am currently doing Django project with sqlite3 with ORM method. I am unable to debug as print() is not working in the terminal even if I put print() function in views.py. I checked in python shell, the queryset is working. In views.py from django.shortcuts import render,redirect from .models import BookBoardModel def index(request): all_books = BookBoardModel.objects.all() print(all_books) for item in all_books: print(item.title) context = {'all_books': all_books} return render(request, 'category_books_page/index.html', context) The terminal shown with warning sign and not giving print(): Due to this, the variable all_books are not properly rendered in the index.html which will not generate any objects in index.html