Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django TabularInline raise ValidationError on a specific row
before posting the question here I have checked Raise validation error in inline field Django. But this still does not answer my question, because the error thrown is in the form but not on the exact row. In MyModel.clean function if I raise Validation error I can specify the field which is bad. But how can I raise an error on the bad row of a TabularInline? class MyBaseFormSet(BaseInlineFormSet): def clean(self): super(MyBaseFormSet, self).clean() for index, form in enumerate(self.forms): if form.cleaned_data and not form.cleaned_data.get('DELETE', False): raise ValidationError('test') class MyInline(admin.TabularInline): model = MyModel formset = MyBaseFormSet -
Render dictionary in django template
I have groupby clause built in a django view and then I intend to display the dictionary created in a template. The problem here is that the template instead of displaying values, displays the header fields repeated (screenshot attached so it makes more sense). Any assistance will be appreciated ! Here is the view def did_count_region_groupby(request): region_carrier_groupby = DID_Definition_Model.objects.all().values('region_carrier').annotate(DID_Count=Count('region_carrier')).order_by('DID_Count') region_carrier_groupby_dict = {'region_carrier_groupby' : region_carrier_groupby} return render(request, 'MASTERHANDLER/did_count_region_groupby.html', region_carrier_groupby_dict) and here is the template {% for key, value in region_carrier_groupby %} <tr> <td> {{key}}</td> <td>{{value}}</td> </tr> {% endfor %} -
update a model's field from another model in django
my models.py is : class clients(models.Model): client_id = models.IntegerField(unique=True, primary_key=True ) ' ' money = models.DecimalField(max_digits=10, decimal_places=2,default=0) class transfermoney(models.Model): first_client_id = models.IntegerField() second_client_id = models.IntegerField() amountofmoney = models.PositiveIntegerField() time = models.TimeField(auto_now=True) date = models.DateField(auto_now=True) my serializers.py is : class moneytransfer(serializers.ModelSerializer): def validate(self, data): try: clients.objects.get(client_id = data['first_client_id']) clients.objects.get(client_id = data['second_client_id']) except clients.DoesNotExist: raise serializers.ValidationError("One of the clients does not exist") return data class Meta: model = transfermoney fields = ('__all__') read_only_fields = ('time','date',) my views.py is : class transferingmoney(APIView): def post(self,request): serializer = moneytransfer(data=request.data) if serializer.is_valid(): serializer.save() def update(self,data): client_1 = clients.objects.get(client_id=data['first_client_id']) client_2 = clients.objects.get(client_id=data['second_client_id']) client_1.money -= data['amountofmoney'] client_2.money += data['amountofmoney'] client_1.save() client_2.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) i'm using django rest framework, when i made a post request to "transferingmoney" , it made a record into the "transfermoney" model table ,, but it did not update the "money" field for client_1 or client_2 in the "clients" model please can you help me, what should i do ? -
How to display custom HTML in an autocomplete field in Django admin?
I want to open the related object popup when the user clicks on a selected value in a Django admin autocomplete multi-select field. This requires adding custom HTML to selected values. I did not find any straightforward way to add custom HTML to Django admin built-in autocomplete field, so I'm using the ModelSelect2Multiple field from django-autocomplete-light. So far I haven't found any better way than to stick the HTML into model __str__() and mark it safe. This is admittedly a hack, but works well with ModelSelect2Multiple data-html attribute when making new selections. However, it does not work with saved selections. The models are as follows: class Author(models.Model): name = models.CharField(_('name'), max_length=160) profession = models.CharField(_('profession'), max_length=100) phone = models.CharField(_('phone'), max_length=20, blank=True) email = models.EmailField(_('email'), blank=True) def __str__(self): change_url = reverse('admin:books_author_change', kwargs={'object_id': self.id}) return mark_safe('<span onclick="showRelatedObjectPopup(' f"{{href: '{change_url}?_popup=1', id: 'change_id_authors'}})" f'">{self.name} – {self.profession}</span>') class Book(models.Model): authors = models.ManyToManyField(Author, verbose_name=_('authors'), blank=True) ... The admin configuration is as follows: from dal import autocomplete @admin.register(Book) class BookAdmin(admin.ModelAdmin): def formfield_for_manytomany(self, db_field, request, **kwargs): if db_field.name == 'authors': return forms.ModelMultipleChoiceField( required=False, label=Author._meta.verbose_name_plural.title(), queryset=Author.objects.all(), widget=autocomplete.ModelSelect2Multiple( url='author-autocomplete', attrs={'data-html': True})) return super().formfield_for_foreignkey(db_field, request, **kwargs) When adding an author to the Authors field in the Book change view, the HTML element … -
Migrations Are Not Taking Effect (Django - Python)
I think I have followed the correct process for getting migrations to work but the changes have not seem to have taken effect. I am trying to add a slug field to my Comments class field=models.SlugField(blank=True, max_length=500). Schema sqlite> .schema blog_Comment CREATE TABLE IF NOT EXISTS "blog_comment" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "name" varchar(80) NOT NULL, "email" varchar(254) NOT NULL, "body" text NOT NULL, "created_on" datetime NOT NULL, "active" bool NOT NULL, "post_id" integer NOT NULL REFERENCES "blog_post" ("id") DEFERRABLE INITIALLY DEFERRED); CREATE INDEX "blog_comment_post_id_580e96ef" ON "blog_comment" ("post_id"); sqlite> 0017_auto_20200426_2137.py # Generated by Django 2.2.6 on 2020-04-26 14:37 import datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('blog', '0016_auto_20200426_0209'), ] operations = [ migrations.AlterField( model_name='comment', name='created_on', field=models.DateTimeField(default=datetime.datetime(2020, 4, 26, 14, 37, 27, 23071, tzinfo=utc)), ), migrations.AlterField( model_name='comment', name='url', field=models.SlugField(blank=True, max_length=500), ), migrations.AlterField( model_name='post', name='date_posted', field=models.DateTimeField(default=datetime.datetime(2020, 4, 26, 14, 37, 27, 23071, tzinfo=utc)), ), ] class Comment(models.Model): class Comment(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created_on= models.DateTimeField(default = timezone.now()) active = models.BooleanField(default=False) url= models.SlugField(max_length=500, blank=True) -
How to do pip install with subprocess in Django Gunicorn server
I need to install a pip package according to given name. I am trying to install package via subprocess.run(). In Django runserver (its called dev. server I guess), everything works fine but in production environment where we have gunicorn, program just freezes after subprocess.run() What am I doing wrong? Can someone points me the problem ? I see subprocess start but I never see subprocess end line in the log file. I tried to put something like ls -la to the command variable. It also works like that way def install(path): try: command = r"pip install {} --disable-pip-version-check".format(path) logger.info("subprocess start") process = subprocess.run(command, shell=True, check=True, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) logger.info("subprocess end") if(process.stdout): logger.info("Package Installation Output: {}".format(process.stdout)) if(process.stderr): logger.error("Package Installation Error - Return 0 : {}".format(process.stderr)) except Exception as err: logger.error("Package installation error: {}".format(err)) -
How can i define user detail view in multiuser blog app?
I'm building a blog app with multi users and i'd like to have this ability that every logged user could click on every username (post author) and see details of this profile my current function gives me only details for current logged in user no mattew what user i click. i have similar CBV function working for post list view that shows me all the posts for each user and i've tried to do the same but it didn't worked.. Please help ;) view > @login_required def profile_detail(request): context = { 'profile': Profile.objects.all() } return render(request, 'users/user_detail.html', context) model class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self, *args,**kwargs): super().save(*args,**kwargs) img = Image.open(self.image.path) if img.height >300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) url pattern path('profile-detail/', user_views.profile_detail, name='user_detail'), link <a class="mr-2" href="{% url 'user_detail' %}">{{ post.author }}</a> -
get_or_create not creating my object with attributes that I need
So I am attempting to get_or_create a conversation object. Now, if the object is already created, the code works fine. But if it's not created, it will create the conversation object, BUT not with the members that I am trying to pass. An empty conversation object. members is a manytomany field to User. What am I doing wrong here? views/message def message (request, profile_id): if request.method == 'POST': form = MessageForm(request.POST) if form.is_valid(): form.save() return redirect('dating_app:messages', profile_id) else: conversation, created = Conversation.objects.filter(members = request.user).filter(members= profile_id).get_or_create(members= members.set(profile_id)) other_user = conversation.members.filter(id=profile_id).get() form = MessageForm({'sender': request.user, 'conversation': conversation}) context = {'form' : form, 'other_user': other_user } return render(request, 'dating_app/message.html', context) models.py/Conversation class Conversation(models.Model): members = models.ManyToManyField(settings.AUTH_USER_MODEL) -
Django 3 how to show block content? the content block went invisible in templates when extended base html
Django 3 the content block went invisible in templates when extended base html The index.html page used to displays a bunch of articles then there are single pages of them single.html they both page type extend from base.html. After I added pagination only the pagination part displays. I am not getting any errors in the vs code problems section. Missing the main content block in both index.html and single pages index.html this is supposed to extend from base.html and load block content of the cards {% extends "base.html" %} {% block title %}Meteorite Collection{% endblock title %} {% block content %} {% for article in articles %} <div> <li class="card m2 p-3 card-body" style="width: 18rem;"> <img class="card-img-top" src="{{article.image.url}}" alt="{{article.title}}"> <a href="{% url 'single' article.id%}"><h2>{{article.title}}</h2></a> <img class="card-img-top" src="{% url 'single' article.id%}" alt="{{article.title}}"> <p class="card-text">{{ article.content | truncatewords:50 }}</p> <p>Posted in: {{article.category}}, Posted by: {{article.author}}</p> <a href="{% url 'single' article.id%}" class="btn btn-primary">Goto {{article.title}} Details</a> </li> </div> {% endblock content %} base.html <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>{% block title %}{% endblock title %}</title> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> </head> <body> <header> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo01" aria-controls="navbarTogglerDemo01" aria-expanded="false" aria-label="Toggle navigation"> … -
Django3 - manage.py commands stuck
I have a big problem wih Django3: basically, whenever I type a command for manage.py, the prompt gets stuck and never carries on the command without even crashing. I tried several times the commands "runserver" and "startapp" and waited beetween 10 minutes and an hour, but I never managed to run the server or create an app because I launch the command and the prompt gets stuck. Strangely enough, to test things out, I created a project, an app and run the server immediately after I installed Django3 and everything worked fine, I even have that project on github. Then I shut down the computer and now nothing works. Also, I noticed in the Windows resource monitor that whenever I try to lauch a command suddenly Python processes start to appear and disappear uncontrollably, and since I never had an issue like this I'm absolutely clueless about everything. So... What's happening? Did someone have the same problem? I have the lastest Windows update, the latest Python3 (I got it via Windows Store) and the Latest Django3 (I got it via pip). I'd include a stacktrace or some sort of log but, since nothing crashes, I suppose no log gets done: … -
How can I using my LWS host SMTP mail service in my Django project?
I discovered Django framework, and I used it to develop my website. The development is finished but I need to improve a mail form in "Contact" section to visitors can contact me. I will host my website at LWS hoster. I've created an email account and I want to use it. This is my setting.py mail configuration EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'mail.****.io' EMAIL_HOST_USER = 'contact@*****.io' EMAIL_HOST_PASSWORD = '****' EMAIL_PORT = 465 Unfortunately, it's not working. When I confirm the contact form, my page wait endlessly and finished with "SMTPServerDisconnected". If anybody host a Django website at LWS and use their mail service... Or maybe anyone has an idea? Thanks for your help. -
is_valid() function returning false based in the traceback from a IntergerField in forms
is_valid() function returning false based in the traceback from a IntergerField in forms. I am probably missing out on something in the is_valid() line of code. Any input is appreciated. traceback [27/Apr/2020 02:23:07] "GET / HTTP/1.1" 200 10413 5 <bound method BaseForm.is_valid of <IdForm bound=True, valid=Unknown, fields=(id)>> <tr><th><label for="id_id">Song ID:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="id" required id="id_id"></td></tr> <tr><th><label for="id_id">Song ID:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="id" required id="id_id"></td></tr> <bound method BaseForm.is_valid of <IdForm bound=False, valid=Unknown, fields=(id)>> [27/Apr/2020 02:23:09] "POST /playlist/add/5/ HTTP/1.1" 200 4406 forms.py class IdForm(forms.Form): id = forms.CharField(label='Song ID', required=True) template <form action="{% url 'playlist_add' P_id=p.id %}" method="POST" enctype="multipart/form-data" value="{{request.post.id}}"> {% csrf_token %} {%for field in form%} {{field.errors}} {{field}} {%endfor%} <button type="submit">Add Song</button> </form> views.py class PlaylistAddFormFunction(View): form_class = IdForm #determine fields template = 'homepage_list.html' def get(self, request): form = self.form_class(None) print('soo') return render(request, self.template, {'form':form}) @method_decorator(login_required) def post(self, request, P_id): print(P_id) form = IdForm(request.POST) print(form.is_valid) print(form) if form.is_valid(): print('xoo') id = form.cleaned_data['id'] song = Song.objects.get(id=id) playlist, created = Playlist.objects.get_or_create(id=P_id) playlist.song.add(song) return redirect('home') else: print(form) form = self.form_class(None) print(form.is_valid) return render(request, self.template, {'form':form}) -
Django - Message translation in template still show original language version
Translations in the same function for form.error work and messages are displayed in a different language, but for "messages" the text is still displayed in English in the template views.py from django.utils.translation import ugettext_lazy as _ form.errors['__all__'] = form.error_class([_('Bad pin')]) Works, i see translated version in my language messages.add_message(self.request, messages.INFO, _('Bad pin')) Didn't work, in the template after entering {{message}}, I see the English oryginal version Settings.py 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', "account.middleware.LocaleMiddleware", 'django.middleware.common.CommonMiddleware', "account.middleware.TimezoneMiddleware", -
Calling quickbooks refresh token view in django
I am working on django project and integrating quickbooks. I am facing problem i want to call refresh token view after my access token is expired. I am using url and passing refresh token value to get new access token but i want it automatically that when access token is expired it will automatically generate new access token by calling refresh token view. How can i do it -
cannot add event in Fullcalendar Django
I cannot add event to the Fullcalendar. It seems like add_event in index.html and add_event in urls.py are not connected. I don't know how to connect between both of them. Every time I insert data in index.html, data that is saved in database is always empty but it is saved somehow. Please help me. I have tried so many things and it still doesn't work. index.html <!DOCTYPE html> <html> <head> <title>カレンダーサンプル</title> <link rel="stylesheet" href="{% static 'fullcalendar/calendar/css/fullcalendar.min.css' %}"/> <link rel="stylesheet" href="{% static 'fullcalendar/calendar/css/style.css' %}"> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <script type="text/javascript" src="{% static 'fullcalendar/calendar/js/moment.min.js' %}"></script> <script type="text/javascript" src="{% static 'fullcalendar/calendar/js/fullcalendar.min.js' %}"></script> <script type="text/javascript" src="{% static 'fullcalendar/calendar/lang/ja.js' %}"></script> <script> // ページ読み込み時の処理 $(document).ready(function () { // カレンダーの設定 $('#calendar').fullCalendar({ height: 550, lang: "ja", header: { left: 'prev,next today', center: 'title', right: 'month,basicWeek,basicDay' }, events: [ {% for event in events %} { title: "{{ event.title}}", start: '{{ event.start|date:"Y-m-d" }}', end: '{{ event.end|date:"Y-m-d" }}', id: '{{ event.id }}', }, {% endfor %} ], timeFormat: 'HH:mm', selectable: true, selectHelper: true, navLinks: true, // eventSources: [{ // url: '/fullcalendar/calendar', // dataType: 'json', // async: false, // type : 'GET', // error: function() { // $('#script-warning').show(); // } // }], select: function(start, end, resource) { var title = prompt("予定タイトル:"); var … -
How to access the selected option in an select tag with Django (not using Javascript)?
I have a form that has a select tag and dynamically created options for that tag as shown below. I want to access the selected tag if it is included in the POST request as part of the form in my Python/Django code: <form action="{% url 'newprogram' %}" method="post" novalidate> {% csrf_token %} TODO: Add Program to School <select name="schooloptions"> {% for school in schools %} <option value="{{ school.name }}">{{ school.name }}</option> {% endfor %} </select> <div class="form-group"> <input autofocus class="form-control" type="text" name="programname" placeholder=""> </div> <input class="btn btn-primary" type="submit" value="Post"> </form> I want to select the option that the user selects from the drop-down menu as follows but it does not work: @login_required def newprogram(request): if request.method == "POST": programname = request.POST["programname"] school = request.POST["schooloptions"].selected() #This does not work and is what I need help with schoolobj = School.objects.get("school") school = Program(School=schoolobj, name=programname) school.save() return render(request, "network/index.html") Any thoughts as to how I can access the selected option from a select HTML tag within a form? -
django.db.utils.DataError: (1406, "Data too long for column 'barcodes' at row 1")
I'm trying to make a program which take values of barcodes with barcode scanner and save the values of barcodes in db, problems occurs when I try to add more than 5-6 barcodes. It gives me "django.db.utils.DataError: (1406, "Data too long for column 'barcodes' at row 1")" error. I've made sure that its a model.textfield() but that doesn't solve my problem. My models look like this: id = models.IntegerField(primary_key=True) barcodes = models.CharField(max_length=255) to_warehouse = models.CharField(max_length=255) from_warehouse = models.CharField(max_length=255) total_count = models.IntegerField() approval_flag = models.IntegerField(default=0) current_status = models.CharField(max_length=50, blank=True, null=True) error_message = models.CharField(max_length=255, blank=True, null=True) created_by = models.CharField(max_length=50, blank=True, null=True) created_at = models.DateTimeField(blank=True, null=True, auto_now_add=True) class Meta: managed = False db_table = 'transfer_inventory' def __str__(self): return "%s" % self.id My view function that creates the obj for that looks like this: def change_status(self, barcodes, warehouse_id, request, is_error="", msg=""): barcode_count = barcodes.count(',') _list_barcodes = barcodes.split(",") print("list: ", list) list_barcodes = [] to_warehouse = Warehouse.objects.filter(id=warehouse_id).values_list('key', flat=True)[0] try: current_warehouse = UserWarehouseMapping.objects.filter( user=request.user).values_list('warehouse__key', flat=True).first() except: current_warehouse = "-" for i in _list_barcodes: list_barcodes.append(i) list_barcodes = list_barcodes.pop(len(list_barcodes) - 1) available_barcodes = list( Inventory.objects.filter(inventory_status='available').values_list('barcode', flat=True)) InventoryTransfer.objects.create(barcodes=barcodes, to_warehouse=to_warehouse, total_count=barcode_count, created_by=request.user.username, from_warehouse=current_warehouse, current_status="Pending") In which specific this part is used to create obj: InventoryTransfer.objects.create(barcodes=barcodes, to_warehouse=to_warehouse, total_count=barcode_count, created_by=request.user.username, from_warehouse=current_warehouse, current_status="Pending") … -
Django Dynamic Object Filtering issue in Template
I have a page which lists the posts along with the photos associated with each post. However I am having trouble in filtering and sending photos from photo lists QuerySet as it us under loop of posts list query set. Any idea how to run filters for getting the photos as only the associated post in a template? <h2> Posts: </h2> {% for post in post_list %} {% include 'posts/list-inline.html' with post_whole=post post_photos=photo_list %} {% endfor %} Here from photo_list in need to filter out multiple objects having foreign key relationship with individual post. The QuerySet filter is not working here in the template. -
Store data programatically in django database once and exclude from running each time server starts
I want to fetched data from URL to database in Django but don't want execute each time server runs. What is good way to achieve this ? -
Navigation Links in Django
I would like to kindly ask you, because since 2 days I'm pretty concerned about that, how to set proper navigation on navigation bar to go back to the homepage or to go into further section such as e.g "contact" or "prices", Ill show quick example what I really mean: Home -- Prices -- Contact Being at the homepage I press "Home" button and of course it refreshes the site, because we are at the homepage. I press the Prices button and it goes into 127.0.0.1:8000/prices and everything seems to be okay now we are in the prices section page - Home -- Prices -- Contact but now when i press "Contact" it goes to 127.0.0.1:8000/prices/contact ,but I would like that to be 127.0.0.1:8000/contact, or by pressing now "home" it refreshes the site, its not going back into the homepage. Can you please give me tip what shall i do now? my urls.py (whole project) urlpatterns = [ path('admin/', admin.site.urls), path('', include('main.urls') ), ] my urls.py (application) urlpatterns = [ path('', views.home, name="home-page"), path('prices/', views.prices, name="prices-page"), path('contact/',views.contact, name="contact-page"), ] my views.py (application) def home(request): return render(request, 'home.html', {}) def prices(request): return render(request, 'prices.html', {}) def contact(request): return render(request, 'contact.html', {}) -
Django, Zappa - RuntimeError: populate() isn't reentrant
I am beginner of django and zappa. And I am trying to deploy django application using zappa on AWS lambda. Also, I'd like to connect RDS database (postgres). To create database, I entered "zappa manage dev create_db" Then, error message occurred as below. And I don't know how to solve this. Other solutions on the Internet didn't work for me. populate() isn't reentrant: RuntimeError Traceback (most recent call last): File "/var/task/handler.py", line 509, in lambda_handler return LambdaHandler.lambda_handler(event, context) File "/var/task/handler.py", line 240, in lambda_handler return handler.handler(event, context) File "/var/task/handler.py", line 372, in handler app_function = get_django_wsgi(self.settings.DJANGO_SETTINGS) File "/var/task/zappa/ext/django_zappa.py", line 20, in get_django_wsgi return get_wsgi_application() File "/var/task/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/var/task/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/var/task/django/apps/registry.py", line 81, in populate raise RuntimeError("populate() isn't reentrant") RuntimeError: populate() isn't reentrant zappa_settings.json is { "dev": { "django_settings": "test_zappa_13.settings", "aws_region": "ap-northeast-2", "profile_name": "default", "project_name": "test-zappa-13", "runtime": "python3.6", "s3_bucket": "zappa-rw2difr3r" } } django settings.py is INSTALLED_APPS = [ 'zappa_django_utils', ... ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'blah', 'USER': 'blahblah', 'PASSWORD': 'blahblah', 'HOST': 'postgres-instance-1.test1234.ap-northeast-2.rds.amazonaws.com', 'PORT': 5432, } } ... And, Django version == 2.2, Python version == 3.6, Zappa version == 0.45.1 Please help me to solve this problem. … -
How to return a response while method is still running
I have uploaded a Django App on Heroku (Free Tier) where the user can upload some .xlsx files and generate a final spreadsheet based on them. The main page consists of three buttons, Upload, Generate, Download and everything works perfectly when it has to do with small files. But When I upload bigger files the Generate process takes a lot longer which leads to error: H12 in Heroku. I tried working with rq as suggested by Heroku, but with no success. What am I doing wrong? Here is my views.py file def main(request): q = Queue(connection=Redis()) if request.method == "POST" and 'cta-button-generate' in request.POST: q.enqueue(webControl.generate_files()) return render(request, template_name='main.html') -
In Django/Javascript While showing all the values from db, check the checkboxes of few of these which were already selected for each row
I am a newbie to django. I have tried various options. Any help would be highly appreciable. Below is my code,I have pasted only required lines from my code. This is not the complete code: Note: section_data is of list type ( while adding from django, these are added via checkboxes only to DB ) I have this in my template.html <table class="table table-striped table-bordered zero-configuration"> <thead>//table headings here</thead> <tbody> {% for row in data %} <tr><td>{{row.class_name}}</td><td>{{row.section_data}}</td> <td><a href="#" data-toggle="modal" data-academic_year="{{row.academic_year}}" data-class_name="{{row.class_name}}" data-section_data="{{row.section_data}}" data-id="{{row.id}}" class="ls-modal"><i class="icon-note menu-icon"></i></a></td></tr> {% endfor %} </tbody> </table> On clicking 'icon-note' above, a popup will be opened, showing classname and section - This icon is utilized for edit. So,In this pop up I am showing all the sections available in DB, but with the help of JS I wanted to check all those values which were already selected for this while adding in DB via django itself : below is the code of the popup, which was written in the same html template as above <div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <div class="modal-body"> <div class="form-group"> <div class="form-check form-check-inline"> {% for row in section_vals %} <input type="checkbox" name="sections_checkbox_edit" … -
Why is my class-based view only working with GET?
I wanted to ask a question, but I kind of found an answer myself and wanted to share it here. Perhaps someone can even tell me what was happening. I created an UpdateView subclass like several times before. But when I got to the page via a button that was part of method=post form I only got an empty form. Was driving me mad. In the end, I found just incidentally that when I entered the URL again in the address bar the values were received from the database. I changed the form with the button from post to get and when I now click it to go to the UpdateView page, it works. But to be honest, I do not know why. CVBs are still mysterious for me ;) -
Reverse for 'newsdate' with no arguments not found. 1 pattern(s) tried: ['newsdate/(?P<year>[0-9]+)$']
I was trying Django Tutorials. I have used a navbar template and used it in base html file. And all other pages are inheriting that base file. But when on linking the newdate(name given in urls.py) I am getting this error NoReverseMatch at /newsdate/2020 Reverse for 'newsdate' with no arguments not found. 1 pattern(s) tried: ['newsdate/(?P<year>[0-9]+)$'] I visited http://127.0.0.1:8000/newsdate/2020 My database with contain one entry with date 2020, The selection of objects from database is getting completed as print("lol",artice_list) prints the item matching from database. Error: NoReverseMatch at /newsdate/2020 Reverse for 'newsdate' with no arguments not found. 1 pattern(s) tried: ['newsdate/(?P<year>[0-9]+)$'] Request Method: GET Request URL: http://127.0.0.1:8000/newsdate/2020 Django Version: 3.0 Exception Type: NoReverseMatch Exception Value: Reverse for 'newsdate' with no arguments not found. 1 pattern(s) tried: ['newsdate/(?P<year>[0-9]+)$'] Exception Location: /home/rishabh/anaconda3/lib/python3.7/site-packages/django/urls/resolvers.py in _reverse_with_prefix, line 676 Python Executable: /home/rishabh/anaconda3/bin/python Python Version: 3.7.4 Python Path: ['/home/rishabh/Documents/DjangoWorks/Learning/src', '/home/rishabh/anaconda3/lib/python37.zip', '/home/rishabh/anaconda3/lib/python3.7', '/home/rishabh/anaconda3/lib/python3.7/lib-dynload', '/home/rishabh/anaconda3/lib/python3.7/site-packages'] Server time: Sun, 26 Apr 2020 17:11:09 +0000 Error during template rendering In template /home/rishabh/Documents/DjangoWorks/Learning/src/templates/navbar.html, error at line 6 Reverse for 'newsdate' with no arguments not found. 1 pattern(s) tried: ['newsdate/(?P<year>[0-9]+)$'] 1 <nav> 2 <ul> 3 <li><a href="{% url 'home' %}">Home</a></li> 4 <li><a href="{% url 'news' %}">News</a></li> 5 <li><a href="{% url 'contact' %}">Contact</a></li> …