Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-autocomplete-light Shows Some ModelSelect2 Fields but not Others
I have a form that looks like this (forms.py): class TaskForm(ModelForm): """ Form based on the Task model. """ class Meta: """ Meta class to define TaskForm with built-in Django variables. Assigns Task as the model and explicitly defines which fields from Task are included. Overrides default widgets for some fields to allow autocomplete inputs, larger text inputs, and custom date inputs. """ model = Task fields = [ 'name', 'description', 'project', 'request', 'category', ] widgets = { 'name': ModelSelect2(attrs={'data-minimum-results-for-search': -1}), 'request': ModelSelect2(attrs={'data-minimum-results-for-search': -1}), 'project': ModelSelect2(url='p-autocomplete',), 'category': ModelSelect2(url='cat-autocomplete',), } Two of the fields have autocomplete views behind them, two do not. The two that do not have autocomplete views behind them do not show up as ModelSelect2 fields (with proper formatting) in the browser. One of the fields that has an autocomplete view behind it DOES show up with the proper formatting, and the other does not (and does not populate any values when clicked). Both autocomplete views are successful when navigating to them directly. Why would django-autocomplete-light formatting only be applied to specific fields in a form? -
How can I do to get the entries in an array?
Hello I have this table : id country begin end 1 US 2020-10-07 15:30 2020-10-07 16:30 2 US 2020-10-07 16:30 2020-10-07 18:00 3 US 2020-10-07 19:00 2020-10-07 20:00 4 SP 2020-10-08 15:30 2020-10-08 17:30 5 SP 2020-10-08 17:30 2020-10-08 18:30 And using Django I would like to put in an array the data like this : [{'country':'US', 'begin':'2020-10-07 15:30'; 'end':'2020-10-07 18:00'}, {'country':'US', 'begin':'2020-10-07 19:00'; 'end':'2020-10-07 20:00'}, {'country':'SP', 'begin':'2020-10-08 15:30'; 'end':'2020-10-08 18:30'}] I get my table with the following query : myTable = Table.objects.all().order_by('begin') For the two first lines I don't know how to implement that... Basically I want if the country is the same and if one end 1 is equals to one begin 2 I want to put this in a same element in my array with begin 1 and end 2. The line 3 stay like that because the begin 2020-10-07 19:00 is not equals to 2020-10-07 18:00 nor 2020-10-07 16:30 and the end 2020-10-07 20:00 is not equals to 2020-10-07 15:30 nor 2020-10-07 16:30. For the fourth and fifth line we noticed the country are not US but SP. Then, the end of the fourth line is 2020-10-08 17:30 and the begin of the fifth line is … -
Django edit model page not displaying part of form
Having an issue where in the models admin part of Django, part of the edit form is not available to edit. For example the URL to access this edit is /admin/association/event/914/ 'association' is the app 'event' is the model '914' is the ID I would normally expect to see something like this (not the same model, but shows the ability to edit it): However, I am only seeing this, where it's only showing the inlines and not the primary model: This is the admin.py code used: class EventAdmin(admin.ModelAdmin): prepopulated_fields = { 'slug': ['competition'] } list_display = ('id','event_date','competition','clubs','event_location','days','promote') exclude = ["old_comp_id", "old_club_id", "club"] inlines = [EventFilesInLine,EventSponsorsInLine,RaceMeetingDatesInLine] search_fields = ['id','competition','event_location','club__club_name'] date_hierarchy = 'event_date' list_filter = ('event_date','state','days','promote') ordering = ('-event_date',) actions = [training_ring_yes, training_ring_no] admin.site.register(Event, EventAdmin) -
write a custom redirection decorator in django
I am trying to write a variation of the following redirection decorator: def permanent_redirect(url): def outer(f): @wraps(f) def inner(request, *args, **kwargs): f(request, *args, **kwargs) return HttpResponseRedirect(url if not callable(url) else url()) return inner return outer although this redirect just fine, the issue with it is that it ignores rendered values, or generared files on the view it is placed. I am a bit of out of my game here honestly, how would I go about modifying this decorator so it takes what is outputed by the view into account? -
How Do I Get Django to Show Image Field From Model in Templates?
I am trying to get the uploaded image to show in the project template. Here is what my code looks like currently: projects.html {% extends "base.html" %} {% block content %} <h1>{{ project.title }} HELLO</h1> <div class="content-section"> <div class="media"> <img src="{{ project.image.url }}" alt="beach" width=250px height=250px /> </div> <div> <h5>About the project:</h5> <p>{{ project.description }}</p> <br> <h5>Technology used:</h5> <p>{{ project.tools }}</p> </div> </div> {% endblock content %} models.py class Project(models.Model): title = models.CharField(max_length=500, unique=True) description = models.TextField(max_length=500) tools = models.CharField(max_length=200) image = models.ImageField(default='default.jpg', upload_to="beach_photos", blank=True) def __str__(self): return f'{self.title}' views.py from django.shortcuts import render from django.http import HttpResponse from projects.models import Project def projects(request): project = { 'project':Project.objects.all() } return render(request, 'projects/projects.html', context = project) settings.py configuration (app is installed) STATIC_URL = 'static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' When I inspect the image element in the webpage, the source shows up as src="" None of the other calls to the model are appearing either. Any help would be appreciated. -
How to send a message to all consumers using Django Channels 3.0.0?
I am trying to develop an interface that contains a section that shows all active users. So, when a user connects to the WebSocket I want to send data to all connected consumers. Currently, I wrote a code that when the user connects it sends data to the connected user only. I want somehow to make the message be sent to all active users/consumers. This is the path to my WebSocket handler/view path('test_ws/', websocket.TestConsumer.as_asgi()), And here is the handler class NewsMentionConsumer(AsyncWebsocketConsumer): groups = ["newsmention1"] channel_name = 'news_mention' active_users = [] async def connect(self): await self.channel_layer.group_add(self.groups[0], self.channel_name) await self.channel_layer.group_send(self.groups[0], { 'type': 'send_updates', 'text': json.dumps({ 'id': self.scope['user'].id, 'username': self.scope['user'].username, 'active_users': self.active_users }) }) await self.accept() self.active_users.append(self.scope['user']) async def send_updates(self, event): # TODO: Make this send to all users/consumers await self.send(event["text"]) I am facing a problem understanding the examples in django.channels docs and tried using send_group function but it doesn't really work. Any suggestions? -
Django: Make a single DB call instead of iterating QuerySet
I have the following code that iterates the tags queryset, and for each item, creates a Department object and adds it to the departments list: departments: List[Department] = [] tags = Tag.objects.filter(id=some_id, type="department") for tag in tags: dept_id = tag.reference_id dept_name = tag.name parent_tag = Tag.objects.get(id=some_id, type="department", reference_id=tag.parent_reference_id) dept_parent_id = parent_tag.reference_id departments.append(Department(dept_id, dept_name, dept_parent_id)) However, as you can see, it is making multiple DB calls via Tag.objects.get(), which seems highly inefficient. Is there an efficient way to populate that departments list without making so many DB calls? TIA. -
Django Pagination Troubleshooting
views.py from django.shortcuts import render, get_object_or_404, redirect,HttpResponseRedirect from .models import Post, Comment from django.utils import timezone from .forms import PostForm from django.contrib.auth.decorators import login_required from django.contrib import messages from django.urls import reverse from django .core.paginator import Paginator, PageNotAnInteger, EmptyPage def post_index(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by("published_date") paginator = Paginator(posts, 4) page = request.GET.get('page') try: post_list = paginator.page(page) except PageNotAnInteger: post_list = paginator.page(1) except EmptyPage: post_list = paginator.page(paginator.num_pages) return render(request, "blog/post_index.html", {"posts": posts, "page": page, "post_list": post_list}) post_index.html {% extends "blog/base.html" %} {% block content %} {% for post in posts %} <article class="media content-section"> <img class= "rounded-circle article-img" src="{{ post.author.profile.profile_pic.url }}"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'profile' %}">{{ post.author }}</a> <small class="text-muted">{{ post.published_date }}</small> </div> <h2><a class="article-title" href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a></h2> <p class="article-content">{{ post.text }}</p> </div> </article> {% endfor %} <div class="pagination"> <div class="section-inner clearfix"> <p> {% if post_list.has_previous %} <a href="?page={{ post_list.previous_page_number }}">&lt; Prev</a> | {% endif %} {% if post_list.has_next %} <a href="?page={{ post_list.next_page_number }}">Next &gt;</a> {% endif %} <span>Page {{ post_list.number }} of {{ post_list.paginator.num_pages }}</span> </p> </div> </div> {% endblock %} Hi guys, i am trying to paginate my site but it doesn't work. The address bar shows that there are other … -
How can I edit a bootstrap modal id with a django model data
I have a django model called CrewMember that adds a user into a team/crew of other users. class CrewMember(models.Model): ROLE = ( ('Supervisor', 'Supervisor'), ('Operative', 'Operative'), ('Trainee', 'Trainee'), ) user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) site_work = models.ForeignKey(SiteWork, null=True, on_delete=models.CASCADE) role = models.CharField(max_length=200, null=True, choices=ROLE) I have a modal on the front end that checks if the user is sure they want to Delete the user as a crew member. I also have a modal for editing the users role and also sending a message to the user but I will just show you the delete modal because they are pretty much the same and all have the same problem. {% for crewman in crew_members.all %} {% if user_is_admin %} <div class="modal fade" id="delUserModal" tabindex="-1" role="dialog" aria-labelledby="delUserModal" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="delUserModal">Please confirm</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> Are you sure you want to delete {{crewman.user}} from the crew members list? </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal"> Close </button> <a class='btn btn-danger' href=" {% url 'delete_member' crewman.user.id crewman.site_work.id crewman.role%}"> Delete </a> </div> </div> </div> </div> {% endif %} {% endfor %} The modal is inside the for … -
How can I pass a model id from the url to a class based view?
I have a class-based view: class Create(View): note_id = None http_method_names = ['post', 'patch'] default_title = "You fool! This was left empty" default_body = "Why did you leave this blank :(" def dispatch(self, *args, **kwargs): method = self.request.POST.get('_method', '').lower() print('method = ', method) if method == 'patch': return self.patch(*args, **kwargs) elif method == 'post': self.post(*args, **kwargs) return super(Create, self).dispatch(*args, **kwargs) def post(self, note_id): date = datetime.date.today() title = self.request.POST.get('title', '') body = self.request.POST.get('note', '') # check for blank attributes if title == "": title = Create.default_title if body == "": body = Create.default_body note = Note(note_title=title, note_body=body, publish_date=date, edit_date=None) note.save() return HttpResponseRedirect(reverse('notes:note')) def patch(self, note_id): note = Note.objects.get(id=note_id) title = self.request.POST.get('title', '') body = self.request.POST.get('note', '') # if something changed if title != note.note_title or body != note.note_body: # check for blank attributes if title == "": title = Create.default_title if body == "": body = Create.default_body note.note_title = title note.note_body = body note.edit_date = datetime.date.today() note.save() return HttpResponseRedirect(reverse('notes:note')) and in url.py I have urlpatterns = [ path('<int:note_id>/create/', views.Create.as_view(), name='create'), path('<int:note_id>/edit/', views.Create.as_view(), name='edit') ] Previously, with function-based views the note_id would just be passed to the function automatically. I can not figure out the equivalent of this in class based … -
Django Channels - Chat Tutorial - Message received only on second tab
I have been following the official Django Channels tutorial on the Chat Room. ChatRoom - Synchronous Tutorial However, even following every steps and double checking, I keep on having the same issue: The tutorial mentions the fact that both users, accessing the same chat room (and thus same group name) should receive messages from each other in both browsers tabs opened. If I send a message from tab 1, I can't see my message in tab 1 and tab 2. If I send a message from tab 2, I can see the message duplicated on tab 2 nothing on tab 1. This issue arises on the synchronous tutorial and the asynchronous one as wel. Did anyone have the same issue? I can't see what I've done wrong while following the tutorial. I am using Django/Channels latest version 3.1.3 with Python 3.9 and the Redis version mentioned on the tutorial. Thank you. -
Django render json response html
I'm am trying to render a json response which returns a html page in the body after I send my parameters to the endpoint url but I haven't found any information of how to handle this in django. So far I was able to see the html in an empty template that I created using JsonResponse(response.text,safe=False) but it shows the html with the tags and all. I'm open to suggestions. Note: The json post is going to send all the parameters to the endpoint and in response I get an html page that I need to show the user for payment processing. headers = {'content-type': 'application/json'} url = 'https://paymentway.net/api.php' params ={ "ClientId": "", "FirstName": fname, "LastName": lname, "Email": email, "Amount": amount, "InvoiceNumber": InvoiceNum } response = requests.post(url, headers=headers, data= json.dumps(params)) -
ValueError: Field 'id' expected a number but got 'Die erste Meldung'. after adding an item via console
I'm trying to add an item into db.sqlite3 via command line In [10]: m = Meldung('Die erste Meldung', zeitstempel=datetime.today(), text='Nun kommt das klassische Hallo-Welt-Beispiel.') In [11]: m.save() but got this error: ValueError: Field 'id' expected a number but got 'Die erste Meldung'. Inside migrations\0001_initial.py below the field id of contentobject Meldung is declared as auto_created=True, but it seems it's not working as expected. How can I solve it? expected result Field 'id' is generated automated by db.sqlite3 environment Python 3.8.2 Django 3.1.3 models.py from django.db import models class Meldung(models.Model): titel = models.CharField(max_length=100) zeitstempel = models.DateTimeField() text = models.TextField('Meldungstext') class Kommentar(models.Model): meldung = models.ForeignKey( Meldung, on_delete=models.CASCADE, ) autor = models.CharField(max_length=70) text = models.TextField('Kommentartext') migrations\0001_initial.py # Generated by Django 3.1.3 on 2020-11-04 20:57 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Meldung', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('titel', models.CharField(max_length=100)), ('zeitstempel', models.DateTimeField()), ('text', models.TextField(verbose_name='Meldungstext')), ], ), migrations.CreateModel( name='Kommentar', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('autor', models.CharField(max_length=70)), ('text', models.TextField(verbose_name='Kommentartext')), ('meldung', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='news.meldung')), ], ), ] -
Django: (2013, 'Lost connection to MySQL server during query') in my deployed app but not in my locally ran version
I deployed my Django app on Google App Engine and I am getting this error for one of my Select queries. The MySQL DB is hosted remotely, the locally ran(runserver) app can connect to it with no issues. Things I've tried: Remade the DB and tables Raised the timeout variables in MySQL Raised the packet size The related query and the snippet: SELECT Marketplace from marketplace # Getting items to populate the ChoiceField with connections[db_connection].cursor() as c: c.execute("SELECT Marketplace from marketplace") marketplace = c.fetchall() for k in marketplace: for v in k: mkt_choices.append(tuple([v, v])) mkt_choices = tuple(mkt_choices) Number of entries found is 26, so size shouldn't be an issue I use 2 DB connections I expect this to be one of many queries to raise this issue so I would like to know what I am doing wrong. Traceback: Environment: Request Method: GET Request URL: https://[project].appspot.com/ Django Version: 3.1.2 Python Version: 3.8.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'users', 'pages'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', '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'] Traceback (most recent call last): File "/layers/google.python.pip/pip/django/db/backends/utils.py", line 82, in _execute return self.cursor.execute(sql) File "/layers/google.python.pip/pip/django/db/backends/mysql/base.py", line 73, in execute return self.cursor.execute(query, args) File "/layers/google.python.pip/pip/MySQLdb/cursors.py", line 206, … -
DJANGO ecommerce website help needed. Different orders have same OrderItems
So I am following this tutorial on YouTube to make an eCommerce website using DJANGO but the problem is that now that I'm done with the tutorial I realize something is wrong. So whenever i make a new order, that order has the order items in it, as Order model has a manytomanyfield with OrderItem. So I make one order and save it. But if i make a second order and then save it, the first order's order items will become equal to the second order which shouldn't happen. I've been at this for 4 hours now and I don't know what to do so I'd appreciate your help. Both Orders have different ref_codes so at least that is working properly. Screenshot of admin view of both orders are attached. Youtube tutorial : https://www.youtube.com/watch?v=YZvRrldjf1Y&t=12766s Models.py from django.db import models from django.conf import settings from django.shortcuts import reverse # Create your models here. CATEGORY_CHOICES = ( ('S', 'Shirt'), ('SW', 'Sport Wear'), ('OW', 'Outwear'), ) LABEL_CHOICES = ( ('P', 'primary'), ('S', 'secondary'), ('D', 'danger'), ) class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() discount_price = models.FloatField(default=0) category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = models.SlugField() description = models.TextField() def __str__(self): … -
Django Profile Pictures Only Showing On One Page, All Other Pages Have A Broken Picture Box
I am not sure why profile pictures are only showing up on one page within my Django Social Media Site. The other pages have a broken picture box. I think that Django is not reading the src of my img tag. Please let me know what you need to see. Thanks, Daniel -
Django REST Framework] AssertionError: Class Serializer missing "Meta" attribute
I'm following the DRF tutorial instructions at https://www.django-rest-framework.org/tutorial/1-serialization/ but an assertion error happened. Here are my codes.(They're exactly the same as the codes from the tutorial website.) I know that class: Meta is required when ModelSerializer is used. But here I used Serializer not ModelSerializer. models.py from django.db import models from pygments.lexers import get_all_lexers from pygments.styles import get_all_styles LEXERS = [item for item in get_all_lexers() if item[1]] LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS]) STYLE_CHOICES = sorted([(item, item) for item in get_all_styles()]) class Snippet(models.Model): created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, blank=True, default='') code = models.TextField() linenos = models.BooleanField(default=False) language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100) style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100) class Meta: ordering = ['created'] serializers.py from rest_framework import serializers from .models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES class SnippetSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) title = serializers.CharField(required=False, allow_blank=True, max_length=100) code = serializers.CharField(style={'base_template': 'textarea.html'}) linenos = serializers.BooleanField(required=False) language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python') style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly') def create(self, validated_data): """ Create and return a new `Snippet` instance, given the validated data. """ return Snippet.objects.create(**validated_data) def update(self, instance, validated_data): """ Update and return an existing `Snippet` instance, given the validated data. """ instance.title = validated_data.get('title', instance.title) instance.code = validated_data.get('code', instance.code) instance.linenos = validated_data.get('linenos', instance.linenos) instance.language = validated_data.get('language', … -
parse json object in django view
I have a form than i need to check if the emails on my form are valid or not here is my ajax code : <script type="text/javascript"> $(document).ready(function (event) { function ValidateEmail(mail) { if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(mail)) { var postEmail = $("div.postEmail"); if (!$("#members_email").val() == "" || !$("#members_email").val() == null) { $.post( "{%url 'validate_email' %}", { email: $("#members_email").val() }, function (data, status) { console.log("Data: " + JSON.stringify(data) + " " + status); postEmail.append(JSON.stringify(data)); // contaner.append("Data: " + JSON.stringify(data)); } ); }; console.log('email is true'); return (true); } console.log('email is false'); return (false) } and this is my code in django view: def validate_email(request): data = json.loads((request.POST.get('postEmail'))) status=True return JsonResponse(status, safe=False) it raises this error : TypeError: the JSON object must be str, bytes or bytearray, not 'NoneType' thanks in advance -
Page not found (404)- in every page of my project
i am new in django . i work on a project. i use crispy-form in my project. it is my users views :: from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm, PasswordChangeForm from django.contrib.auth import login, authenticate from django.views.generic import CreateView from django.contrib import messages from django.contrib.auth.mixins import LoginRequiredMixin class RegisterUser(CreateView): form_class = UserCreationForm template_name = 'users/register-user' def get(self, request, *args, **kwargs): return render(request, 'users/register-user.html', {'form': UserCreationForm()}) def post(self, request, *args, **kwargs): form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') password = form.cleaned_data.get('password1') user = authenticate(username=username, password=password) login(request, user) messages.success(request, f'Welcome, {username}!') return redirect('cars') return render(request, 'users/register-user.html', {'form': form}) class ChangePassword(LoginRequiredMixin, CreateView): form_class = PasswordChangeForm template_name = 'users/change-password' def get(self, request, *args, **kwargs): form = PasswordChangeForm(request.user) return render(request, 'users/change-password.html', {'form': form}) def post(self, request, *args, **kwargs): form = PasswordChangeForm(request.user, request.POST) if form.is_valid(): user = form.save() update_session_auth_hash(request, user) messages.success(request, 'Password changed!') return redirect('cars') return render(request, 'users/change-password.html', {'form': form}) it is my users urls:: from django.urls import path from users import views as users_views from django.contrib.auth import views as auth_views urlpatterns = [ path('', users_views.RegisterUser.as_view(), name='register_user'), path('change-password', users_views.ChangePassword.as_view(), name='change_password'), path('login', auth_views.LoginView.as_view(template_name='users/login.html'), name = 'login'), path('logout', auth_views.LogoutView.as_view(template_name='users/logout.html'),name='logout'), ] it is my car views :: from .models import Car, Repair from django.views.generic … -
django: redirect user after generating the download of a template
I need to redirect a user after he finishes filling up a form and clicking on download, which generate a pdf template and then downloads it. I have tried redirecting from the backend side in django as well as in client side with javascript and nothing makes it. here is what I currently have: USER INPUT VIEW. (notice it redirects toward a template, which contains the pdf format.) def New_Sales(request): #context = {} form = modelformset_factory(historical_recent_data, fields=('id','Id', 'Description','Date','Quantity', 'NetAmount', 'customer_name', 'invoice_number')) if request.method == 'GET': formset = form(queryset= historical_recent_data.objects.none()) #blank_form = formset.empty_form elif request.method == 'POST': formset = form(request.POST) #invoice_hidden_form = CreateInvoiceForm(request.POST) #blank_form = formset.empty_form if formset.is_valid(): #request.session['sale'] = formset.cleaned_data for check_form in formset: check_form.save() quantity = check_form.cleaned_data.get('Quantity') id = check_form.cleaned_data.get('Id') update = replenishment.objects.filter(Id = id).update(StockOnHand = F('StockOnHand') - quantity) update2 = Item2.objects.filter(reference = id).update(stock_reel = F('stock_reel') - quantity) request.session['sale'] = formset.cleaned_data #if invoice_hidden_form.is_valid(): #invoice_hidden_form.save() #print('invoice_hidden_form is saved successfully') #request.session['invoice'] = invoice_hidden_form.cleaned_data print(formset.cleaned_data) return redirect('/invoice/pdf/assembly/') PDF GENERATION + DOWNLOAD VIEW: def generate_pdf_assembly(request): data = request.session['sale'] invoice_number = data[0]['invoice_number'] print(data) #total_ht = request.session['sale'].get('NetAmount') rate_list = [] for index in range(len(data)): rate_list.append(round(data[index]['NetAmount']/data[index]['Quantity'],1)) total_ht = [] for index in range(len(data)): total_ht.append(data[index]['NetAmount']) print('total_ht', total_ht) total_ht = sum(total_ht) my_company = MyCompany.objects.get(id = 1) tva = … -
How to add an ImageField to the HTML and make it visible
I am trying make a proper ImageField so a user can change the image from the admin panel. But even know I see the image in the Media folder I still cannot see it on front page. setting.py STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = "/media/" model.py class HomePage(models.Model): name = models.CharField(max_length=10, blank=True) main_visual = models.ImageField(default="default.jpg", upload_to="homepage_pics") top_content_header = models.CharField(max_length=100, blank=True) top_content = models.TextField(max_length=100, blank=True) featured_groups_header = models.CharField(max_length=100, blank=True) featured_groups = models.TextField(max_length=100, blank=True) seven_groups_header = models.CharField(max_length=100, blank=True) seven_groups = models.TextField(max_length=100, blank=True) about_us_header = models.CharField(max_length=500, blank=True) about_us = models.TextField(max_length=500, blank=True) about_us_image = models.ImageField(default="about_us.png", upload_to="about_us_pics") def __str__(self): return f'{self.name}' views.py def home(request): if request.method == 'POST': form = ContactForm(request.POST or None) if form.is_valid(): sender_name = form.cleaned_data['name'] sender_email = form.cleaned_data['email'] message = "{0} has sent you a new message:\n\n{1}".format(sender_name, form.cleaned_data['message']) send_mail('New Enquiry', message, sender_email, ['warp.dev.group@gmail.com']) return HttpResponse('Thanks for contacting us!') else: form = ContactForm() context = { "homepage": HomePage.objects.filter(name="homepage").first(), "footer": Footer.objects.filter(name="footer").first(), 'form': form } return render(request, 'member/home.html', context) home.html <section class="site-section" id="about-section"> <div class="container"> <div class="row"> <div class="col-md-5 mr-auto"> <div class="text-left heading-wrap mb-5"> <h2 class="mt-0 mb-5">{{ homepage.about_us_header }}</h2> <p>{{ homepage.about_us }}</p> </div> </div> <div class="col-md-6 position-relative align-self-center"> <img src = {{ homepage.about_us_image }} alt="Image" class="img-overlap-1"> </div> </div> </div> </section> The about_us … -
Django ORM lookup syntax
I have a model Fruit, and fruit has orchards. class Fruit(): orchards = models.ManyToManyField('Orchard', blank=True) Each orchard belongs to a farm: class Orchard(): farm = models.ForeignKey('Farm', verbose_name='Farm', null=True, blank=True, on_delete=models.PROTECT) Every fruit is a seedling class Seedling(): fruit = models.ForeignKey('Fruit', editable=False, on_delete=models.CASCADE) Here is my attempt: queryset = Seedling.objects.all().filter(fruit__orchards__in__farm=farm_id) This gets me an error django.core.exceptions.FieldError: Related Field got invalid lookup: in Anyone able to clear up my query? Much appreciated -
Django CMS dinamically image
i need to change dinamically image background-image css from home page in django cms, but is imposible. home CSS CODE The css has the welcome-image-area class the user needs to change the image url in the cms. .welcome-area { height: 100%; } .welcome-image-area { position: relative; height: 100%; background-image: url(../images/bg/bg.jpg); background-size: cover; z-index: 1; } .welcome-image-area:after { position: absolute; background: rgba(0, 0, 0, .7); left: 0; top: 0; width: 100%; height: 100%; content: ""; z-index: -1; } HTML CODE base.html <div id="welcome-image-area" class="welcome-image-area" data-stellar-background-ratio="0.6" > <div class="display-table"> <div class="display-table-cell"> <div class="container"> <div class="row"> <div class="col-md-12 text-center"> <div class="header-text"> <h2>{% static_placeholder 'mensaje bienvenida' %}</h2> <p>{% static_placeholder 'sub mensaje bienvenida' %}</p> <a class="smoth-scroll hire-us-slide-btn" href="#service">Servicios <i class="fa fa-hand-pointer-o btn-hire-us" aria-hidden="true"></i></a> <a class="slide-btn smoth-scroll" href="#contact">Contactanos <i class="fa fa-hand-pointer-o btn-contact-us" aria-hidden="true"></i></a> </div> </div> </div> </div> </div> </div> </div> -
Why is my Django form not "valid"? Can't get the POST request to update database
I am trying to create a user profiles for users in my Django app. I have the form displaying where I want it to and when I try to submit, nothing happens. I put a print statement after the form.is_valid in my view.py and found that it wasn't 'valid' but I have no idea why. I have tried several different ways to 'clean' / 'validate' data but I can't get past the form being 'invalid.' Any help would be greatly appreciated! urls: path('userinfo/', views.user_info, name='userinfo') form template: {% extends "base.html" %} {% load bootstrap4 %} {% block content %} <div class="container"> <h1>Enter User Info</h1> <form method="POST" class="form"> {% csrf_token %} {% bootstrap_form form %} <input type="submit" class="btn btn-primary" value="Create Profile"> </form> </div> {% endblock %} view: def user_info(request): form = ProfileForm() if request.method == 'POST': form = ProfileForm(request.POST) if form.is_valid(): form.save() else: form = ProfileForm() return render(request, 'miraDashboard/form.html', context={'form': form}) model: from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) name = models.CharField("Full Name", max_length=1024) job_role = models.CharField("Role", max_length=254, default="Seeking Job Opportunities") zip_code = models.CharField("Zip Code", max_length=5) user_image = models.ImageField("Upload Profile Picture", upload_to='images/') def __str__(self): return f'{self.user.username} Profile' form: from django.forms import ModelForm from .models import … -
Trying to populate Django app database with Faker
I am trying to populate Django database with Faker. I created a Django project (name = first_project) and then I created a Django app (name = first_app). I created models in my app and then I created a file named 'populate_first_app.py' in my main first_project folder(the one which contains manage.py) and filled in with the following code: import os os.environ.setdefault('DJANGO_SETTINGS_MODULE','first_project.settings') import django django.setup() import random from first_app.models import Topic,Webpage,AccessRecord from faker import Faker fakegen = Faker() topics = ['Search','Social','Marketplace','News','Games'] def add_topic(): t = Topic.objects.get_or_create(top_name=random.choice(topics))[0] t.save() return t def populate(N=5): for entry in range(N): top = add_topic() fake_url = fakegen.url() fake_date = fakegen.date() fake_name = fakegen.company() webpg = Webpage.objects.get_or_create(topic=top,url=fake_url,name=fake_name)[0] acc_rec = AccessRecord.objects.get_or_create(name=webpg,date=fake_date)[0] if __name__ == '__main__': print("populating script!") populate(20) print("populating complete!") after making migrations and running the code, my terminal shows: (MyDjangoEnv) E:\Django\first_project>python populate_first_app.py populating script! Traceback (most recent call last): File "populate_first_app.py", line 34, in <module> populate(20) File "populate_first_app.py", line 28, in populate webpg = Webpage.objects.get_or_create(topic=top,url=fake_url,name=fake_name)[0] File "C:\Users\vedan\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\vedan\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\query.py", line 573, in get_or_create return self.get(**kwargs), False File "C:\Users\vedan\anaconda3\envs\MyDjangoEnv\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\vedan\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\query.py", line 942, in filter return self._filter_or_exclude(False, *args, **kwargs) File …