Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using python-lambda-local for django project
I am using python-lambda-local for testing aws-lambda function on local environment. Now I have django project like this /chatbot - /utilities settings.py entry.py and settings.py has entry point def hander For example, I can exec entry.py handler like this $python-lambda-local -f handler -t 5 entry.py event.json However of course it ignores the settings.py, and django environment. What is the bet practice to use django with aws lambda. -
JSON generated by json.dumps() is NOT valid according to RFC 4627
My Django management command generates some JSON. It creates a couple of Python dictionaries, puts them into another dictionary, and uses json.dumps() to convert to JSON. It then tries to save it to JSONField in database using a Django Model. The JSON is not saving due to it not being valid. I checked the JSON with many validators. They all said the JSON is invalid due to: Error: Parse error on line 1: { 'nodes': [{ 'name' --^ Expecting 'STRING', '}', got 'undefined' Eventually I found a validator that said the JSON is Javascript valid but not RFC4627 valid: I can't post the JSON here due to it being sensitive. Is there any reason json.dumps() would generate invalid JSON ? -
DRF serializer parsing comma-delimited string into a list field
Is there a way of modifying how DRF serializers parse incoming request payload? I'm trying to let clients send a comma-delimited list as query parameter but receive it inside the serializer as a list instead but DRF keeps complaining. Right now I'm manually intercepting the request in the view and doing the parsing that field manually before passing it to the serializer which doesn't seem elegant to me. What I'm doing right now class ExampleSerializer(...): list_field = serialzers.ListField(child=serializers.Integerfield(...)) # more fields def view(request): payload = request.GET payload["list_field"] = str(payload.get("list_field", "")).split(",") serializer = ExampleSerializer(data=payload) What I'd prefer (using same serializer as above) def view(request): serializer = ExampleSerializer(data=request.GET) -
How to prevent image bigger than box
I have this code : <div class="row d-flex p-3 mb-4" style="border: 1px solid rgba(0, 0, 0, 0.1)"> {{ content_page.additional_content|safe }} </div> "additional content" is text field (using CKEditor) and can contain images. I want to make it so that the contents can't be bigger than the box or parent. How can I do that? Thanks. -
Group queryset into categories django
I have a Ingredient model and a Shopping model for a shopping list and I would like to group ingredients by their category in the shopping list view. Is there a SQL method to do this or will running for loops for every category in the Shopping model the easiest way to accomplish this? The below image is an example of what I would like to achieve in my shopping list view: #models.py class Ingredient(models.Model): name = models.CharField(max_length=220) category = models.CharField(max_length=50, default="uncategorised") class Shopping(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=220, blank=True, null=True) # users can create their own items not just those in the Ingredient model category = models.CharField(max_length=80, default="uncategorised") -
'RelatedManager' object has no attribute 'payment_status'
I am creating an app in which I want to query all the members and their status. but I am getting this error. these are my both models. class Member(models.Model ): user = models.ForeignKey(Users,verbose_name='User Id', on_delete=models.CASCADE) com = models.ForeignKey(Committee, on_delete=models.CASCADE,verbose_name='Committee Name') class PaymentDetail(models.Model): mem = models.ForeignKey(Member,on_delete=models.CASCADE, related_name='payment_details', verbose_name='Memeber Phone no') com = models.ForeignKey(Committee, on_delete=models.CASCADE,related_name='committee_details',verbose_name='Committee Name') payment_month = models.DateField(default=datetime.now()) payment_status = models.CharField(max_length=16, choices=PAYMENT_DETAILS_CHOICES, default="1") First I am getting all the members by (members.objects.all() then looping over like this for member in members: member.payment_details.payment_status but I am getting this error related manager has no attribute. actually I can get data from PaymentDetail.objects.all() but it will only show data from PaymentDetail table. I want all the members and next to them their status from PaymentDetail table -
getting trouble in django-admin setup
PS C:\Users\laveen\pycharmprojects\DjangoCourse> django-admin django-admin : The term 'django-admin' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 django-admin + CategoryInfo : ObjectNotFound: (django-admin:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException -
Recieve and use JWT token/Token in Web Socket using django-channels
What I need to know? I want to receive JWT Token while connecting in web socket. I want to use JWT token. What I am using? django for project. django-channels for implementing Web Socket. -
How to delete a Django model object automatically after 24 hrs
I am new to django. I want to delete a model object automatically after the specific time. This is my model i want to delete class CustomerOrder(models.Model): order_types = ( ('dinein','Dinein'), ('delivery','Delivery'), ('pickup','Pickup') ) restaurant = models.ForeignKey(RestaurantDetail,on_delete=models.CASCADE,null=True) customer_name = models.CharField(max_length=30,null=True) table_no = models.IntegerField(null=True) total_price = models.FloatField(null=True,blank=True) success = models.BooleanField(default=False,blank=True,null=True) status = models.CharField(max_length=15,default='pending',null=True) ordered_menu = models.ManyToManyField(OrderedMenu) timestamp = models.DateTimeField(default=datetime.datetime.now()) order_type = models.CharField(max_length=15,default='dinein',choices=order_types) the timestamp is the saved time of the current object. is any idea about how to delete a model object automatically after the specific time? (example after 24 hrs). -
Please help me to figure out where is the actual bugs, I did correctly but didn't get to work as expected
{% extends 'main.html' %} {% load static %} {% block content %} {% if page == "register" %} <h1>Hello This is register Page!!!</h1> <form method="POST" action="{% url 'register' %}"> {% csrf_token %} {{form.as_p}} <input type="submit" value="Register" /> </form> <p>Aready have an account <a href="{% url 'login' %}"> Login </a></p> {% else %} <div class="auth"> <div class="card"> <div class="auth__header text-center"> <a href="/"> <img src="{% static 'images/icon.svg' %}" alt="icon" /> </a> <h3>Account Login</h3> <p>Hello Developer, Welcome Back!</p> </div> <form action="{% url 'login' %}" method="POST" class="form auth__form"> {% csrf_token %} <!-- Input:Email --> <div class="form__field"> <label for="formInput#text">Username: </label> <input class="input input--text" id="formInput#text" type="text" name="username" placeholder="Enter your username..." /> </div> <!-- Input:Password --> <div class="form__field"> <label for="formInput#password">Password: </label> <input class="input input--password" id="formInput#passowrd" type="password" name="password" placeholder="••••••••" /> </div> <div class="auth__actions"> <input class="btn btn--sub btn--lg" type="submit" value="Log In" /> <a href="forgetpassword.html">Forget Password?</a> </div> </form> <div class="auth__alternative"> <p>Don’t have an Account?</p> <a href="{% url 'register' %}">Sign Up</a> </div> </div> </div> {% endif %} {% endblock content %} and here is the error I have been taking Udemy course "Learn to build awesome websites with Python & Django!" by Dennis Ivy and I have reached almost middle of the course but when I reached here I was badly … -
get more than two foreign keys from another django table and perform calculations on them
In the Django app, I have created two tables. Product Invoice I have one table called Product which contains product name and product price columns are given. Then, I have a second table named Invoice which contains a product name(foreign key), product price(foreign key), discount, and total. My concern is how can I import both the values from the Product table i.e. product name and product price and perform calculations on them. The structure is given below: myapp -> PRODUCT: *Product Name *Product Id *Product Price INVOICE: *Product Name (foreign key) *Product Id (foreign key) *Product Price (foreign key) *Discount *Total = Product Price - Discount how can I import values and perform further calculations? -
Changing the opacity of the colour on the Polar Area chart
I am using Chart.js to create a set of polar area charts, I want to change teh opacity of the colour used to display the data so it is slightly transparent. Below you will find the code: var totals = {{ class_submission_totals|safe }} {% for t in type_qs %} var labels_{{ t.pk }} = [] var backgroundColors_{{ t.pk }} = [] {% for b in behaviour_qs %} {% if b.type.pk == t.pk and not b.previous %} labels_{{ t.pk }}.push("{{ b.title }}") backgroundColors_{{ t.pk }}.push("{{ b.primarycolour }}") {% endif %} {% endfor %} {% endfor %} new Chart("chart_{{ i.pk }}_{{ t.pk }}", { type: "polarArea", data: { labels: labels_{{ t.pk }}, datasets: [{ fillOpacity: 0.3, pointRadius: 1, backgroundColor: backgroundColors_{{ t.pk }}, data: totals_{{ i.pk }}_{{ t.pk }}_arr, }] }, options: { responsive: false, maintainAspectRatio: true, plugins: { legend: { display: true, }, title: { display: false, text: 'Chart.js Polar Area Chart' } } } }); {% endfor %} {% endfor %} -
django html: copy form input data and display in another page
I am trying to develop a delivery service web where users can input pickup and delivery address in the form and get the price online. if the price is fine, the user can click "place order" button which will navigate into another new page for user to fill in additional information, and importantly the previously input piackup and delivery addresses and the price will need to automatically shown somewhere in the new page. I am new to django and html, and I have tried to created a simpler page serving the same purpose. Now I could do the first part of form filling, and the backend calculate based on the user input and return the calculation result (e.g. price). Now, I am wondering how to do the "navigation to another new page which will display the two input values and calculation result" Main html: <html> <body> <form method="POST" hx-post="{% url 'blog:post_list' %}" hx-target="#num_1" hx-target="#num_2" hx-target="#result"> {% csrf_token %} <div> <label>num_1:</label> <input type="text" name="num_1" value="" placeholder="Enter value" /> </div> <div> <label>num_2:</label> <input type="text" name="num_2" value="" placeholder="Enter value" /> </div> <br /> <div id="num_1">{{ num_1 }}</div> <br /> <div id="num_2">{{ num_2 }}</div> <br /> <div id="result">{{ result }}</div> <br> <button type="submit">Submit</button> </form> … -
there is a problem in the login part of my project [closed]
my form is not working for some reason. that is, it does not give the expected result my views.py def TeacherLogin(request): if request.method == 'POST': form = TeacherLogin(data = request.POST) if form.is_valid(): user = authenticate(username=username, password=password).first() # user = User.objects.filter(username=username).first() if user is not None: return redirect('home') else: form = TeacherLogin() my forms.py class TeacherLoginForm(ModelForm): class Meta: model = User fields = ('username', 'password') my urls.py #in apps from django.urls import path, include from .views import * app_name = 'teachers' urlpatterns = [ path('teacherlogin/', TeacherLogin, name='teacherlogin'), ] -
How to programmatically make a user to assign permissions on template?
As you all know django admin has a function to give "Permissions" for user on their admin panel ! How to do that programmatically ? For example lets say i have a super user and the user can create staff users under them as multiple roles. And how to allow him to assign or add roles when the super user creates a profile on custom build admin panel ( am not asking for djago admin, am asking for custom own built admin panels) -
How I get the time zone of logged user by using Django?
I want to manage(such as Change the default language) the country region details of in my Django website. Does anyone have a best way to do that? -
Prefetch_related with filter for m2m
I'm trying to build a queryset to find candidates who has apply for a job_type, knows some languages and he wants to work in some zones. I'm able to select candidates based on job_type_ an d languages but my query doesn't filter by zones. : { "jobtype_id": 15, "languages": [21,83], "zones": [1,2,4] } This is my queryset: candidates = Candidate.objects.all().prefetch_related('job_types', 'languages').filter( job_types__id=job_type_id, languages__id__in=filter_languages).prefetch_related( Prefetch('job_types__candidate_job_type_zone', queryset=CandidateJobTypeZone.objects.all().filter(zone_id__in=filter_zones)), ) This is the SQL generated (i want an inner join to candidate_job_type_zone table and filter by zone id): SELECT `candidates`.`name`, `candidates`.`firstname`, `candidates`.`lastname`, `candidates`.`phone_number`, `candidates`.`secondary_phone_number`, `candidates`.`profession`, `candidates`.`own_car`, `candidates`.`driver_licence`, `candidates`.`location`, `candidates`.`document_type`, `candidates`.`document_id`, `candidates`.`work_permit`, `candidates`.`prefer_language`, `candidates`.`is_promoted`, `candidates`.`last_promoted_payment_date`, `candidates`.`is_active_job_search`, `candidates`.`last_active_job_search_date`, `candidates`.`created_at`, `candidates`.`updated_at`, `candidates`.`extra_data`, `candidates`.`user_id`, `candidates`.`nationality_id` FROM `candidates` INNER JOIN `candidates_jobs_types` ON (`candidates`.`user_id` = `candidates_jobs_types`.`candidate_id`) INNER JOIN `candidates_languages` ON (`candidates`.`user_id` = `candidates_languages`.`candidate_id`) WHERE (`candidates_jobs_types`.`job_type_id` = 15 AND `candidates_languages`.`language_id` IN (21, 83)) These are may models: class Candidate(models.Model): ... # relations user = models.OneToOneField( User, on_delete=models.CASCADE, null=False, verbose_name="Usuario relacionado", primary_key=True) job_types = models.ManyToManyField('JobType', through="CandidateJobType") languages = models.ManyToManyField(Language, through="CandidateLanguage") class CandidateJobType(models.Model): candidate = models.ForeignKey( Candidate, verbose_name="Candidato", on_delete=models.CASCADE) job_type = models.ForeignKey( JobType, verbose_name="Puesto de trabajo", on_delete=models.CASCADE, related_name='job_types') extra_data = models.JSONField(verbose_name="Datos extras", null=True) zones = models.ManyToManyField(Zones, through="CandidateJobTypeZone") is_active = models.BooleanField(verbose_name="Is active", null=True, default=True) class Meta: db_table = "candidates_jobs_types" unique_together = ('candidate', 'job_type') class … -
Multiple FeaturedPost on HomePage Using Wagtail
I haven't seen any question like this on the site. So hopefully this question will be useful for others in the future. I have a PostPage, EditorialPage, and DocumentPage. Within the models of the three, I added a 'featured' Boolean, so that if toggled in the settings, either Post is featured onto the HomePage. However, in the HomePage/Models, I only was able to get it to work with PostPage. I'm not too keen with query/querysets, but I feel it has something to do with that. I've read the Docs multiple times, but I do not understand how to make this work. Blog/Models.py class PostPage(Page): header_image = models.ForeignKey( "wagtailimages.Image", null=True, blank=True, on_delete=models.SET_NULL, related_name="+", ) featured = models.BooleanField(default=False) highlight = models.BooleanField(default=False) description = models.CharField(max_length=255, blank=True,) body = StreamField(BodyBlock(), blank=True) tags = ClusterTaggableManager(through="blog.PostPageTag", blank=True) post_date = models.DateTimeField( verbose_name="Post date", default=datetime.datetime.today ) content_panels = Page.content_panels + [ ImageChooserPanel("header_image"), FieldPanel("description", classname="full"), InlinePanel("blog_authors", label="author", min_num=1, max_num=4), MultiFieldPanel([ InlinePanel("categories", label="category",), FieldPanel("tags"), ], heading="Meta"), StreamFieldPanel("body"), ] settings_panels = Page.settings_panels + [ FieldPanel("post_date"), MultiFieldPanel([ FieldPanel("featured"), FieldPanel("highlight"), ], heading="Showcase") ] Home/Models.py (Method 1) class HomePage(RoutablePageMixin, Page): def get_context(self, request): featured_post = PostPage.objects.live().public().filter(featured=True) featured_editorial = EditorialPage.objects.live().public().filter(featured=True) feature_document = DocumentPage.objects.live().public().filter(featured=True) featured_select = sorted( chain(featured_post, featured_editorial, feature_document), key=lambda page: page.first_published_at, reverse=True)[0] return featured_select … -
I am trying to get data from database using python Django but got an error
Hello everyone I am trying to get data from database but it give me error in case when I am trying to get single data from db as shown below wahid = Webapp.objects.get(title="Ecommerce Website") Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 418, in get clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs) File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 942, in filter return self._filter_or_exclude(False, *args, **kwargs) File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 962, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, *args, **kwargs) File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 969, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query.py", line 1358, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query.py", line 1377, in _add_q child_clause, needed_inner = self.build_filter( File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query.py", line 1258, in build_filter lookups, parts, reffed_expression = self.solve_lookup_type(arg) File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query.py", line 1084, in solve_lookup_type _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta()) File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query.py", line 1481, in names_to_path raise FieldError("Cannot resolve keyword '%s' into field. " django.core.exceptions.FieldError: Cannot resolve keyword 'title' into field. Choices are: created, demo_link, description, id, review, source_link, tags, tiltle, vote_ratio, vote_total It will work only on getting all data from db as shown in image -
How to run python-socketio with django?
I am using python socket io in django rest framework. When i try to connect to socket through postman socketio I get following error. Can anyone help me. Not Found: /socket.io/ server.py import os import socketio sio = socketio.Server(async_mode="eventlet") @sio.event def connect(sid, environ): print(sid, "connected") wsgi.py import os import socketio application = get_wsgi_application() from .socketio_config.server import sio socket_application = socketio.WSGIApp(sio, wsgi_app=application) -
Unable to set form choices from view Django
I learned how to do this from Django Form ChoiceField set choices in View in Form initial However it doesn't seem to work correctly, choices are given view: form_class = AskMCQuestionForm() mc_choices = [] if question.One: mc_choices.append(tuple((1, question.One))) if question.Two: mc_choices.append(tuple((2, question.Two))) if question.Three: mc_choices.append(tuple((3, question.Three))) if question.Four: mc_choices.append(tuple((4, question.Four))) if question.Five: mc_choices.append(tuple((5, question.Five))) mc_choices = tuple(mc_choices) print(mc_choices) form_class.fields['user_answer'].choices = mc_choices form_class.fields['assignment'].initial = assignment form_class.fields['exam'].initial = question.exam form_class.fields['correct_answer'].initial = question.correct_answer form_class.fields['text'].initial = question.text print("About to render page for MC question") return render(request, 'Exam/ask_question.html', {'question': question, 'form': form_class}) form: class AskMCQuestionForm(forms.ModelForm): class Meta: model = MC_Question fields = ('text', 'user_answer', 'assignment', 'correct_answer', 'exam',) widgets = { 'text': forms.TextInput(attrs={'class': 'form-control', 'readonly': True}), 'user_answer': forms.Select(attrs={'class': 'form-control'}), 'assignment': forms.Select(attrs={'class': 'form-control'}), 'correct_answer': forms.HiddenInput(), 'exam': forms.HiddenInput(), } model: class MC_Question(models.Model): One = models.CharField(max_length=200) Two = models.CharField(max_length=200) Three = models.CharField(max_length=200, blank=True, null=True) Four = models.CharField(max_length=200, blank=True, null=True) Five = models.CharField(max_length=200, blank=True, null=True) class Answers(models.IntegerChoices): one = 1 two = 2 three = 3 four = 4 five = 5 text = models.CharField(max_length=200) correct_answer = models.IntegerField(choices=Answers.choices, blank=True, null=True) user_answer = models.CharField(max_length=200) exam = models.ForeignKey(Test, on_delete=models.CASCADE) assignment = models.ForeignKey(Assignment, on_delete=models.CASCADE, blank=True, null=True) question is an object of MC_Question, the same as what the form is creating. Apologies if I … -
Deploying Django App to Heroku Fail to Push
I am trying to deploy my app to heroku and am running into errors. I'm directly following the walkthrough on Heroku's site, with no luck. error: error: src refspec master does not match any error: failed to push some refs to cmd line: https://imgur.com/a/RVDNUzx Any thoughts? -
How bad is it if I do not use Django_tenants in a SAAS app with multiple users?
So I wish I would of known about Django_tenants earlier. I have written a SAAS (Software as a service) app in Django and the user data is separate by foreign key on the DB. See example. class Company(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE) . . class Product(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) . . How bad is this? Am I going to have major problems in the future? Is the data going to get contaminated in any way? Is sqlite3 the appropriate DB? Django_tenants uses Postgresql I have reasearched Django_tenants framework, and it is absolutely the safeguard I would need. But since my app is already written, I realize that to implement Django_tenants, it will basically be a complete rewrite, which I don't really want to do. So, I would really appreciate an opinion from someone with experience in the matter. Thank you. -
Why is Annotate Count function is not populating result?
I hope someone can help me out here - I have to models in Django one called 'Likes' and one called 'Foods', each record in Like contains a FK from Foods. I have the following function in python: def matches(request, eventId): matches = Food.objects.annotate(Count('like__event')) return JsonResponse([match.serialize() for match in matches], safe=False) The above returns a json response, however, I do not see the count of likes in it - I would expect to see at least "like__count": 0 but not even that, it's almost as if the annotate piece is being completely ignored. I think this is because my module is serialized that I don't see it in the JsonResponse. But then what would be the workaround? Thank you in advance! -
Heroku server error 500 after hosting Django app
I have this project, where details are fetched from API LINK COWIN It works completely fine when I run it in localhost, but after hosting it in Heroku, it is showing Server Error 500 settings.py: ALLOWED_HOSTS = ['*'] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / 'static/css', ] MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' # Default primary key field type # https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' if os.getcwd() == '/app': DEBUG = False django_heroku.settings(locals()) I am trying to host it from Github. github repo link: Github link for project