Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass django user authentication data to react app?
I am doing a project by using django as front and back-end. But recently I want to attach another react page on this project. So, what I want to do is passing the user's info and mounting inside react. Below is my django's structure, I bundled my react app and put it on django's front-end (inside a toolbar). Normally, in django front-end, using request.user can get user's auth data. But how can I pass it to my react page? Thanks in advance! **urls.py:** url(r'test/', TestView, name='TestView') **views.py** def TestView(request): template_name = 'test.html' context = {} return render(request, template_name, context) **test.html:** <!DOCTYPE html> <html lang="en"> <noscript>You need to enable JavaScript to run this app.</noscript> <div id="root" style="height:100%"></div> <script src="../../../test_bundle.js"></script> </html> **main_html.py:** <div class="item"> <div class="ui dropdown" id="test"> <a class="item" onclick="load_test();">Test Component</a> </div> </div> <script> function load_test() { div_reload('#test', '/test/', 'GET', 'html'); } </script> -
drag and drop web page builder that we can export the source code to use in a Django project?
Is there any drag and drop web page builder (same as elementor) that we can export the source code to use in a Django project? -
Remove an item and reverse URL lookup at same time
I am building a calendar application in Django. I have implemented functionality to let a user add/remove Highlights to his/her week. Since the highlights are rendered on each individual week's page, I want to return the user to that page after deleting the highlight from the database. However, my remove_note() method takes 2 parameters (request, note_id). In the method, I query the database for the week associated with that note so that I can redirect the user to the week_view of the corresponding week_number. My thought - is there a way to pass note_id and week_number from the week_view.html to reduce database calls? I tried but couldn't quite get there myself. Thank You! views.py from django.shortcuts import render, get_object_or_404, redirect from week.models import Week, Note from week.forms import NoteForm def index(request): week_list = Week.objects.filter(user_id=request.user.id).order_by('week_number') context = { 'week_list': week_list, 'cal_width': range(52), } return render(request, 'cal/index.html', context) def week_view(request, week_number): if request.method == "POST": week = get_object_or_404(Week, week_number=week_number, user_id=request.user.id) form = NoteForm(request.POST) if form.is_valid(): form = form.cleaned_data new_note = Note(text=form['text'], week=week) new_note.save() context = { 'week': week, 'form': NoteForm(), 'notes': week.note_set.all(), } return render(request, 'cal/week_view.html', context) else: week = get_object_or_404(Week, week_number=week_number, user_id=request.user.id) context = { 'week': week, 'form': NoteForm(), 'notes': week.note_set.all(), … -
How can i handle django nested models in front-end?
I have a User, Post and Tag model in Django. Tag model is not relevant for this topic. I am trying to get all the data in the front end with nested objects. I can succesfully did that.When i want to create a new post i send the post data to django and in django view i update the data with current logged user but when i do that it gives me; {'owner': {'non_field_errors': [ErrorDetail(string='Invalid data. Expected a dictionary, but got int.', code='invalid')]}} error. How can i achive what I want ? models.py; class Post(models.Model): # Post specs title = models.CharField(max_length=100, null=False) place = models.CharField(max_length=100, null=False) notes = models.CharField(max_length=10000, null=False) tags = models.ManyToManyField(Tag) start_date = models.DateField(null=True) end_date = models.DateField(null=True) created_at = models.DateField(auto_now=True) owner = models.ForeignKey(User , null = True, on_delete=models.SET_NULL) serializers.py; class PostSerializer(serializers.ModelSerializer): tags = serializers.SlugRelatedField( many=True, queryset=Tag.objects.all(), slug_field='name' ) owner = UserSerializer() class Meta: model = Post fields = ('title','place','notes','start_date','end_date','created_at','id','owner','tags') and view post function; def post(self, request, format =None): """ Creates a post """ print(request.data) post = request.data post.update( {'owner':request.user.id}) serializer = PostSerializer(data = post) if serializer.is_valid(): serializer.save() return Response(serializer.data, status = status.HTTP_201_CREATED) print("not valid->",serializer.errors) return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST) -
DJANGO: About linkinf wto tables with ForeignKey
Hello all and thanks for all the DAILY support, really. Now, something I swear can not find answred in between many examples and related topics: I have a VEHICLES model, and a TIRES model. Both will be linked by a field, PLATE; class Vehicles(models.Model): Plate= models.CharField(max_length=10) Quantity = models.IntegerField(default=0) Vendor = models.CharField(max_length=50) def __str__(self): return self.matricula class Tires(models.Model): Plate = models.ForeignKey(Vehicle, default=0, on_delete=models.SET_DEFAULT) # --- tires would be placed in an exisiting vehicle (plate), or , if not in use, "Tires.Plate=0" Number = models.IntegerField(unique=True) What I need these two allow me to do, an what they really do or do not: Adding records to Vehicles.................YES Adding tires with predefined Plate numbers in a dropdown menu, from Vehicles.Plates....................YES, CHECK Adding tires with Plate number = 0, indicating the tire is not in use by any vehicle.......NO, NOT CHECKED; the menu offers only the exisiting plates in "Vehicles.Plate": Even if I tried adding DEFAULT value. Deleting registers from TIRES.........CHECK Deleting registers from VEHICLES.......NOT CHECKED; doing so, instead of making the corresponding Tires.Plate default to 0, as I would have expected from "...ForeignKey(Vehicle, default=0, on_delete=models.SET_DEFAULT)", I get a "FOREIGN KEY constraint failed" error. So indeed by removing the vehicle i'm causing the error … -
How to extends html file in Django
I want to extend my html file with base.html from template folder inside main my project folder. When I type: {% extends 'base.html' %} it gives me this: TemplateDoesNotExist at /app/ base.html Request Method: GET Request URL: http://127.0.0.1:8000/app/ Django Version: 3.0.4 Exception Type: TemplateDoesNotExist Exception Value: base.html Hope I will get some help :) -
Django HTML template table rendering
I want to render a table look like this: <table> <tr> <td>some data</td> <th>special one</th> <td>some data</td> ... <td>some data</td> </tr> ... </table> There is a solution that can render all in the same tag. <table> {% for rowval in results %} <tr> {% for val in rowval %} <td>{{val}}</td> {% endfor %} </tr> {% endfor %} </table> But in my case, there would be a th at the second place for every row of the data, if there is a record. Is there a way to implement this feature? -
Annotate in subquery django
I have a problem with this query: ProductoModel.objects.annotate(suma=Subquery(ValoracionNModel.objects.filter(producto=OuterRef('pk')).values('puntaje').annotate(sum=Sum('puntaje')).values('sum'))) In SQL: SELECT Negocio_productomodel.id, Negocio_productomodel.nombre, Negocio_productomodel.descripcion, Negocio_productomodel.precio, Negocio_productomodel.foto, Negocio_productomodel.aliado_id, Negocio_productomodel.tipo_producto_id, (SELECT SUM(U0.puntaje) AS sum FROM Negocio_valoracionnmodel U0 WHERE U0.producto_id = Negocio_productomodel.id GROUP BY U0.puntaje ORDER BY NULL) AS suma FROM Negocio_productomodel' Error: django.db.utils.OperationalError: (1242, 'Subquery returns more than 1 row') Can you Help me, please? I know the problem in SQL is the GROUP BY, but I don't know how remove this in Django. -
Debugger Docker Containers with Visual Studio Code
I have a Django project in Visual Studio Code. I start it through a virtual machine (linux) using Docker. I want to be able to debug the project by adding breakpoints. I tried following this tutorial, but can't get it: https://code.visualstudio.com/docs/containers/debug-python The application starts in "localhost: 8000", the private IP of the physical machine is 192.168.0.102 and that of the virtual machine: 192.168.56.1. My file launch.json: { "name": "Python: Remote Attach", "type": "python", "request": "attach", "port": 8000, "host": "localhost", "pathMappings": [ { "localRoot": "${workspaceFolder}", "remoteRoot": "/code" } ] } Thanks! -
Django swapping field values
I have a Django model I am developing locally like: import uuid from django.db import models class MyModel(models.Model): uuid = models.UUIDField( _('Non-sequential key for external lookups'), default=uuid.uuid4, editable=False, null=False, unique=True, ) This resulted in a migration like: from django.db import migrations, models import uuid class Migration(migrations.Migration): operations = [ migrations.CreateModel( name='MyModel', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('uuid', models.UUIDField(unique=True, default=uuid.uuid4, editable=False, verbose_name='Non-sequential key for external lookups')), ] This was working great initially; objects I created had both an incrementing integer id and a uuid property, with id mapped to pk. Fast forward a week, and I need to rebuild the database to retest a migration script I'm writing. The script fails, and when I dig into it, I discover that the ID and UUID fields are swapped: $ ./manage.py shell >>> from my_model import MyModel >>> item = MyModel.objects.first() >>> item.pk UUID('cee60e6b-aa2e-48a2-a34c-4315ebacea0b') >>> item.id UUID('cee60e6b-aa2e-48a2-a34c-4315ebacea0b') >>> item.uuid 45384 Has anyone else ever run into anything like this? I'm baffled over what the heck is going on, or what might have changed. The database side looks fine (primary key on the id column, and unique index on the uuid column); it's just Django's mapping that's all screwy. I'm running Django 2.2.9. -
Django - How to use two queries with select_related and render two different type of values in template?
I have the following models: class BillType(models.Model): name = models.CharField(max_length=200) created_on = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.name and the next one: class Bill(models.Model): bill_type = models.ForeignKey(BillType, on_delete=models.CASCADE, related_name='billtype') month = models.CharField(max_length=200) amount = models.IntegerField() due_date = models.DateField(blank=True) note = models.TextField(blank=True) recurring = models.BooleanField(default=True) currency = models.CharField(max_length=100) created_on = models.DateField(default=datetime.now, blank=True) def __str__(self): return self.month In views.py I am fetching all BillType objects and all objects from the Bill model which are related to BillType. However, I will need to fetch all of the objects in the same Bill model based on the due_date column or objects which are overdue, or in other words older than "today". I have tested the last part and it is returning all objects that are older than "today". def billingOverview(request): bill_types = BillType.objects.all() bills = Bill.objects.select_related('bill_type').all() today = datetime.today() overdue = Bill.objects.select_related('bill_type').filter(due_date__lte=today).all() context = { 'bill_types': bill_types, 'bills': bills, 'overdue': overdue } return render(request, 'management/billing-overview.html', context) In the template, I will need to render BillType objects separately in a different container for each of them, for which I have created For loop and it is working well so far. However, for each rendered BillType object, I have Overdue and Latest Bill areas. The first … -
I've been trying to get my images to upload on my website but can't seem to find the media link
`I have 4 classes. A parent able called Product. I also have Category and Variations. I've already migrated everything successfully. I can't see any issues there, and i can see it in my admin. <pre> class Product(models.Model): name = models.TextField() slug = models.SlugField(null=True, unique=True) description = models.TextField() stock = models.SmallIntegerField() price = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return self.name def get_absolute_url(self): return reverse('product_list_by_category',args=[str(self.slug)]) class ProductImage(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) image = models.ImageField(upload_to='images/', blank=True) featured = models.BooleanField(default=False) thumbnail = models.BooleanField(default=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) active = models.BooleanField(default=True) def __unicode__(self): return self.product.name Here i tried to link my images to media. When i add images to the product it works as a new file is created with the images I added. STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'assets'), ) CRISPY_TEMPLATE_PACK = 'bootstrap3' CRISPY_TEMPLATE_PACK = 'bootstrap4' LOGIN_REDIRECT_URL = '/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') `How i got my products to display def product(request, category_id=None): category = None products = Product.objects.all() ccat = Category.objects.annotate(num_products=Count('products')) if(category_id): category = get_object_or_404(Category, slug=category_id) products = products.filter(category=category) return render(request, 'product.html', {'products':products, 'countcat':ccat}) How I tried to display the images on the website ``` {% for product in products %} {% for item in product.productimage_set.all %} <img src="{{ … -
How do i write this code more pythonic way
I am writing Django's views to check if a valid album id is provided or not. But it looks cumbersome and hard to read. I want to make it more readable and short. I cant directly check data['id']. It will give error if its blank. def post(self, request): if len(request.body) > 0: data = json.loads(request.body.decode('utf-8')) else: return Response({'message': 'Album id is required'}) if 'id' not in data: return Response({'message': 'Valid Album id is required'}) try: id = int(data['id']) if id < 1: return Response({'message': 'Valid album id is required'}) album = Album.objects.get(pk=id) except: return Response({'message': 'Valid album id is required'}) -
Django generates too many SQL queries for models.ForeignKey
A Model class has a foreign key (models.ForeignKey) referring to another Model class. Django generates too many SQL queries for this foreign key. When a admin.StackedInline class uses the Model class, it tries to make a select list containing all items in the referred-to table (ProductTemplate in sample code below). Is there a way to limit the foreign key to only list one item, instead of all items in the referred-to table? Any other suggestions will also be highly appreciated. Let me know if you need more details. In file admin.py: ... class TransactionAttributeInlineAttribute(admin.StackedInline): model = models.TransactionAttribute verbose_name = 'Transaction Link' verbose_name_plural = 'Product Links' class MyAttributeAdmin(admin.ModelAdmin): inlines = [TransactionAttributeInlineAttribute] list_display = ['name','datatype','required'] ... In file models.py: ... class TransactionAttribute(models.Model): product_template = models.ForeignKey(ProductTemplate) ... -
how to check if a manytomany field object exist in detailview template
I want to search in a ManyToManyField in the DetailView. It works fine if a user with the same query exist, but if there isn't a user, i get page not found error. models.py: class agents(models.Model): agent_type = models.ForeignKey(types, on_delete=models.SET_NULL, blank=True, null=True) name = models.CharField(max_length=100) users = models.ManyToManyField(user_models.users, through='user_agent') views.py: class AgentDetailView(LoginRequiredMixin, generic.DetailView): model = models.agents template_name = 'agent/agent_detail.html' def get_queryset(self): query = self.request.GET.get('q') if query: return models.agents.objects.filter(Q(users__user__first_name__contains=query) | Q(users__user__last_name__contains=query) | Q(users__id_number__contains=query) | Q(users__mobile__contains=query)) else: return models.agents.objects.all() agent_detail.html: <h1>name: {{ agents.name }}</h1> <form method="GET" action="" id="searchform"> <input class="searchfield" id="searchbox" name="q" type="text" placeholder="Search..."/> <button name="search" type="submit" value="{{ request.GET.q }}">Search</button> </form> {% if agents.users %} <p><strong>Users:</strong> <br> {% for users in agents.users.all %} <li>{{ users }}</li> <hr> {% endfor %} </p> {% else %} <p>There are no user for this agent in database.</p> {% endif %} -
Cannot oversave model imagefield DJANGO
I'm encountering weird problem with updating image. I do not receive any error, it just doesn;t get saved to the MEDIA_ROOT folder. If I do it manually via admin_site it works. When i'm using the forms, the above happens. views.py: if request.method == "POST": pass_change_form = UserUpdatePasswordForm(data=request.POST, user=request.user) avatar_change_form = UserUpdateAvatar(data=request.POST, files=request.FILES, instance=request.user.profile) if avatar_change_form.is_valid(): avatar_change_form.save() print(avatar_change_form) messages.success(request, 'The avatar has been changed') return redirect('profile') else: messages.warning(request, 'Please fill the fields correctly') return redirect('password-change') forms: class UserUpdateAvatar(forms.ModelForm): class Meta(): model = Profile fields = ["avatar"] models: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(default="default.jpg", upload_to="profile_avatars") def __str__(self): return f'{self.user.username} Profile' -
Overriding default django project structure
Is it possible to override the default project structure in Django? I'm trying to put all my django apps in a src folder but it seems like it is not that easy. When i try to run my dev server, i get the error "ModuleNotFoundError: No module named 'django_project'". Here is my current Project Structure. -
Django - How to return to default image after users delete their uploaded image?
So I originally had the user create a post in admin and be able to leave image field blank and Django would set a default image. My problem is; If a user uploads an image, then deletes the image, I get an error: The 'image' attribute has no file associated with it. How can I make the default image reappear and specifically come from static folder? My code: urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py # FIXME: If default image is changed to user's upload but then deleted. Make default image reappear. # Recipe Field class Recipe(models.Model): title = models.CharField(max_length=200) image = models.ImageField(upload_to='recipes/images/', blank=True) def get_image(self): if not self.image: return f'{settings.STATIC_URL}default.png' return self.image.ur solo.html <h2>{{ recipe.title }}</h2> <h3>{{ recipe.category }}</h3> <h3>{{ recipe.meal }}</h3> <img src="{{ recipe.image.url }}"> I'm just starting with Django so I apologize in advance if it's all a mess. Thank you in advance! -
using more than one button in same view in django
I am trying to make a "next" and "back" buttons for displaying 5 elements of my database, every time you click on "next" button, it will display the next 5 elements and if you click "back" button, it will show the 5 previous elements. The error that shows up is Request Method: POST Request URL: http://localhost:8000/notificacions/ Django Version: 3.0.3 Exception Type: MultiValueDictKeyError Exception Value: 'back' my python code in views is: if request.method == 'POST': if request.POST['next']: for element in range(5): show_notifications.append(notifications_list[the_counter]) the_counter+=1 elif request.POST['back']: the_counter-=10 for element in range(5): show_notifications.append(notifications_list[the_counter]) the_counter+=1 and my html code is: {% csrf_token %} BackNext -
Take value from other model in model connected FroeignKey
I wanna to two models: - Tasks - Paths (contain in Tasks) I created that two models: class Tasks(models.Model): task_type = models.IntegerField() url = models.TextField() status = models.IntegerField() class Paths(models.Model): tasks = models.ForeignKey(Tasks, on_delete=models.CASCADE) path = models.TextField() But i want to create rest api aplication and i want to have in model PATHS the thrid value Tasks_ID(ID from ForeignKey) i tried: ... path = models.TextField() tasks_id = tasks.id But it isnt so simple. Please give me advise, how should i do this. -
Django project is always rendering the home/default page, some urls.py mapping problem
Stuck with a Django project, I have an app called resumeapp in ResPortal project. A button clicked on homepage 127.0.0.1:8000 is still staying in the same page even though the url is changed to http://127.0.0.1:8000/ApplicantPage For example 127.0.0.1:8000 will go to the homepage but 127.0.0.1:8000/ApplicantPage will also display the homepage even though I linked another view. Here is my code: project urls.py from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url('',include('resumeapp.urls')), ] resumeapp\urls.py from django.conf.urls import url from django.contrib import admin from .import views urlpatterns = [ url('', views.upload_page, name='upload-page'), url('ApplicantPage', views.upload_nextpage, name='upload-page2'), ] -
Django Class Post has no object members
Class 'Post' has no 'objects' member? Code Below--models file--> from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title Code Below--views file---> from django.shortcuts import render from .models import Post def home(request): context = { 'posts': Post.objects.all() } return render(request, 'blog/home.html', context) def about(request): return render(request, 'blog/about.html', {'title': 'About'}) please tell me this is an easy fix, I have no clue what could be wrong. using python3.7 for everything . It works on the server however in my code it says its an error. I don't like seeing errors, please help and thank you in advance. -
Django default information for model
I have 2 models (the Timeline one which will contain default information that I have to upload, and the Pdf one that contains the file and a relation to one of the timeline cells). I was told to create my own migration file and have done the following but I get this error and I can't find anything online about it: File "/Users/fetz/Desktop/parentsuportal/parentsuportal/timeline/migrations/0005_auto_20200324_1721.py", line 33, in addData Timeline(header = "Transport Support", age = "18-25") File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 520, in __hash__ raise TypeError("Model instances without primary key value are unhashable") TypeError: Model instances without primary key value are unhashable My models: HEADER_CHOICES = [ ('Financial Support', 'Financial Support'), ('Educational Support', 'Educational Support'), ('Governmental Support', 'Governmental Support '), ('Charity Support Groups', 'Charity Support Groups'), ('Therapy Support', 'Therapy Support '), ('Transport Support', 'Transport Support ') ] AGE_CHOICES = [ ('0-4', '0-4'), ('4-11', '4-11'), ('11-18', '11-18'), ('18-25', '18-25') ] class Timeline(models.Model): header = models.CharField(max_length=30, choices=HEADER_CHOICES) age = models.CharField(max_length=6, choices=AGE_CHOICES) class Pdf(models.Model): pdf = models.FileField(upload_to='timelinepdfs') timeline = models.ForeignKey(Timeline, on_delete=models.CASCADE) My migration file: from django.db import migrations def addData(apps, schema_editor): # We can't import the Person model directly as it may be a newer # version than this migration expects. We use the historical version. Timeline … -
Django - not receiving AJAX data sent
I make an AJAX call, which should send data to the backend. In the backend, I print the data that has been sent from the frontend, however None is returned. This is unexpected, as the network tab(in chrome) confirms the AJAX request was successfully made, with the correct data appended to it. This make me think something is wrong with the backend(Django). HTML(signup.html): <form id="signup_form"> {% for field in form %} {{ field }} <br> {% endfor %} <button class="signup-btn btn btn-primary">Sign up</button> </form> <div id="testbox"></div> Javascript/AJAX CODE: var delayTimer; $('#signup_form').keyup(function() { clearTimeout(delayTimer); delayTimer = setTimeout(function () { var usernameVal = $("#username_signup").val(); // This returns expected result(value in input box) console.log(usernameVal); $.ajax({ url: '/users/ajax/signup', data: { 'usernameVal': usernameVal, }, dataType: 'json', success: function(data) { $('#testbox').text(data['usernameVal']); } }); }, 1000); }); views.py: // Renders form and signup page def signup(request): context ={} form = SignupForm() context['form'] = form return render(request, 'signup.html', context) // Handles AJAX (This is the view AJAX calls (url = /users/ajax/signup)) def ajax_signup(request): form = SignupForm(request.GET) if form.is_valid(): // This line below is printed successfully print("WORKS") // This line below returns None unexpectedly print(form.cleaned_data.get("usernameVal")) return JsonResponse({'usernameVal': form.cleaned_data.get("usernameVal")}) else: print(form.errors) return JsonResponse({'hello': 'not working'}) -
mouse cursor trail effect in Django
I am trying to add a mouse trail effect on a Django web page. I have written code in js and css and now I am trying to include them in my base.html so I added "" in my body tag (after my nav bar, but before {% block content %} {% endblock %} ), but nothing happens on my actual webpage. Am I supposed to write that somewhere else?