Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Count related model where an annotation on the related has a specific value and store count in an annotation
I have two models Pick and GamePick. GamePick has a ForeignKey relation to Pick, which is accessible on Pick.game_picks. I have setup GamePick with a custom queryset and manger so that when ever I retrieve a GamePick with the manager objects is is annotated with a field is_correct based on the values of other fields. Now what I want to be able to do is count the how many correct GamePicks are pointing to a specific Pick. One simple way is doing this with a method in Python: class Pick(models.Model): ... def count_correct(self): return self.game_picks.filter(is_correct=True).count() So far so good. But now, I would like to annotate each Pick with that count, say as correct_count. This is so I can order the Pick with something like Pick.objects.all().order_by("correct_count"). Now how would I do this? This is where I am: correct_game_picks = GamePick.objects.filter( pick=models.OuterRef("pk") ).filter(is_correct=True) subquery = models.Subquery( correct_game_picks.values("is_correct"), output_field=models.BooleanField() ) picks = Pick.objects.annotate( correct_count=models.Count(subquery) ) This is what pick.query gives me: SELECT "picks_pick"."id", "picks_pick"."picker", "picks_pick"."pot_id", COUNT(( SELECT (U0."picked_team_id" = U1."winning_team_id") AS "is_correct" FROM "picks_gamepick" U0 INNER JOIN "games_game" U1 ON (U0."game_id" = U1."id") WHERE (U0."pick_id" = "picks_pick"."id" AND (U0."picked_team_id" = U1."winning_team_id")) )) AS "correct_count" FROM "picks_pick" GROUP BY "picks_pick"."id", "picks_pick"."picker", "picks_pick"."pot_id" I … -
Is it possible to create an updating newsfeed in Django
Here's the gist of my goals in my project. Collect data from Reddit, Twitter, etc. using their respective APIs. Embed those posts in a newsfeed format (newest post at the top, etc). Save previous posts in the bottom of the feed(user can scroll down and see past posts) (involves caching?) What I've done: So pretty much, I've been able to create a services script to fetch the data through the APIs, store each post in a list ordered by creation time, pass this list through the view as context to my template, and, in the template, check if the post is a twitter or reddit post by looping through the context. If either, access the respective template tag to post the embedded html to the page. Note: This is easily the most difficult project I've worked on as a self-taught developer, so some concepts that are necessary to understand to complete my final project may be out of my realm of knowledge. That's OK, but I'm not sure what concepts I need to understand. Alas, why I am here. Basically, is it possible to implement this newsfeed-esque design using Django, or does that reach the limit of the framework's functionality? … -
How to post data with null fields in django?
I am trying to have a source class that takes in either a project, profile, department, or team as an AutoOneToOne Field from django_annoying. Basically, I am trying to have access to the sourceID and source type (project, profile, department, or team) to then send to a different class: Posts. When I try to add a source with profile "s" and null for the other fields as shown here: I get the following error message: I've tried adding a default="", but that is counterintuitive, and doesn't work anyways. Here is my Source class: class Source(models.Model): profile = AutoOneToOneField('Profile', on_delete=models.CASCADE, null=True, blank=True) project= models.OneToOneField('Project', on_delete=models.CASCADE, null=True, blank=True) team = AutoOneToOneField('Team', on_delete=models.CASCADE, null=True, blank=True) department = AutoOneToOneField('Department', on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.profile + self.project + self.team + self.department -
How can I change custom radio widget code to hide the text in Django?
This is the code I have for my custom radio widget {% with id=widget.attrs.id %}<div{% if id %} id="{{ id }}" {% endif %}{% if widget.attrs.class %} class="{{ widget.attrs.class }}" {% endif %}> {% for group, options, index in widget.optgroups %}{% if group %} <div style='display:inline-block'> {{ group }}<div style='display:inline-block' {% if id %} id="{{ id }}_{{ index }}" {% endif %}> {% endif %}{% for option in options %} <div style='display:inline-block'>{% include option.template_name with widget=option %}</div>{% endfor %}{% if group %} </div></div>{% endif %}{% endfor %} </div>{% endwith %} This is the actual HTML that is produced and I'm pretty sure I can't isolate "Strongly Disagree" text because it is not wrapped. The text is right next to the radio widget circle. I want to hide the text or at least make it opacity: 0 so I can eventually turn the form into this layout since it is 5 questions with the same agree/disagree options: -
does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import .Django 3.0.2
Project name : CRMPROJECT App name: leads I'm working on a CRM project With Django and I keep getting this error while trying to map my urls to views django.core.exceptions.ImproperlyConfigured. The included URLconf does not appear to have any patterns in it Below is the project/urls.py file ''' from django.contrib import admin from django.urls import path,include from leads import views urlpatterns = [ path('admin/', admin.site.urls), path('leads/',include('leads.urls',namespace='leads')), ] ''' Below is leads/urls.py from django.urls import path from . import views app_name = 'leads' urlpatterns = [ path('',views.home,name='home'), ] And lastly my leads/views.py ''' from django.shortcuts import render from django.http import HttpResponse # Create your views here. def home(request): return render(request,'leads/base.html') ''' -
MINIO on localhost?
I want to set up MinIO as my Django app object storage, and I want to test the functionality of this module on my computer (localhost). I follow the instruction in django-minio-backend, but I got the below error. raise MaxRetryError(_pool, url, error or ResponseError(cause)) urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='127.0.0.1', port=9000): Max retries exceeded with url: /django-backend-dev-public?location= (Caused by SSLError(SSLError(1, '[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1091)'))) These are lines that I've added to my settings.py file. INSTALLED_APPS = [ ... 'rest_framework', 'django_minio_backend', ... ] MINIO_CONSISTENCY_CHECK_ON_START = True MINIO_ENDPOINT = '127.0.0.1:9000' MINIO_ACCESS_KEY = 'minioadmin ' MINIO_SECRET_KEY = 'minioadmin ' MINIO_USE_HTTPS = True MINIO_URL_EXPIRY_HOURS = timedelta(days=1) # Default is 7 days (longest) if not defined MINIO_CONSISTENCY_CHECK_ON_START = True MINIO_PRIVATE_BUCKETS = [ 'django-backend-dev-private', ] MINIO_PUBLIC_BUCKETS = [ 'django-backend-dev-public', ] MINIO_POLICY_HOOKS: List[Tuple[str, dict]] = [] here -
'User' object has no attribute 'is_verified'
Im having this error. All of a sudden it was working fine on my local. but when i tried to deploy the app i have this error, im using a package two_factor Otp, here is the traceback Traceback: File "/tmp/8d909c171bfae2c/antenv/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/tmp/8d909c171bfae2c/antenv/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/tmp/8d909c171bfae2c/antenv/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/tmp/8d909c171bfae2c/antenv/lib/python3.7/site-packages/django/contrib/admin/sites.py" in wrapper 241. return self.admin_view(view, cacheable)(*args, **kwargs) File "/tmp/8d909c171bfae2c/antenv/lib/python3.7/site-packages/django/utils/decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "/tmp/8d909c171bfae2c/antenv/lib/python3.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "/tmp/8d909c171bfae2c/antenv/lib/python3.7/site-packages/django/contrib/admin/sites.py" in inner 212. if not self.has_permission(request): File "/tmp/8d909c171bfae2c/antenv/lib/python3.7/site-packages/two_factor/admin.py" in has_permission 28. return request.user.is_verified() File "/tmp/8d909c171bfae2c/antenv/lib/python3.7/site-packages/django/utils/functional.py" in inner 257. return func(self._wrapped, *args) Exception Type: AttributeError at / Exception Value: 'User' object has no attribute 'is_verified' any help would be appreciated. thank you -
Django - submit button value
I'm trying to send the value of a button when a form is submitted using the POST method. {% block content %} <div class="modal-dialog modal-lg" role="document"> <form action="" method="post" id="news-create" class="form">{% csrf_token %} <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> <span class="sr-only">Close</span> </button> <h4 class="modal-title">Add News</h4> </div> <div class="modal-body"> {{ form }} </div> <div class="modal-footer"> <input class="btn btn-primary" type="submit" name="save" value="Save" /> <input class="btn btn-primary" type="submit" name="save_new" value="Save as new" /> </div> </div><!-- /.modal-content --> </form> </div><!-- /.modal-dialog --> <script> var form_options = { target: '#modal', success: function(response) {} }; $('#news-create').ajaxForm(form_options); </script> {% endblock content %} But when I print the QueryDict request.POST inside the file view.py the value of the button is not present. How can I get the value? I need to perform different action based on the button clicked. At the moment I'm using a bootstrap modal view to render a form (UpdateView) based on a model. Thanks for the support -
Django search submission from different urls not working
I'm trying to use a search form in a nav bar, but for whatever reason it is not being redirected to the correct URL. it should go to "http://localhost:8000/search?q=hj" but goes to "http://localhost:8000/?q=hj" or just appends on to the end of the url. Why is this? If i include the 'search' in the url manually, it works. in urls.py: from django.urls import path from . import views urlpatterns = [ path("", views.Index.as_view(), name="index"), path("search", views.search, name="search"), ] in views.py: def search(request): if request.method == 'GET' and 'q' in request.GET: q = request.GET['q'] bugs = Bug.objects.filter(title__contains=q).order_by('priority', 'solved') projects = Project.objects.filter(title__contains=q) return render(request, 'myapp/searched.html', {'bug_list': bugs, 'project_list': projects}) and the template: <form action="{% url 'search' %}" method="GET"> <input type="text" class="form-control bg-light border-0 small" placeholder="Search bugs or projects..." aria-label="Search" name="q" aria-describedby="basic-addon2"> <div class="input-group-append"> <button class="btn btn-info" type="submit"> <i class="fas fa-search fa-sm"></i> </button> </div> </form> I've searched for similar answers but was unable to find any. I know I'm likely missing something really obvious and just can't see it. -
ModuleNotFoundError: No module named 'apps.product.context_processors'
I'm getting this error and I cannot find what is causing it. Here is the traceback: Traceback (most recent call last): File "/Users/alex/projects/passtur/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/alex/projects/passtur/venv/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/alex/projects/passtur/passtur/apps/core/views.py", line 9, in frontpage return render(request, 'core/frontpage.html', {'newest_products': newest_products}) File "/Users/alex/projects/passtur/venv/lib/python3.9/site-packages/django/shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "/Users/alex/projects/passtur/venv/lib/python3.9/site-packages/django/template/loader.py", line 62, in render_to_string return template.render(context, request) File "/Users/alex/projects/passtur/venv/lib/python3.9/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/Users/alex/projects/passtur/venv/lib/python3.9/site-packages/django/template/base.py", line 168, in render with context.bind_template(self): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/contextlib.py", line 117, in __enter__ return next(self.gen) File "/Users/alex/projects/passtur/venv/lib/python3.9/site-packages/django/template/context.py", line 240, in bind_template processors = (template.engine.template_context_processors + File "/Users/alex/projects/passtur/venv/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/alex/projects/passtur/venv/lib/python3.9/site-packages/django/template/engine.py", line 85, in template_context_processors return tuple(import_string(path) for path in context_processors) File "/Users/alex/projects/passtur/venv/lib/python3.9/site-packages/django/template/engine.py", line 85, in <genexpr> return tuple(import_string(path) for path in context_processors) File "/Users/alex/projects/passtur/venv/lib/python3.9/site-packages/django/utils/module_loading.py", line 17, in import_string module = import_module(module_path) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'apps.product.context_processors' [27/Apr/2021 21:43:33] "GET / HTTP/1.1" 500 110467 My core/views.py is: from django.shortcuts import … -
How do I properly setup an producer - consumer scheme using redis as a message broker and store results in postgresql / sqlite?
I am really new with celery - redis scheme, but I am trying to implement a producer-consumer https://github.com/SkyBulk/celery scheme similar to where my task producer is my Django tasks , and then a broker (Redis) with celery beat for task scheduler where Redis can fit on this scheme to store my tasks, and celery worker executes task producer (django tasks) or any other outside djngo and save results of those tasks to sqlite or postgresql (not the logs of the scheduler) demo questions. why do I get nothing on Redis? INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "orders.apps.OrdersConfig", ] CELERY_BROKER_URL = "redis://redis:6379/0" CELERY_RESULT_BACKEND = "redis://redis:6379/0" CELERY_BEAT_SCHEDULE = { "sample_task": { "task": "orders.tasks.sample_task", 'schedule': timedelta(seconds=2), }, "send_email_report": { "task": "orders.tasks.send_email_report", "schedule": crontab(minute="*"), }, } logs celery_1 | [2021-04-27 21:42:01,910: INFO/MainProcess] Received task: orders.tasks.sample_task[a50a9653-c141-4922-816a-67b9423bb110] celery_1 | [2021-04-27 21:42:01,912: WARNING/ForkPoolWorker-3] each two seconds celery_1 | [2021-04-27 21:42:01,913: INFO/ForkPoolWorker-3] Task orders.tasks.sample_task[a50a9653-c141-4922-816a-67b9423bb110] succeeded in 0.0017081940000025497s: None celery_1 | [2021-04-27 21:42:03,910: INFO/MainProcess] Received task: orders.tasks.sample_task[567c8088-3de7-4876-a86f-ee418ff47ec5] celery_1 | [2021-04-27 21:42:03,912: WARNING/ForkPoolWorker-3] each two seconds celery_1 | [2021-04-27 21:42:03,913: INFO/ForkPoolWorker-3] Task orders.tasks.sample_task[567c8088-3de7-4876-a86f-ee418ff47ec5] succeeded in 0.0019250379999675715s: None celery_1 | [2021-04-27 21:42:05,908: INFO/MainProcess] Received task: orders.tasks.sample_task[407d41a7-8b09-4760-94d8-9311f0e9222e] celery_1 | [2021-04-27 21:42:05,909: WARNING/ForkPoolWorker-3] each two seconds celery_1 | [2021-04-27 21:42:05,910: … -
mod_wsgi.Input object has no attribute stream Error
when I try to send an e-mail from my Contact page, I get this error. How Can I Solve? I am getting this error on ubuntu server and in addition, these codes work in localhost without any problems. I tried very hard, but I could not find a solution because I did not know very well about servers. I would be grateful if you could help AttributeError at /iletisim/ 'mod_wsgi.Input' object has no attribute 'stream' Request Method: POST Request URL: https://xxxx.com/iletisim/ Django Version: 3.2 Exception Type: AttributeError Exception Value: 'mod_wsgi.Input' object has no attribute 'stream' Exception Location: /var/www/contact/views.py, line 22, in iletisim Python Executable: /usr/bin/python3 Python Version: 3.6.9 Python Path: ['/var/www', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages'] Server time: Wed, 28 Apr 2021 00:42:52 +0300 MY VIEW.PY from django.shortcuts import render,redirect from .models import * from .forms import * from log.forms import * from django.contrib import messages def iletisim(request): iletisim_log_form = IletisimLogModelForm(request.POST or None, request.FILES or None) iletisim_form = IletisimModelForm(request.POST or None, request.FILES or None) if iletisim_form.is_valid(): form = iletisim_form.save(commit=False) if iletisim_log_form.is_valid(): logform = iletisim_log_form.save(commit=False) logform.log_kullaniciadi = form.iletisim_adisoyadi logform.log_epostasi = form.iletisim_epostasi logform.log_konusu = form.iletisim_konusu logform.log_icerigi = form.iletisim_icerigi sock = request._stream.stream.stream.raw._sock logform.log_ipportiletisim = sock.getpeername() logform.save() form.save() messages.success(request, 'Gonderildi...') return redirect('sonuc') return render(request, … -
Django employer employee relationship
I'm having bit of a trouble with how to structure One Employer to many Employees relationship in Django when employees need to login too. My initial set is only employers are users and employees don't login and here is that setup: from django.contrib.auth.models import User class Company(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True) company_name = models.CharField(max_length=100, blank=False, null=True) ... class Employee(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, null=True, related_name='employees') full_name = models.CharField(max_length=50, null=True, blank=True) .... But now I made a mobile app and employees need to login as well. I'm managing the auth with JWT, Back-end (Django) with Graphene (So GraphQL) and mobile app with Apollo client. Question is: How do I create a User account (in auth_user table, which is what JWT uses for authentication) for employees while still maintaining the foreignKey relationship to the company? -
TemplateSyntaxError at /register/ Invalid block tag on line 20: 'endblock'. Did you forget to register or load this tag?
{% extends "django_blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom-mb-4">Join Today</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Sign Up</button> </div> </form> <div class="border-top pt-3"> <small class="text-muted" >Already Have An Account? <a class="ml-2" href="#">Sign In</a> </small> </div> {% endblock content %} It was working before I added crispy form. Whenever I reload /register the error appears -
LOGIN_REDIRECT_URL not redirecting
I'm using Django, Mysql and Docker, with a custom user model for Django. After entering correct login details the LOGIN_REDIRECT_URL='searcher-home' variable in settings.py isn't redirecting to the home page as expected, instead it attempts to redirect to the default path of /accounts/profile/. Does anyone know what could be causing this? I've looked elsewhere for answers, but all issues I've found are either looking for LOGIN_URL which isn't what I need, or are using custom LoginViews, which I'm not. Any insight would be appreciated. -
Django X-editable
and thank you for always saving me in my project :D I am using django to develop my app and here is the page I have basically displaying a table : Html code here : <table class="logtable" > <tr> <td> Year </td> <td name="yearr">{{ yearr }}</td> </tr> <tr> <td> Plant </td> <td>{{ plant }}</td> </tr> <tr> <td>Responsible</td> <td>{{responsible}}</td> </tr> <tr> <td>Produced sales in Km per week</td> <td>{{produced}}</td> </tr> <tr> <td>Sold sales per Week (m)</td> <td>{{sold}}</td> </tr> <tr> <td>Number of customers </td> <td>{{customers}}</td> </tr> <tr> <td>Number of produced references </td> <td>{{references}}</td> </tr> <tr> <td>Shipment destinations </td> <td>{{destinations}}</td> </tr> <tr> <td>Plant shifts </td> <td>{{shifts}}</td> </tr> </table> I would like to to be able to double click a td to change its value and save into the database, I think x-editable allows me to do that, can someone help me on how to do it ? Thank you -
JSON parse error - Expecting value: line 1 column 1 (char 0) - DELPHI Rest Datasnap
I'm trying to make a POST request in the delphi language, as a client and Django as a server. But when doing the POST is giving the error: { "detail":"JSON parse error - Expecting value: line 1 column 1 (char 0)" } All the authentication part is working correctly, I can make GET requests without problems. Source code used to add my json to the body of the request. sJson := '{"id":9,"grupo":"TESTE","id_empresa":26,"prioridade":0}'; RESTRequest.Body.ClearBody; with RESTRequest.Params.AddItem do begin name := 'body'; Value := sJson; Kind := pkREQUESTBODY; ContentType := ctAPPLICATION_JSON; end; RESTRequest.Execute; Result.Value := RESTResponse.content; Result.StatusCode := RESTResponse.StatusCode; Result.Mensagem := RESTResponse.StatusText; Making the same request through PostMan everything goes well, but not when I do it through my application. Would anyone know the resolution of this ?? -
Not getting any data in my django template
I have a URL that calls my Create View with a primary key. For some reason the html template never gets any data. Have tied printing out pk, table.pk etc. but no data seems to make it to the view... my view looks like this: class SegmentAddView(LoginRequiredMixin,CreateView): model = Program template_name = 'segment_add_view.html' form_class = SegmentForm context_object_name = 'program_info' The models are as follows: class Program(models.Model): air_date = models.DateField(default="0000-00-00") air_time = models.TimeField(default="00:00:00") service = models.CharField(max_length=10) block_time = models.TimeField(default="00:00:00") block_time_delta = models.DurationField(default=timedelta) running_time = models.TimeField(default="00:00:00",blank=True) running_time_delta = models.DurationField(default=timedelta) remaining_time = models.TimeField(default="00:00:00",blank=True) remaining_time_delta = models.DurationField(default=timedelta) title = models.CharField(max_length=190) locked_flag = models.BooleanField(default=False) deleted_flag = models.BooleanField(default=False) library = models.CharField(null=True,max_length=190,blank=True) mc = models.CharField(max_length=64) producer = models.CharField(max_length=64) editor = models.CharField(max_length=64) remarks = models.TextField(null=True,blank=True) audit_time = models.DateTimeField(auto_now=True) audit_user = models.CharField(null=True,max_length=32) class Segment(models.Model): class Meta: ordering = ['sequence_number'] program_id = models.ForeignKey(Program, on_delete=models.CASCADE, related_name='segments', # link to Program ) sequence_number = models.DecimalField(decimal_places=2,max_digits=6,default="0.00") title = models.CharField(max_length=190, blank=True) bridge_flag = models.BooleanField(default=False) seg_length_time = models.TimeField() seg_length_time_delta = models.DurationField(default=timedelta) seg_run_time = models.TimeField(default="00:00:00",blank=True) seg_run_time_delta = models.DurationField(default=timedelta) seg_remaining_time = models.TimeField(default="00:00:00",blank=True) seg_remaining_time_delta = models.DurationField(default=timedelta) author = models.CharField(max_length=64,null=True,default=None,blank=True) voice = models.CharField(max_length=64,null=True,default=None,blank=True) library = models.CharField(max_length=190) summary = models.TextField() audit_time = models.DateTimeField(auto_now=True) audit_user = models.CharField(null=True,max_length=32) I have a button in my detail screen that does this: <button type="submit" value="add_segment" … -
Django Models: How to pass the id of a class, and the non-null object fields of a class to another class?
This is a conceptual question, not an error necessarily. How do I differentiate between drawing the autogenerated id of a class and drawing the name of non-null object fields in a class? For example, in my class Source, I have: class Source(models.Model): profile = AutoOneToOneField(User, on_delete=models.CASCADE, null=True) project= AutotOneToOneField(Project, on_delete=models.CASCADE, null=True) team =AutotOneToOneField(Team, on_delete=models.CASCADE, null=True) department = AutoOneToOneField(Department, on_delete=models.CASCADE, null=True) def __str__(self): return self.profile + self.project + self.team + self.department and the goal is to have the source either be from a profile, project, team, or department, and I want to associate that source with a a sourceID, but I also want to be able to know the type of source. In my class, VideoPost: class VideoPost(models.Model): sourceID = models.ForeignKey(Source, on_delete=models.CASCADE) postID = models.ForeignKey(Post, on_delete=CASCADE) I want to draw the sourceID, but in my class Following: class Following(models.Model): profile = AutoOneToOneField(User, on_delete=models.CASCADE) account_types = models.ForeignKey(Source, on_delete=models.CASCADE) #need to create an account type account_ids = models.PositiveIntegerField() following_objects = GenericForeignKey('account_types', 'account_ids') def __str__(self): return self.profile + 'is following' I want to draw the type of source (in account_types). How do I differentiate and return the values desired? -
Add divs with Django template tags on button press
I have a simple form defined in forms.py: SAMPLE_STRINGS = [('','Select...'),'aa','ab','bb','c0'] class MyCustomForm(forms.Form): chosen_string = forms.ChoiceField(choices=SAMPLE_STRINGS, label='Please select a string', required=True) chosen_number = forms.IntegerField(label='Please select an integer', widget=forms.NumberInput(attrs={'placeholder': 0})) I want to allow the user to add boxes (divs) containing the above form. One standalone div, with Django's template tags, would look like this: <div class="box" style="height:auto; background-color: #eee;"> <form method="POST" action=""> {% csrf_token %} {{form.as_p}} </form> </div> I know that, if there is a button <button class="add_box">New Box</button>, the corresponding jQuery script to add new elements would look like this: $('#button_id').click(function(){ $('#canvas').append(' ...*HTML of element*... '); }); However, this jQuery doesn't seem to work when the element to be appended doesn't contain pure HTML/CSS but also Django templates. My views.py: def my_form_func(response): form = MyCustomForm(response.POST or None) return render(response, "main/my_custom_form.html", {"form": form}) my_custom_form.html: <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> $( function() { $( ".box" ).draggable().resizable(); } ); // adding div and form on button click - this part causes error $('.add_box').click(function(){ $('#canvas').append('<div class="box" style="height:auto; background-color: #eee;"><form method="get" action="">{% csrf_token %}{{form.as_p}}</form></div>'); }); </script> <html> <button class="add_box">New Box</button> <div id="canvas" style="background-color: #444; height: 90%"> <div class="box" style="height:auto; background-color: #eee;"> <form method="POST" action=""> {% csrf_token %} {{form.as_p}} </form> </div> </div> … -
DJANGO form adding in a phone number to user profile registration
So the current issue I am having is that I currently have a form to create a user we are now adding in a phone number option for this it is currently creating the user and user profile but the user profile does not have the phone number saved the only way ive been able to get it in is manually via django admin page I've tried a few variations but none have works so far I appreciate any assistance I can get #this is in my forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] #fields = UserCreationForm.Meta.fields+ ('username', 'email', 'password1', 'password2') def clean(self): email = self.cleaned_data.get('email') username = self.cleaned_data.get('username') if email and User.objects.filter(email=email).exclude(username=username).exists(): raise forms.ValidationError('Email addresses must be unique.') return super().clean() class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ['phone_number'] this is my views.py def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) profile_form = UserProfileForm(request.POST) #added if form.is_valid() and profile_form.is_valid(): #addded profile form form.save() profile_form.save() #added messages.success(request, 'Account created!') return redirect('login') else: form = UserRegisterForm() profile_form = UserProfileForm() #added return render(request, 'user/register.html', {'form': form, 'profile_form': profile_form}) this is my register.html <form method="post"> {% csrf_token %} <fieldset class="form-group"> <legend … -
how can i add the input to the link in the action for a sech bar?
I am currently writing some script in HTML that creates a search bar. The page seems to redirect to https://schedule.nylas.com/?, but I want it to redirect to the input in the search box. i.e the input in the search box is icecreamshop and it goes to https://schedule.nylas.com/icecreamshop <form autocomplete="off" action="https://schedule.nylas.com" + input> <div class="autocomplete" style="width:300px;"> <input id="myInput" type="text" name="" placeholder="store"> </div> <input type="submit"> </form> -
django not applying css and widget after form fail
I am trying to apply CSS to input fields after form failure. The ModelForm where I am applying the original CSS and widget is: class MyAppForm(ModelForm): class Meta: widgets = { 'date_field': DateInput(attrs={"type": "date"}) } def __init__(self, *args, **kwargs): super(MyAppForm, self).__init__(*args, **kwargs) for i, f in self.fields.items(): f.widget.attrs['class'] = 'custom-css' The template where I'm redisplaying the form looks like this: {{ myapp_form.date_field.errors }} <label for="{{ myapp_form.date_field.id_for_label }}">{{ myapp_form.date_field.label }}</label> {{ myapp_form.date_field }} After the form is redisplayed, the date field displays as text input is custom-css are not applied to the input elements. How can I get widgets and CSS to apply after error? -
Suggestion on model test
I’ve been thinking about changing my simple model creation test from this. def test_create_user(self): user = User.objects.create_user( email='normal@user.com', password='foo', # other fields ) assert user.email == 'normal@user.com' # assert other fields To this def test_create_user(self): user = UserFactory.create() assert isinstance(user, User) I’m not sure if they represent the same thing, but I think the second one is easier to read. I would like to know suggesting about this kind of test, since I’m pretty new to testing thing. Thanks for your attention. -
App not compatible with buildpack Django heroku
Would anyone be able to give me a tip Heroku? Very new at this as well as Django. I am trying to follow these steps on Dev using django_heroku that is imported on the settings.py file. Small snip of settings.py: """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 2.1.7. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os import django_heroku django_heroku.settings(locals()) # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATES_DIR = os.path.join(BASE_DIR, 'templates') This is my requirements.txt: Django==2.2.8 gunicorn django-heroku django-crispy-forms==1.8.1 django-summernote==0.8.11.4 pytz==2019.3 sqlparse==0.3.0 ProcFile: web: gunicorn mysite.wsgi --log-file - Using the Heroku pipeline as mentioned in the blog post when I do a git push heroku master: Enumerating objects: 237, done. Counting objects: 100% (237/237), done. Delta compression using up to 8 threads Compressing objects: 100% (137/137), done. Writing objects: 100% (237/237), 67.80 KiB | 6.16 MiB/s, done. Total 237 (delta 100), reused 216 (delta 92), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Using buildpack: heroku/python remote: -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz …