Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to uninstall django-rest-swagger?
Is there a simple or elegant way to uninstall django-rest-swagger on Windows 10? I've recently started developing API's and creating documentation. I found a tutorial that used the django-rest-swagger app. After installing the app and doing more reading, I discovered that it was deprecated, and the developer's GitHub page recommends using drf-yasg. I tried using "pip uninstall django-rest-swagger," and that echoed back that the app was uninstalled. But, when I went into the virtual environment folder of the project, all the package folders were still there. I also tried "pipenv uninstall django-rest-swagger", but it returned "pipenv is not recognized..." I spent a few hours reading the app docs, and googling "how to remove/ uninstall django-rest-swagger." However, I didn't find anything useful. Eventually, I gave up, and decided to do it the hard way. I manually deleted all the installed files. Fortunately, I hadn't updated my requirements.txt, so, I knew what was originally installed. While this solution worked, it was somewhat time consuming. Does django-rest-swagger have an internal uninstall command? And does anyone know why "pip uninstall" didn't remove the app folders? Thanks -
Django - Pass multiple parameters from in a form action
I want to pass 3 values from my Template which are id, size & request.user template.html <form action='{{ id }}/{{ size }}/{{ request.user }}' method='GET'> . . <form> urls.py path("<id>/<size>/<user_name>", views.add_to_cart) That is what I have in mind which does not work for sure, so I wonder if there is a way to call a specific URL and then pass in some parameters which I can then use in my views.py file to query a specific object using the id from the database and edit something, I guess something like the following might explain what I mean: ./cart?id=00003,size='M',user=admin So is there a way to do this in Django, my bad if the question is dummie its first time I study back-end. -
How to use try and except in django?
I wanted to use try and except in djagno template is there is any way to use it. I want to check either attendance table has any data of not. and if not it has to show error text {% try %} {% for attendances in attendance %} .... {% endfor %} {% except %} <h1>Error Attendance table has no data.</h1> -
How can I use if inside if in django template
Hello Guys I want to create a card where if an authenticated user is equal to a certain post. So to show authenticated users these are his post in blue I want to add noteActive class. so anyone knows how to use if inside if in Django template?? index.html {% extends 'base.html' %} {% block title %} OctoNotes - Home {% endblock title %} {% block content %} <div class="noteDisplay"> {% if notes %} {% for note in notes %} {% if request.user == note.user %} <div class="noteCard noteActive"> {% else %} <div class="noteCard"> {% end if %} <div class="noteUser"> <p class="noteUserUsername">{{note.user}}</p> <div class="info"> <p class="noteUserPubDate">{{note.pub_date}}</p> {% if request.user == note.user %} <div class="info-btn"> <div></div> <div></div> <div></div> </div> <div class="noteDropDown"> <a href="#">Edit</a> <a href="{% url 'notes:deleteNote' note.id %}">Delete</a> </div> {% endif %} </div> </div> <div class="noteContent"> <h2>{{note.title}}</h2> <p>{{note.content}}</p> </div> </div> {% endfor %} {% else %} <p> No Notes, Create Your First Note.... </p> {% endif %} </div> {% endblock content %} -
Django file explorer
I need to create a Django file explorer. It needs to perform a similar function to the Simplehttpserver that comes with python. The main purpose is rendering static html files and making certain directories available for TEST users or ITOPS users etc. Need some advice how to do this. -
why column blog_post.category_id does not exist in django after hosting with heroku
I'm making a web application with django and I can run this application on localserver without any error.But when I host it gets a error like column blog_post.category_id does not exist LINE 1: ...d_on", "blog_post"."status", "blog_post"."image", "blog_post... By the way I run migrations for this application with heroku server.And also when I list tables in heroku using heroku pg:psql this command.After that I can see all the tables are created in heroku server.Do you have any suggestion. -
gunicorn: error: argument --error-logfile/--log-file: expected one argument - Procfile
When I run heroku open, it says that there is an application error. I run heroku logs --tails, this comes up: gunicorn: error: argument --error-logfile/--log-file: expected one argument I assume it's a problem with my Procfile, because my Procfile has something to do with --log-file. Heres my Procfile: web: gunicorn pages_project.wsgi --log-file - Please help me! -
How to render a table in Django from a class with manytomanyfield for all fields selected for an instance?
I am struggling to render a table view in Django 3.2 that will display data from instance of a class: class SalesPlan(models.Model): customer = models.OneToOneField(Customer, null=True, on_delete=RESTRICT) period = models.DateField() product = models.OneToOneField(Product, null=True, on_delete=RESTRICT) qty = models.DecimalField(max_digits=10, decimal_places=2, null=True) classes for customer and product: class Customer(models.Model): customer_code = models.CharField(max_length=6, primary_key=True, unique=True) customer_name = models.CharField(max_length=100) belongs_to_sales_channel = models.ForeignKey(SalesChannel, on_delete=RESTRICT) customer_portfolio = models.ManyToManyField(Product) date_created = models.DateTimeField(auto_now_add=True, null=True) class Product(models.Model): product_group = models.ForeignKey(ProductGroup, on_delete=RESTRICT) product_subgroup = models.ForeignKey(ProductSubGroup, on_delete=RESTRICT) item_code = models.CharField(max_length=5, primary_key=True) item_name = models.CharField(max_length=100) unit_of_measure = models.CharField(max_length=10) product_weight = models.DecimalField(max_digits=5, decimal_places=3) product_weight_text = models.CharField(max_length=10) I have tried a function based view and class based view. A class based view gives me one line for one product, since SalesPlan class is set like that. Is there a way to render rows for each product in Customer.customer_portfolio.all() with all data already set and only with quantity for a user to input? I have searched for similar examples, all I found is what I already have: class based view can display a form, for one instance (only one row). I failed using formset, I am currently researching if it's possible using a formset. -
Splitting settings.py in prod and dev causing a ModuleNotFoundError, why?
I am new to django and trying to deploy my app. I would like to split my settings in two (dev and prod). When I did python manage.py runserver with just one settings.py file, it worked perfectly. I have now the following folder structure: apps core pycache settings pycache init.py base.py dev.py prod.py init.py asgi.py urls.py utils.py wsgi.py media etc. base.py from pathlib import Path import os import sys from django.contrib.messages import constants as messages # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent sys.path.insert(0, os.path.join(BASE_DIR, "apps")) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = "my_secret_key" # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ "account.apps.AccountConfig", "address.apps.AddressConfig", "basket.apps.BasketConfig", "contact.apps.ContactConfig", "discount.apps.DiscountConfig", "home_page.apps.HomePageConfig", "la_marque.apps.LaMarqueConfig", "orders.apps.OrdersConfig", "payment.apps.PaymentConfig", "shipping.apps.ShippingConfig", "store.apps.StoreConfig", "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "django_extensions", ] 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", ] ROOT_URLCONF = "core.urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [BASE_DIR / "templates"], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", "basket.context_processors.basket", ], }, }, ] AUTH_USER_MODEL = … -
Failing to access Nginx server (Django + Docker + Postgres)
After following this excellent tutorial https://testdriven.io/blog/dockerizing-django-with-postgres-gunicorn-and-nginx/, I was able to create my own docker with Django + Postgres. However when I try to access my Nginx server (locally) I receive "This site can’t be reached" page: Which is weird because when I build my docker-compose.prod.yml and run it, everything seems to be working fine: Do you guys have any idea what might be causing this issue? Here is my code repo: https://github.com/MarioSilvaPrada/portfolio_v2 Dockerfile.prod: https://github.com/MarioSilvaPrada/portfolio_v2/blob/master/Dockerfile.prod docker-compose.prod.yml: https://github.com/MarioSilvaPrada/portfolio_v2/blob/master/docker-compose.prod.yml Thank you in advance! -
Javascripts not working after Django update
I updated my Django 1.9 application to Django 3.1 following the changes mentioned in the releases. The application is running, but the javascripts are not showing the same bevhavior. <a href="{% url field.label_tag|cut:field.label|striptags prj_pk=ProjectId %}" class="add-another" id="add_{{field.auto_id}}" onclick="return showAddAnotherPopup(this);"></a> This line previously showed + button to open a new form but now the + button is not seen on the webpage. What has changed with respect to Javascripts in Django 3.1? -
Is django.views.generic.edit.UpdateView same as CreateView
I am making a view that will create and update an object. I was looking at which view to inherit from, but it appears that CreateView and UpdateView are identical in principal. Any reason to choose one over the other? Create View: class BaseCreateView(ModelFormMixin, ProcessFormView): """ Base view for creating a new object instance. Using this base class requires subclassing to provide a response mixin. """ def get(self, request, *args, **kwargs): self.object = None return super().get(request, *args, **kwargs) def post(self, request, *args, **kwargs): self.object = None return super().post(request, *args, **kwargs) class CreateView(SingleObjectTemplateResponseMixin, BaseCreateView): """ View for creating a new object, with a response rendered by a template. """ template_name_suffix = '_form' And Update View: class BaseUpdateView(ModelFormMixin, ProcessFormView): """ Base view for updating an existing object. Using this base class requires subclassing to provide a response mixin. """ def get(self, request, *args, **kwargs): self.object = self.get_object() return super().get(request, *args, **kwargs) def post(self, request, *args, **kwargs): self.object = self.get_object() return super().post(request, *args, **kwargs) class UpdateView(SingleObjectTemplateResponseMixin, BaseUpdateView): """View for updating an object, with a response rendered by a template.""" template_name_suffix = '_form' -
Django custom authentication backend - "is_valid" calls authenticate
I am doing my custom auth backend for the first time, and it generally works, but i fail to understand a thing or two and there is some unwanted behaviour in my view. Basically i just wanted to add an additional mandatory field - domain name which would have to be filled in (or choosen) on login. So i have my custom DomainUser (AbstractUser) which defines additional "domainname" field class DomainUser(AbstractUser): domainname = models.CharField(max_length=50) REQUIRED_FIELDS = ['domainname', ] def __str__(self): return self.username @property def domainusername(self): return ''.join([self.domainname, '\\', self.username]) then there is the view: def domain_login(request): if request.method == 'POST': login_form = DomainLoginForm(data=request.POST) if login_form.is_valid(): username = login_form.cleaned_data.get('username') domainname = login_form.cleaned_data.get('domainname') raw_password = login_form.cleaned_data.get('password') user = authenticate(username=username, domainname=domainname, password=raw_password) if user is not None: login(request, user) return HttpResponseRedirect(reverse('admin:index')) else: pass # should return invalid logon page else: login_form = DomainLoginForm() context = { 'login_form': login_form, } return render(request, 'domain_auth/login.html', context) And the auth: class DomainLDAPBackend(BaseBackend): def authenticate(self, request, username=None, domainname=None, password=None): #return DomainUser.objects.get(username__iexact=username, domainname__iexact=domainname) return DomainUser.objects.get(username__iexact=username) def get_user(self, user_id): try: return DomainUser.objects.get(pk=user_id) except DomainUser.DoesNotExists: return None Auth is a complete placeholder for now (it doesn't really authenticates the use with domain, but that's just temporary), it's just for test purpose … -
How to order django rest framework search results by the query written?
I want to order my django search results (DRF) in the order it was written. For example when I search https://mywebsite.com/api/title=one,two,five,nine so the first result from the API should be Post One, Post Two, Post Five, and Nine and so on. Thanks in advance. -
django __date return None in MySQL
Simple question: Why Model.objects.values('some_datetime_field',) returns the datetimes while Model.objects.values('some_datetime_field__date',) returns Nones? -
Django - alter objects from different apps
I am working with several different django apps, which provides some data for another one: class WordpressSnapshot(models.Model): configuration = models.ForeignKey(WordpressServerConfiguration, on_delete=models.CASCADE, related_name='snapshots') created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s' % self.created_at class Post(models.Model): class Meta: unique_together = (('snapshot', 'slug'),) snapshot = models.ForeignKey(WordpressSnapshot, on_delete=models.CASCADE, related_name='posts') date = models.DateTimeField() excerpt = models.CharField(max_length=255) slug = models.CharField(max_length=255) title = models.CharField(max_length=255) content = models.TextField() author = models.ForeignKey(PostAuthor, on_delete=models.CASCADE, related_name='posts') media = models.URLField() def __str__(self): return '%s %s' % (self.slug, self.author) class WebSite(models.Model): name = models.CharField(max_length=255) .... posts = models.ForeignKey( "wordpress.WordpressSnapshot", on_delete=models.SET_NULL, null=True, blank=True ) pages = models.ManyToManyField(Page, null=True, blank=True) def __str__(self): return self.name Currently I'm creating a new WordpressSnapshot (which gets all posts from our blog), updating the posts field in WebSite, updating several other fields in the same fashion and after that - I am creating a new frontend object, which relies on data from WebSite. What is the best/the most django approach to hide all of that stuff behind a single click? Do I have to create a new model "BuildingSiteFacade" just to perform all this operations during creation of BuildingSiteFacade object? -
How do I diagnose django render speed problem?
I have been trying to figure out what is slowing down my requests, and all I can figure out is that there is some slowdown in the rendering of the response. I ran some tests of the query, serializer, and JSON rendering like this: client = Client.objects.get(user__username="pugdog") start = parse("2021-09-01T00:00:00-04:00") end = parse("2021-10-01T00:00:00-04:00") db_test_start_time = time() events = Event.objects.filter(client=client, start__gt=start, end__lt=end) list(events) db_test_end_time = time() factory = APIRequestFactory() request = factory.get('/') serializer_context = {'request': Request(request), } output = [] for event in events: serializer = EventReadSerializer(instance=event, context=serializer_context) output.append(serializer.data) renderer = JSONRenderer() json_output = renderer.render(output) serializer_test_end_time = time() print(f"query speed: {db_test_end_time - db_test_start_time}") print(f"serializer speed: {serializer_test_end_time - db_test_end_time}") print(f"Total time: {serializer_test_end_time - db_test_start_time}") The output is: query speed: 0.006450176239013672 serializer speed: 2.926229238510132 Total time: 2.9326794147491455 This is how long it takes to process the query and convert it to JSON, but when I try and pull this data using the API REST client "Insomnia", it takes around 43.8 seconds, which means that I am having a massive slowdown somewhere. I am running Insomnia on the same machine I am developing on, so there should be no network issue. This test is when I populate the database with 100 Event objects. I … -
React Table with filter controls outside of the table with Django as a server-side filtering engine
I'm trying to implement server-side filtering for my table using React Table. However, most of docs and articles I read online are implementing filters on column headers. My app layout, however, requires filters being a standalone component FilterComponent that sits outside of the table: return ( <> <FilterComponent columns={columns} /> <TableContainer className={classes.container}> ... </TableContainer> </> ); FilterComponent Component It's basically a list of Autocomplete components that allow users to pick columns and filter criteria. And users can use Add and Remove buttons to get more or fewer filters. return ( <div> {inputList.map((x, i) => { return ( <div className="box" key={i}> <Autocomplete ... /> // pick a column <Autocomplete ... /> // pick an operator ("=", ">", "<". etc.) <Autocomplete ... /> // pick a filter criteria <div className="btn-box"> {inputList.length !== 1 && ( <button className="mr10" onClick={() => handleRemoveClick(i)}> Remove </button> )} {inputList.length - 1 === i && ( <button onClick={handleAddClick}>Add</button> )} </div> </div> ); })} </div> Two Questions I use Django for the backend, and have configured filters properly so that you can just pass in some query parameters to the AJAX call to get desired result. Filter setups In react-table's example, it appears that we need to define "Filter" … -
Django Static Video Wont Play On Chrome or Edge
I have a landing page that is a Django project and hosted on Heroku. For some reason I cant get the landing page video to play on Chrome or Edge. Firefox it works fine, here is my html code. I cant seem to figure out why this tag wont work. Thanks for the help in advance. {% block content %} {% load static %} <html lang="en"> <br> <head> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous"> <!--Font Awesome--> <script src="https://kit.fontawesome.com/9571fdc7fc.js" crossorigin="anonymous"></script> <!--JS--> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script> <script src= "https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script> <!-- Custom CSS --> <link rel ="stylesheet" href={%static "forms/css/home-styles.css" %}> <title>Missing Link</title> </head> <body> <secion class ="showcase"> <header> <h2 class ="logo"> <img src="{% static "forms/chain.png" %}" alt="logo" class ="logo" height="42" width= "42"> Missing Link</h2> <div class = "toggle"> </div> </header> <video muted loop autoplay> <source src="{% static "forms/landing_video.mp4" %}" type="video/mp4"> </source> </video> <div class ="overlay"></div> <div class ="text"> <h2> IT Data Systems</h2> <h3> Believing In Something Better ! </h3> <p> </p> {% if user.is_authenticated %} <a class="btn btn-primary btn-lg" href="/dashboard" role="button">My Dashboard</a> {% else %} <p>If you arent a current user, please contact your local administrator. </p> <a class="btn btn-primary btn-lg" href="/account/login" … -
Django datatables view Related Field got invalid lookup: istartswith
I am trying to render a datatable using django datatables view, but it always gives this error when I try to search, django.core.exceptions.FieldError: Related Field got invalid lookup: istartswith. The model I am using has a ForeignKey to another model. I have tried all the solutions I have found. They dont work!! I have tried https://datatables.net/forums/discussion/55916/searching-on-columns-with-data-null , https://bitbucket.org/pigletto/django-datatables-view/issues/5/order_columns-doesnt-work-with-foreign and https://github.com/izimobil/django-rest-framework-datatables/issues/58 javascript var customerTable = $(DOMstrings.customerTable ).DataTable({ "processing": true, "searching": true, 'pageLength': 30, //"lengthMenu": [ 50, 100, 150, 200 ], //"colReorder": true, "scrollY": 500, //"scrollX": 1500, //"deferRender": true, "responsive": true, "ordering": true, "paging": true, "lengthChange": true, "ajax": { "url": customerListURL, }, "serverSide": true, "columns": [ { "fields": "id" }, { "fields": "customer.first_name"}, { "fields": "amount" }, { "fields": "date_time" }, //{ "fields": "picture" }, //{ "searchable": "false" }, ], dom: 'Bfrtip', buttons: [ 'colvis', 'pageLength', ], }); -
Django - On a button click, I want a url to be called without the page reloading
I am doing a django project where I want when the user clicks on a button, a specific path is called, the website is an e-commerce website intended for practice purposes: urls.py path("<id>/<size>/<user_name>", views.add_to_cart) views.py Then in my views I have this simple code that just uses the ID to get a specific object and carries a simple algorithm (The code is longer but the rest is just a code that plays with the field of the object I got) def add_to_cart(request, id, size, user_name): shirt = Shirt.objects.get(pk=id) shirt.html Then in the shirt.html I have some front end display, right now I am not giving the user options so the button is just whenever the user clicks on it, a shirt of a small size is added to cart and removed from stock. <form method="post"> {% csrf_token %} <button type="button" onclick="submitData({{ id }}, 'M', {{request.user}})"> ADD TO CART </button> </form> And finally, as I read previously I included this code as a JavaScript code in the html page <script type="text/javascript"> function submitData( id, size, user ){ var url = "./" + id "/" + size + "/" + user; $.ajax({ url: url, dataType: 'JSON', success: function(data){ alert(data.result); if (data.url){ window.open(data.url, … -
ModuleNotFoundError: No module named 'main.urls'
ModuleNotFoundError: No module named 'main.urls' Help me out with his error got after i fixed somehow the secret key error -
How to make user friendly upload images for ManyToManyField?
I have to models: class Post(models.Model): images = models.ManyToManyField(PostImage) ... class PostImage(models.Model): image = models.ImageField(upload_to='post_images/') ... And the corresponding classes in the admin.py file: class PostImageAdmin(admin.TabularInline): model = Post.images.through class PostAdmin(admin.ModelAdmin): inlines = [PostImageAdmin] What should I do so that in the admin site, instead of selecting the saved PostImage object, I can simply upload the images through the ImageField? In short, I need to replace this with this. I tried to override the widget with this: formfield_overrides = {models.ForeignKey: {'widget': AdminFileWidget}} in PostImageAdmin class, but when I try to save the Post, I get an error: Select a valid choice. That choice is not one of the available choices. P.S. ManyToManyField is required for some reasons. -
How convert list to json based on same key value in django
How convert list to json based on same key value in django My django list (my question) {'include_product_id[x_734652]': ['1'], 'product_name[x_734652]': ['Test_1'], 'product_qty[x_734652]': ['1'], 'product_price[x_734652]': ['10'], 'total_amount[x_734652]': ['10'], 'include_product_id[x_332559]': ['2'], 'product_name[x_332559]': ['Test_2'], 'product_qty[x_332559]': ['10'], 'product_price[x_332559]': ['10'], 'total_amount[x_332559]': ['100']} I need result like that [{'include_product_id': 1, 'product_name': Test_1, 'product_qty': 1, 'product_price': 1, 'total_amount': 10, }, {'include_product_id': 2, 'product_name': Test_2, 'product_qty': 10, 'product_price': 10, 'total_amount': 100, }] -
Django groups and model instance
I want managers to create a instance of a model and their respective employees should be able to access their managers model instance. How do i do it for class based views? models.py class weights(models.Model): company= models.ForeignKey(Company, on_delete=models.CASCADE, null=True, blank=True) mvw1 = models.IntegerField(null=True) mvw2 = models.IntegerField(null=True) mvw3 = models.IntegerField(null=True)