Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there any ways to combine two rows of table into one row using Django ORM?
I have a table which has columns named measured_time, data_type and value. In data_type, there is two types, temperature and humidity. I want to combine two rows of data if they have same measured_time using Django ORM. I am using Maria DB Using Raw SQL, The following Query does what I want to. SELECT T1.measured_time, T1.temperature, T2.humidity FROM ( SELECT CASE WHEN data_type = 1 then value END as temperature , CASE WHEN data_type = 2 then value END as humidity , measured_time FROM data_table) as T1, ( SELECT CASE WHEN data_type = 1 then value END as temperature , CASE WHEN data_type = 2 then value END as humidity , measured_time FROM data_table) as T2 WHERE T1.measured_time = T2.measured_time and T1.temperature IS NOT null and T2.humidity IS NOT null and DATE(T1.measured_time) = '2019-07-01' Original Table | measured_time | data_type | value | |---------------------|-----------|-------| | 2019-07-01-17:27:03 | 1 | 25.24 | | 2019-07-01-17:27:03 | 2 | 33.22 | Expected Result | measured_time | temperaure | humidity | |---------------------|------------|----------| | 2019-07-01-17:27:03 | 25.24 | 33.22 | -
Understanding Django localization in templates
I am trying to use two languages in my website, my native, and an english one. I followed the django documentation, from where I copied the code. I have the locale folders and files set up. When I open the site, it already sets the default language to Slovene, which should be English instead, and I don't know why. The main.html looks like this when I open the site: <html xmlns="http://www.w3.org/1999/xhtml" xmlns="http://www.w3.org/1999/html" xmlns:height="http://www.w3.org/1999/xhtml" lang="sl" > If I understand correctly, the lang="sl" should be lang="en", and I do not know why it defaults to Slovene. Even when I use the form, it shows me both choices (English and Slovene), but when I select English, and click Go, it just refreshes the page, but doesn't change the language. The current language (Slovene) still stays selected, so I'm guessing that somewhere the correct language doesn't get selected. I'm also confused as to why it doesn't default to English when I start the server. Can anyone provide some insight or point me in the right direction? settings.py LANGUAGE_CODE = 'en-gb' TIME_ZONE = 'Europe/Ljubljana' USE_I18N = True USE_L10N = True USE_TZ = True LOCALE_PATHS = [ os.path.join(BASE_DIR, "locale"), ] ugettext = lambda s: s LANGUAGES … -
How do I add points of skill tags for every correct main questions and sub questions?
enter image description here consider a folder which contains main questions and subquestions. Teacher create those questions with skill tags( core skill, knowledge skill, exam skill, foundation skill). Now student is taking his exam, first he will get main question, if he do well we have to add the points to that main question. For suppose he did mistake the main question, we have to give sub questions which relates to main question it also has skill tags. If he do correct here we should add the points of main and subquestions. -
how to test django modal details?
i'd like to test this little part of code : @staff_member_required() def prestation_details_modal(request, uuid): p = get_object_or_404(Prestation, uuid=uuid) return TemplateResponse(request, "includes/modal /prestation_modal.html", {'prestation': p}) i ever tested something like : def test_resp_temp_page(self): url = reverse('index') response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertTemplate(response, 'include/modal /mission_modal.html') thx for help ! -
Calling View in API Request Factory when testing in Django Rest Framework
Whenever we test an API in Django Rest Framework using API Request Factory why do we call the view when we are already passing the url . Look at the following code for better understanding . request = self.factory.post("/api/v1/menu/", data) views = MenuResource.as_view({"post": "post"}) response = views(request) response.render() self.assertEqual(201, response.status_code) In the above code we are calling the url as well as calling the view . View is being called for rendering the view on the url but that is not what my use case is . I just want to test the response code . Is there a way of getting the response code without rendering the view as that is an over kill for my use case . I have looked for other methods except for using API Request Factory but i just wanted to know why does API Request Factory need to call the view . Is there any advantage in comparison to other API Testing modules present in Django Rest Framework .enter code here -
How do I create a button for adding a time in the Django Form Template?
How do I create a button for adding a time in the Django Form Template? form is this class TodoForm(forms.ModelForm): dead_line = forms.SplitDateTimeField(widget=widgets.AdminSplitDateTime, initial=datetime.datetime.now()) class Meta: model = Todo fields = ['title', 'content','classification','dead_line'] widgets = { 'content': SummernoteWidget(), } form.html is this <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form | safe }} <button type="submit" class="btn btn-primary float-right btn-block">Submit</button> </form> result question : What if I want to create an hour button or an extra day button? Do I need to use a widget? Should I create a js button? Thank you very much for giving me specific examples. tanks for reading ~! -
I want to show a fixed value in a field in forms.py
I am making a model form for mock up website, asking for seller information. I want the field country to be fixed to a certain country and the seller cannot change it.Assuming the website do not operate in any other country. How can i show the field as fixed and not changeable showing a fixed country value ? This is my model form: class seller(forms.Form): gst_number = forms.CharField(label='GST-Number',max_length=100, validators=[GST_validator]) add_line_i = forms.CharField(label='Address Line 1',max_length=100) city= forms.CharField(required = True,widget = forms.Select(choices=indiancities)) country = forms.CharField(required = True) I am getting it like this : I want it to be like this and country should not be editable. -
How to keep track of history of transactions and rollback when needed?
Let's say I'm maintaining an Activity log of a user in UserActivity model. class UserActivity(models.Model): description = models.TextField() query = models.TextField() How to implement and what fields are required on this model, so that I would be able to rollback a transaction in history at any time? What are its cons and dependencies? I know transaction.atomic. Think of this as doing a transaction a few days ago and rolling back today. -
Tests fails after import external library
Hey I'm facing kind of weird problem. I have Django project with 3 applications: core mturk_manager cognito_admin The mturk_manager is the new one. When I run tests only for this application using command python manage.py test mturk_manager or even with core application together python manage.py mturk_manager core everythings passes as expected. Problem is with application cognito_admin when I run all tests together some of the tests from my new application mturk_manager fails. I was debugging the problem for such a long time :) and found problem: In cognito_admin I'm importing external package from moto library from moto import cognito_idp even if I have commented out all tests from cognito_admin tests still fails in other application. I really need this package its really usefull. Any ideas how to solve this problem ? -
Delete data form after sending post request
I'm coding user management page. In page, I have form to add new user with post request and delete button with comfirmation form. I add new user successfully, page is reloaded, then I delete any account, but data in form I sent request to create new user is sent again with new user ID. How to fix? -
Why post request is working on django 2.2.1 but in version 1.11.20 fails?
When I am trying to do a post request in my remote machine through the view file presented below I'm getting an HTTP 400 bad request, however, when I do the same using my local machine it works perfectly. Here are the most important details of each machine according to my understanding: Local machine django == 2.2.1 drf == 3.9.4 python == 3.7 Remote machine (Using docker on an EC2 machine) django == 1.11.20 drf == 3.9.4 python == 2.7 I've already check that drf 3.9.4 still compatible with python 2. https://www.django-rest-framework.org/community/release-notes/ views.py from django.shortcuts import render from django.http import HttpResponse from django.urls import reverse from .models import irrigation, moisture from .serializers import IrrigationSerializer from rest_framework import viewsets from rest_framework import status from rest_framework.response import Response from rest_framework.decorators import api_view, action class irrigationValues(viewsets.ModelViewSet): queryset = irrigation.objects.all() serializer_class = IrrigationSerializer def list(self, request): serializer = self.serializer_class(self.queryset, many = True) return Response(serializer.data) def dashboard(request): irrigations = irrigation.objects.all() return render(request, 'dashboard.html',{'irrigations':irrigations}) @api_view(['POST']) def addIrrigation(request): addIrrigation = IrrigationSerializer(data=request.data) if addIrrigation.is_valid(): addIrrigation.save() return Response({"data":"Value added"},status = status.HTTP_201_CREATED) else: error_details = [] for key in addIrrigation.errors.keys(): error_details.append({"field": key, "message": addIrrigation.errors[key][0]}) data = { "Error": { "status": 400, "message": "Your submitted data was not valid - please … -
What should be the broker url for redis on production mode in Django
When I'm trying to run my Django project on VPS, it works perfectly but the problem is Celery broker. on my local mechine I used this code on tasks.py and celery.py app = Celery('imgmanipulation', backend='redis', broker='redis://localhost') How should I change this for production uses? Suppose I've a hosting which is: id: root@167.78.250.252 pass: farid.19 Any type of help will be appreciated. Thank you :) -
python how to dump dynamic create class to file
I had been dynamic create a python meta class I want to dump it to a python file cls = type("ClsName", (object, ), attr) code = xxxGetSource(cls) writeToFile(code, "moduleName/ClsName.py") I need this, because when django makemigrations, it need to found the metaclass for model, but my model metaclass was dynamic generate class XXXModel(GenerateMetaCls({ .... }), models.Model): pass -
How to startup telegram bot in django correctly
I am trying to connect a telegram bot (webhook) to my project. In the project/tbot.py I have method tbot_startup(): dp = DjangoTelegramBot.dispatcher dp.add_handler(CommandHandler("start", tbot_hello)) logger.info('TELEGRAM BOT STARTED') In the file, wsgi.py: application = get_wsgi_application() tbot_startup() # It doesn't matter before or after the "application" var After launching the application (manage.py runserver), there is an entry in the log: IndexError: list index out of range It's about this line: https://github.com/JungDev/django-telegrambot/blob/master/django_telegrambot/apps.py#L47 I've tried to fix it, with this code. bot = DjangoTelegramBot bot.bot_tokens.append(TOKEN_FROM_SETTINGS) dp = bot.dispatcher dp.add_handler(CommandHandler("start", tbot_hello)) Now the application starts, but the bot does not work. At the same time, if you change something in the project, django will re-read the files and the bot will restart and work. I don't know how to fix it. Please, help me startup bot with main web-application correctly. -
I am not able to load the staticfiles in my templates. What am I doing wrong?
I need to incorporate css in my templates to help them look better, but inspite of adding the static url and root, I am just not able to load it in my template. I am attaching the relevant code here. Please tell me what am I doing wrong. Thanks in advance. settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR,'templates') STATIC_DIR = os.path.join(BASE_DIR,'static') STATIC_URL = '/static/' STATIC_ROOT = [STATIC_DIR,], index.html <!DOCTYPE html> {% load staticfiles %} <html lang="en"> <head> <link href="{% static 'css/index.css' %}"> </head> -
No operator matchesYou might need to add explicit type casts django postgres
i was trying to access artist_type based on id when i try domain.com/artist/3 i get this error: operator does not exist: character varying = integer LINE 1: ...main_site_artist" WHERE "main_site_artist"."artist_type" = 3 ^ HINT: No operator matches the given name and argument types. You might need to add explicit type casts. as i can see in table there are 2 artist_type with id 3. as i am filtering artist based on artist_type this is models.py: from django.db import models class artist(models.Model): CHOICES = ( (0, 'celebrities'), (1, 'singer'), (2, 'comedian'), (3, 'dancer'), (4, 'model'), (5, 'Photographer') ) artist_name = models.CharField(max_length = 50) artist_type = models.IntegerField(choices = CHOICES) description = models.TextField(max_length = 500) def __str__(self): return self.artist_name this is my database table: celeb=# select * from main_site_artist; id | artist_name | artist_type | description ----+-------------+-------------+---------------- 1 | test | 1 | test 2 | aka | 3 | aka 3 | test2 | 4 | aka 4 | sonu | 3 | aka moth 5 | norma | 0 | its norma here urls.py: from django.urls import path from . import views urlpatterns = [ path('',views.index, name='mainsite-index'), path('about/',views.about, name='mainsite-about'), path('contact/', views.contact, name='mainsite-contact'), path('artist/<int:artist_type>/',views.talent, name='mainsite-talent'), path('book_artist/', views.artist_booking, name="artist_book") ] views.py: def talent(request, … -
Please help me in building an ecommerce platform
I had to build an ecommerce platform in Django which is like myus.com, basically it should help you purchase inexpensive products of a country directly by having a store in that country. I also wanna work with API'S like taboo.com so people can interact in their own native language. I need help about how to start this project? Need a developer friend who can mentor me? I need help how to do it fast and where to find help? Some other help which you may think will be useful. -
Add Username and Client IP Address in the Django manage.py runserver default output
Could anybody please help me, how to add Username and Clinet IP Address in the Django manage.py runserver default output. currently I am seeing: [01/Jul/2019 11:34:27] "GET / HTTP/1.1" 200 237 expected result: [pid: 10|app: 0|req: 1/2] 10.176.123.254 (Logged in username/email) {86 vars in 4942 bytes} [Mon Jul 1 06:08:37 2019] GET / => generated 291 bytes in 1160 msecs (HTTP/1.1 200) 7 headers in 250 bytes (1 switches on core 0) -
How do I add points of skill tags getting for every correct main question and subquestions?
I would like to add the points of skill tags(1,2,3,4 consider as 4 skills) each of these skill tag (any number of skills)has 1 point and add each tag to main questions and sub questions. Once the student has give the correct answer for the question(main questions and sub questions), it should add the points to the main question and sub questions(if student gave correct answer to main question it redirects to next main question instead of sub question)using the Django Rest Framework with one API call. How do i can save it. Thanks! -
How can I implement individual django session for individual users visiting my page without user registration?
I am making a restaurant-ordering website where customers open the site from their own smartphone and order food. I don't want them to have their own user accounts but the website must recognize these users(from cookies or something). In short, different users must have their own sessions provided they open the website from their devices. Is this possible in Django? -
Getting filtered objects from url by passing correct attributes
I have a Django app with posts and comments with comments linked to the posts with foreign keys. I am unable to fetch the comments for a particular post. I checked my DB to make sure the foreign key is getting added correctly and it is. I tried changing the attribute name multiple times with no effect. My html code in the post detail template for get all comments button is as below: <a class="btn btn-outline-info mb-4" href="{url 'user-comments' object.id}">View Answers</a> My views.py looks like this: class PostCommentListView(ListView): model = Comment template_name = 'blog/comment.html' context_object_name = 'comments' ordering = ['-comment_date'] paginate_by = 7 def get_queryset(self): post = get_object_or_404(Comment, post_id=self.kwargs.get('post_id')) return Comment.objects.filter(post=post).order_by('-comment_date') and the url 'user-comments' is as follows: path('post/', PostCommentListView.as_view(), name='user-comments') I am getting a page not found message. Request URL: http://127.0.0.1:8000/post/15/%7Burl%20'user-comments'%20object.id%7D The current path, post/15/{url 'user-comments' object.id}, didn't match any of these. -
missing 1 required positional argument: 'pk'
I am new in Django and react. I already faced this error at last week and That times its was request URL error. yesterday I changed backend design and now its error happens again. Here is my url=> urlpatterns = [ url(r'^allowances_mas/', AllowanceAPIView.as_view()), url(r'^allowances_mas/(?P<pk>\d+)/$', AllowanceAPIView.as_view()),.... here is my put method that inside view, def put(self,request,pk): save_allowance = get_object_or_404(Allowance.objects.all(),pk=pk) data = request.data.get('allowance') serializer = AllowanceSerializer(instance=save_allowance,data=data,partial=True) if serializer.is_valid(): allowance_saved=serializer.save() return Response({"success":"Allowance '{}' updated successfully".format(allowance_saved.AllowID)}) else: return Response({"fail":"'{}'".format(serializer.errors)}) Here is url request from React axios => axios.put('http://127.0.0.1:8000/api/allowances_mas/1/', { allowance },{ headers: { 'Content-Type': 'application/json' } }) .then(res => { axios.get('http://127.0.0.1:8000/api/allowances_mas/') .then(res=>{ const resallowance=res.data.allowance; this.setState({ allowances:resallowance }); }) }) .catch(err=>{ console.log("error",err); }) .finally(fin=>{ console.log(fin); }) I can do get and post method but put and delete can't because of this error. I set the pk key and why it's still happening the error? Thanks. -
How To Populate Table With Filtered Data in Django
I am attempting to populate a table with a filtered set of data from my Manifests model using a url parameter. I believe that the problem I am having is in the Views.py line manifests = Manifests.objects.all().filter(reference=reference_id) Models.py class Manifests(models.Model): reference = models.ForeignKey(Orders) cases = models.IntegerField() description = models.CharField(max_length=1000) count = models.IntegerField() def __str__(self): return self.description Urls.py url(r'^add_manifest/(?P<reference_id>\d+)/$', add_manifest, name='add_manifest'), Views.py def add_manifest(request, reference_id): if request.method == "POST": form = CreateManifestForm(request.POST) if form.is_valid(): instance = form.save(commit=False) try: order = Orders.objects.get(id=reference_id) except Orders.DoesNotExist: pass instance.reference = order instance.save() return redirect('add_manifest', reference_id=reference_id) form = CreateManifestForm() #manifests = Manifests.objects.all() manifests = Manifests.objects.all().filter(reference=reference_id) context = { 'form': form, 'reference_id': reference_id, 'manifests' : manifests, } return render(request, 'add_manifest.html', context) template (add_manifest.html) <div class="table-responsive"> <!--<table id="manifest_table" class="table table-striped table-bordered table-sm " cellspacing="0"--> <table class="table table-striped table-bordered manifest_table" cellspacing="0" style="width="100%"> <thead> <tr> <th></th> <th style="width:10%;">Ref ID</th> <th style="width:10%;">Cases</th> <th style="width:60%;">Description</th> <th style="width:10%;">Count</th> </tr> </thead> <tbody> {% for manifests in manifests %} <tr> <td> <a href="{% url 'edit_manifest_browse' manifests.pk %}" class="btn btn-default btn-sm" role="button">Edit</a> </td> <td>{{ manifests.reference }}</td> <td>{{ manifests.cases }}</td> <td>{{ manifests.description}}</td> <td>{{ manifests.count}}</td> </tr> {% endfor %} </tbody> </table> </div> <div class="text-center"> <button type="submit" class="btn btn-primary" name="button" align="right">Subit Manifest</button> </div> </div> I want the table to … -
ValueError in a Q&A like app for linking answers to question
I am learning to build a Q&A app using Django. I have set up models for posts, comments and users. I am not able to successfully link the id for the posts to the comments. I have tried linking the comments to the posts by overriding the ModelForm on Django unsuccessfully. This is in my views.py file: class CommentCreateView(LoginRequiredMixin, CreateView): model = Comment fields = ['comment'] def form_valid(self, form): form.instance.author = self.request.user form.instance.post_id = self.kwargs['post_id'] return super(CommentCreateView, self).form_valid(form) My models.py has the model for comments are follows: class Comment(models.Model): cid = models.AutoField(primary_key=True) author = models.ForeignKey(User, on_delete=models.CASCADE) post_id = models.ForeignKey(Post, on_delete=models.CASCADE) comment = models.TextField() comment_date = models.DateTimeField(default=timezone.now) def save(self, *args, **kwargs): super(Comment, self).save(*args, **kwargs) def __str__(self): return self.comment def get_absolute_url(self): return reverse('blog-home') and my url path is as follows: path('comment/', PostCommentListView.as_view(), name='user-comments') I expect the comments to get linked with the posts via the ForeignKey. But when I tried doing the same, I get an error as described below: ValueError at /post/11/comment/ Cannot assign "11": "Comment.post_id" must be a "Post" instance. Exception Value: Cannot assign "11": "Comment.post_id" must be a "Post" instance. -
Django - "fulltext = request.GET['fulltext']" stops working after I add request return render html to function
def count(request): fulltext = request.GET['fulltext'] return render(request, 'count.html') fulltext = request.GET['fulltext'] would stop working after I added return render(request, 'count.html') to the function. If I don't add the return render, it would give me ValueError: Exception Value: The view wordcount.views.count didn't return an HttpResponse object. It returned None instead.