Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to set permissions per handler function with APIView?
I am writing an API for a small school-related project using Django and Django-Rest-Framework. I am trying to figure out permissions. I am using APIView for my views, and am looking to set different permissions for each handler method without writing more views. Here is one of the views for the blog module that I have: (This view is used for /posts/) from .serializers import * from django.db.models import Case, When from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.decorators import permission_classes from rest_framework import status, permissions # Create your views here. class PostList(APIView): """ API Endpoint to List Posts METHODS: GET, POST """ @permission_classes([permissions.AllowAny,]) def get(self, request, format=None): posts = Post.objects.all() serializer = PostSerializer(posts, many=True) return Response(serializer.data, status=status.HTTP_200_OK) @permission_classes([permissions.IsAuthenticated]) def post(self, request, format=None): serializer = PostCreationSerializer(data=request.data) if serializer.is_valid(): obj = serializer.save() data = serializer.data data["id"] = obj.id return Response(data, status=status.HTTP_201_CREATED) return Response(status=status.HTTP_400_BAD_REQUEST) The current default is permissions.IsAuthenticated, though changing that would not necessarily help as I would still need to change some permissions individually. So I should be able to make a GET request while not authenticated to /posts/ and get a list of all posts, while I should get a 401 from a POST request to /posts/. … -
Django model problem : (fields.E304) Reverse accessor for a model clashes with reverse accessor for an other/same model
i'm writing a simple model`with a foreignKey field which refer to the author of a specific article but i got this error message when making migrations. I know the the problem will be solved by adding related_nameattribute to the field but i want to understand why is this happening ? thank you for your time SystemCheckError: System check identified some issues: ERRORS: articles.Article.author: (fields.E304) Reverse accessor for 'Article.author' clashes with reverse accessor for 'Article.author'. HINT: Add or change a related_name argument to the definition for 'Article.author' or 'Article.author'. users.Article.author: (fields.E304) Reverse accessor for 'Article.author' clashes with reverse accessor for 'Article.author'. HINT: Add or change a related_name argument to the definition for 'Article.author' or 'Article.author'. my articles.models file from django.db import models from django.conf import settings class Article(models.Model): title = models.CharField( max_length=250) date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) body = models.TextField() def get_absolute_url(self): return reverse("article_detail", kwargs={"pk": self.pk}) def __str__(self): return self.title -
Make Django Template Font Smaller if Object Long
I'm trying to get make my heading font smaller if there are more than 20 characters. For some reason it doesn't seem to render the smaller font when I have a long heading. <div class="col-12 col-md-9"> <a href="{% url "pmp:project_detail" project.id %}"> {% if project > 20 %} <h1 style="font-size:.7em;">{{ project }}</h1> {% else %} <h1>{{ project }}</h1> {% endif %} </a> </div> -
AttributeError: 'UserVote' object has no attribute 'model' in Django
Trying to add this voter class to a custom user model. I don't think I needed to create a custom model the way I did, but I'm already into it and I'd prefer not to start from scratch. Basically, I'm trying to create a matching system where two users can select yes or no to each other and then be matched. Anyhow, the migrations worked. But, when I go to add it to admin.py, I get " AttributeError: 'UserVote' object has no attribute 'model' " **Models.py ** from django.db import models from django.contrib.auth.models import AbstractBaseUser,BaseUserManager, User from dating_project import settings class ProfileManager(BaseUserManager): def create_user(self, username, email,description,photo, password=None): if not email: raise ValueError("You must creat an email") if not username: raise ValueError("You must create a username!") if not description: raise ValueError("You must write a description") if not photo: raise ValueError("You must upload a photo") user = self.model( email=self.normalize_email(email), username = username, description= description, photo= photo, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email,description,photo, password): user = self.create_user( email=self.normalize_email(email), password=password, username=username, description=description, photo=photo, ) user.is_admin=True user.is_staff=True user.is_superuser=True user.save(using=self._db) return user class Profile(AbstractBaseUser): email = models.EmailField(verbose_name="email") username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = … -
Django-Filters : override method to allow property's model filtering
This is a model containing some field and a property carbs_g_secured : Models.py class Food(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255) ingredients_label = models.TextField() moisture_g = models.DecimalField(max_digits=4, decimal_places=1, blank=True, null=True) def __str__(self): return self.name def carbs_g_secured(self): # If moisture is missing if self.carbs_g : return self.carbs_g,'Carbs provided' else : return None, 'Moisture is missing' I'd like to do some min/max filtering with django-rest-framework on the the carbs_g_secured property. I know I can't do that directly with Django-filters but I try to override the whole thing. I have the following approach : Serializers.py class FoodSerializer(serializers.ModelSerializer): carbs_g_secured = serializers.ReadOnlyField() class Meta: model = Food fields = '__all__' Views.py class FoodFilter(filters.FilterSet): carbs_g_secured_max = django_filters.NumberFilter(method='MyPropertyFilter') class Meta: model = Food fields = {'name': ['exact', 'in', 'startswith'], 'species':['exact'], 'protein_g':['exact','lte','gte'], 'carbs_g_secured_max':['exact']} def MyPropertyFilter(self, queryset, name, value): results = [row for row in queryset if value and row.carbs_g_secured()[0] and row.carbs_g_secured()[0] < value] return results Problem is this is returning a list where it's expecting a query set. web_1 | AssertionError: Expected 'FoodFilter.carbs_g_secured_max' to return a QuerySet, but got a list instead. So it seems I'm a bit stuck. I think it's not good practise to transform this list into query set. What do you guys … -
How to detect when HttpResponse(content_type='text/csv') is returned starts in Django Template?
I have a button in my template which when clicked converts a particular model to csv file and download begins. <a href="{% url 'down' %}" >Download csv File</a> The view: def down(request): allobj=resource.objects.all() response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="resources.csv"' writer = csv.writer(response) writer.writerow(['Name','Email','Resource']) for obj in allobj: writer.writerow([obj.name,obj.email,obj.resource]) return response Problem: I want to show a loading gif as the model is pretty big. I can start the animation when the link is clicked, but I need to know when to stop it. So is there a way to detect in the template when the response is returned or when the download begins? I know its easy to detect when a view has functioned successfully using Ajax, But how would I implement the downloadable link using ajax as it usually has a Json response but here I have a response = HttpResponse(content_type='text/csv') -
How to manage downloadable files in Django
In my Django application users can upload a PDF in the admin section. I would like these PDF files to be able to be downloaded on the public site. This works fine locally but in my production environment I get a 404 not found error for these files. I'm wondering what is the best way to serve these type of files so that they can be downloaded ? I have done some googling and seen some people mentioning that they should be hosted on another server. Is this the best approach or can they be hosted within the Django app for download ? Here are my settings for where these files are located : # Base url to serve media files MEDIA_URL = '/media/' # Path where media is stored MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') -
How to do RTL with django-easy-pdf
I'm using django-easy-pdf in a project to provide an output report. Works great. I'm just adding Hebrew to the languages available and I cannot get the output in RTL. I've tried a number of approaches to force RTL formatting including hard-coding html, body, p, table, tr, td, span { direction: rtl; } within the tags in base.html. Does django-easy-pdf support RTL and if so, how do I implement it? -
Could not parse the remainder: '==obj.id' from 'sobj.id==obj.id'
i am using nested for loop in django template to print data which i get from the data base {% if objectives %} {% for obj in objectives %} {% for sobj in sobjective %} {% if sobj.id==obj.id %} yes {% endif %} all the open tags are closed but its raising an error as i mentioned above TemplateSyntaxError at /objectives Could not parse the remainder: '==obj.id' from 'sobj.id==obj.id' -
python3 nested namespace packages as Django modules
I'm struggling since months with a problem when using Python nested packages with Django. I have a project which is a Django framework, consisting of several packages, some of them are even Django apps, It's open source, you can even look at the code if it helps. There is one package gdaps which is core functionality, plugin manager etc. Then there should be a gdaps-frontend package which bundles basic frontend matters. And then, there are several plugins for frontends, like 'gdaps-frontend_vue`etc. Now, to address e.g. from gdaps.frontend.api import foo (part of gdaps-frontend), I think that gdaps and gdaps.frontend both should be nested namespace packages. They must not have init.py files The problem now is, that gdaps and gdaps.frontend also are Django apps. Which need a init.py file with a "default_app_config="foo.AppConfig" declaration in it for conveniently finding the AppConfig. I can't get it right here. Either with init.py - then imports go wrong, or without, then Django doens't find the app. I also have a version string in gdaps and gdaps.frontend which I use in several places. Any ideas How to solve this? -
Django: "No comment found matching the query" 404 Error
I'm making a simple blog app with comments on a 'posts detail view' page, but I'm getting a 404 error saying "No comment found matching the query" whenever I try submitting my comment. Everything else in the app works except for the comments. I'm new to django and am making this site to learn, would appreciate any help! Views.py class PostDetailView(DetailView): model = Post fields = ['content'] class CommentCreateView(LoginRequiredMixin, CreateView): model = Comment fields = ['content'] template_name = 'blog/comment.html' def form_valid(self, form): post = self.get_object() form.instance.author = self.request.user return super().form_valid(form) models.py class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) class Meta: ordering = ['-date_posted'] def __str__(self): return f'Comment {self.content} by {self.author.username}' def get_absolute_url(self): return reverse('comment', kwargs={'pk': self.pk}) urls.py from django.urls import path from .views import ( PostListView, PostDetailView, PostCreateView, PostUpdateView, PostDeleteView, UserPostListView, CommentCreateView ) from . import views urlpatterns = [ path('', PostListView.as_view(), name='blog-home'), path('post/comment/<int:pk>/', CommentCreateView.as_view(), name='create'), path('user/<str:username>', UserPostListView.as_view(), name='user-posts'), path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('post/new/', PostCreateView.as_view(), name='post-create'), path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'), path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'), path('about/', views.about, name='blog-about'), ] comments.html This is the form. It's supposed to redirect to a different form to comment then back to post detail view {% extends "blog/base.html" %} … -
Javscript POST requests being saved to database in different order than sent
I'm sure there is a much more elegant way of writing this JS using a for loop (open to suggestions!). I am attempting to use JS to POST to my django database using django REST. The code below is achieving that, but is not written in order... The user inputs text into 10 different text boxes, then the script writes them to the database. The problem is that when it is written into the database, it is not in the order it was entered on the webpage. It seems to be random. Any ideas why? addAgendaItems.js function saveUpdates(id) { let ai1 = document.getElementById("item1").value let ai2 = document.getElementById("item2").value let ai3 = document.getElementById("item3").value let ai4 = document.getElementById("item4").value let ai5 = document.getElementById("item5").value let ai6 = document.getElementById("item6").value let ai7 = document.getElementById("item7").value let ai8 = document.getElementById("item8").value let ai9 = document.getElementById("item9").value let ai10 = document.getElementById("item10").value if (ai1 != ''){ changeData(id, ai1); } if (ai2 != ''){ changeData(id, ai2); } if (ai3 != ''){ changeData(id, ai3); } if (ai4 != ''){ changeData(id, ai4); } if (ai5 != ''){ changeData(id, ai5); } if (ai6 != ''){ changeData(id, ai6); } if (ai7 != ''){ changeData(id, ai7); } if (ai8 != ''){ changeData(id, ai8); } if (ai9 != ''){ changeData(id, … -
Connecting uwsgi with Nginx does not work
I'm trying to connetc my django app with nginx via uwsgi, but it seems that the passing of data to uwsgi does not happen. I've tested that the uwsgi server is running properly and do not get any log output on either end. uwsgi.ini [uwsgi] module = MyDjangoApp.wsgi:application master = True ;http-socket = :8001 #to run uwsgi on its one to ensure that it works socket = :8001 vacuum = True max-requests = 5000 plugin = python3 enable-threads = True /etc/nginx/sites-available file tree default serverDjango_nginx.conf serverDjango_nginx.conf: # the upstream component nginx needs to connect to upstream django { #server unix:///path/to/your/mysite/mysite.sock; # for a file socket server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of the server server { # the port your site will be served on listen 8000; # the domain name it will serve for server_name 127.0.0.1; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste # Django media # location /media { # location /media { # alias /path/to/your/mysite/media; # your Django project's media files $ # } # location /static { # alias /path/to/your/mysite/static; # your Django project's … -
Django: can't able to import views in urls.py 'from pages import views'
from django.contrib import admin from django.urls import path, include from pages import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), path('dashboard/', include(pages.urls)), ] I'm trying to import views from pages directory (which is a app in django) like this 'from pages import views' but this isn't working. See the image bellowAs shown in image the when i'm trying to import views from pages it gives me error saying no module pages -
Adding existing sqlite3 database to Django App
Trying to follow this tutorial: https://knivets.com/how-to-integrate-django-with-existing-database/ and this SO: Using existing database in Django My settings.py databases setup: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, # existing db I wan't to add 'articles': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'articles.sqlite3'), } } When I run: python manage.py inspectdb --database=articles It does detect and generates a model based on the table I'm interested in. I've added this model to models.py but this table is not reflected when I run python manage.py dbshell It does not appear. In Django /admin the table shows up but breaks when I try to add to it and none of the existing data appears. I appreciate any help ya'll can offer here. -
Django Custom user CustomUserManager won't save my extra data field
I have a issue with my custom user model, I am creating a api with DjangoRestFrameork, django-allauth and Django-restauth and when I create a new user with this Json for exemple to my API { "email": "user@email.com", "first_name": "jack", "last_name": "mister", "password1": "password123", "password2": "password123", "profile_type": "individu", "identite_number": "23ewfwewfwe234234" } it's save Only email and password and not my another field My Django Model : class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['profile_type', 'identite_number', ] objects = CustomUserManager() GROUPE = 'groupe' ASSOCIATION = 'association' INDIVIDU = 'individu' INDUSTRY = 'industry' USER_PROFILE_CHOICE = [ (GROUPE, 'groupe'), (ASSOCIATION, 'association'), (INDIVIDU, 'individu'), (INDUSTRY, 'industry'), ] identificator = models.CharField(blank=True, null=True, max_length=20) profile_type = models.CharField( max_length=12, choices=USER_PROFILE_CHOICE, default=INDIVIDU, ) identite_number = models.CharField(blank=True, null=True, max_length=20) identity_scan = models.FileField(blank=True) My Django manager class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(email=email, profile_type=extra_fields.get('profile_type'), identite_number=extra_fields.get('identite_number'), **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): """ Create and … -
Django 2.2 How to send a static input value to Database
I have created a ModelForm and i have created a Button with a value in html, but i cant send this value to my mssql database. It should send the value on a click on the button, but it does nothing. I want to submit the number 200 to the database in the field 'Bunkernumber' my form: class BunkerForm(ModelForm): class Meta: model = Bunker fields = 'all' (fields are: ID,Bunkernumber, Bunkername) my view: def Bunker_view(request): updatebunk = BunkerForm() if request.method == 'POST': updatebunk = BunkerForm(request.POST) if updatebunk.is_valid(): updatebunk.save() context = {'updatebunk': updatebunk} return render(request, "pages/bunker.html", context) my html: <form action="" method="POST"> {% csrf_token %} <div class="card text-center text-white mb-3" id="bunker1"> <div class="card-header"> <h5 class="card-title">Bunker 1</h5> </div> <div class="card-body"> <div class="col-md-12 text-center"> <input type="submit" class="btn btn-primary btn-lg " name="bunker2000" value="2000"> </div> </div> </div> </form> what can i do to save the value "2000" to my database? -
Django Rest Framework Multi Image Upload
This what my code currently looks so My problem is that when it try to upload multiple images to the API it only resolves one image and the other is never uploaded can anyone tell me why and how and assist me in a way that I can do multiple image uploads -
ModuleNotFoundError: No module named 'django.urls' Django 3.0.4
Whenever I try to run "python manage.py runserver" in cmd terminal of Visual Studio, I get an ModuleNotFoundError: No module named 'django.urls'. Can somebody help me please?! I'm using django 3.0.4 and python 3.8 IN URLS.PY: from django.contrib import admin from django.urls import path urlpatterns = [ django.urls.path('admin/', admin.site.urls), ] -
OperationalError at /admin/Product/product/
could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? I have created django application with three apps.Two of them belong to same database and third app i.e Product belongs to different database.Everything works fine locally but gives this error after deploying the app on heroku.I have deployed single apps with one database before but this is my first time deploying an application with three apps having different database connectivity.Using PostgreSQL as my database. settings.py ALLOWED_HOSTS = ['0.0.0.0', 'localhost', '127.0.0.1','evening-refuge-34732.herokuapp.com'] DATABASE_ROUTERS = ['Product.router.ProductRouter'] DATABASES = { 'default': { 'NAME': 'pg_def', 'ENGINE': 'django.db.backends.postgresql', 'USER': 'postgres', 'PASSWORD': '1234', 'HOST':'localhost' }, 'product_db': { 'NAME': 'product_db', 'ENGINE': 'django.db.backends.postgresql', 'USER': 'postgres', 'PASSWORD': '1234', 'HOST':'localhost' } } import dj_database_url db_from_env = dj_database_url.config(conn_max_age=600) DATABASES['default'].update(db_from_env) -
how to iterate though list of dictionaries in html
i am making a web application with django and i need to make table with few rows and columns. And i need to go though a list with 2 dictionaries and format is on a table in html file. questions = [ { 'description': 'Programming stuff', 'option_names': ['Disagree', 'Not sure', 'Agree'], 'quiz_questions': [ 'I like python', 'I like Java' ] }, { 'description': 'Country stuff', 'option_names': ['Hell no', 'No', 'Don\'t care', 'Yes', 'Hell yes'], 'quiz_questions': [ 'Australia exists', 'My backyard is a sovereign country' ] } ] i got this function that puts 2 list dictionaries in 2 rows def show_questions(request): return render(request, 'questions.html', context={'title': 'Emotion test', 'questions': questions}) i have a guess that i might need just to do some formatting in html file or or adjustments to show_questions function because this function was used for a list with no dictionaries. -
Google Ads Api TransportError exception
I try to develop a tool that uses google ads api aiming to campaign management and reporting for my company using Python. But I get TransportError exception like below Request Method: GET Request URL: http://127.0.0.1:8000/anasayfa/ Django Version: 3.0.4 Python Version: 3.8.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'musteri_bolumu'] 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 "C:\Users\A.Orbey\AppData\Local\Programs\Python\Python38-32\lib\site-packages\suds\transport\http.py", line 67, in open return self.u2open(u2request) File "C:\Users\A.Orbey\AppData\Local\Programs\Python\Python38-32\lib\site-packages\suds\transport\http.py", line 132, in u2open return url.open(u2request, timeout=tm) File "C:\Users\A.Orbey\AppData\Local\Programs\Python\Python38-32\lib\urllib\request.py", line 531, in open response = meth(req, response) File "C:\Users\A.Orbey\AppData\Local\Programs\Python\Python38-32\lib\urllib\request.py", line 640, in http_response response = self.parent.error( File "C:\Users\A.Orbey\AppData\Local\Programs\Python\Python38-32\lib\urllib\request.py", line 569, in error return self._call_chain(*args) File "C:\Users\A.Orbey\AppData\Local\Programs\Python\Python38-32\lib\urllib\request.py", line 502, in _call_chain result = func(*args) File "C:\Users\A.Orbey\AppData\Local\Programs\Python\Python38-32\lib\urllib\request.py", line 649, in http_error_default raise HTTPError(req.full_url, code, msg, hdrs, fp) During handling of the above exception (HTTP Error 404: Not Found), another exception occurred: File "C:\Users\A.Orbey\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\A.Orbey\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\A.Orbey\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\A.Orbey\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "D:\projeler\google_adwords\musteri_bolumu\views.py", line 46, in anasayfa campaign_service = client.GetService('CampaignService') File "C:\Users\A.Orbey\AppData\Local\Programs\Python\Python38-32\lib\site-packages\googleads\adwords.py", line 303, in GetService client = … -
Shopping Cart total price problem in Django
Hi I'm trying to develop an online store website using Django and I don't know why, but my price counter is not working. It was working all fine before I added some pagination, and now it's not adding all the values.Can anyone please help me out? My views.py: def cart(request): cart = Cart.objects.all()[0] context = {"cart":cart} template = 'shopping_cart/cart.html' return render(request, template, context) def add_to_cart(request, slug): cart = Cart.objects.all()[0] try: product = Product.objects.get(slug=slug) except Product.DoesNotExist: pass except: pass if not product in cart.products.all(): cart.products.add(product) messages.success(request, mark_safe("Product added to cart. Go to <a href='cart/'>cart</a>")) return redirect('myshop-home') else: cart.products.remove(product) messages.success(request, mark_safe("Product removed from cart")) new_total = 0.00 for item in cart.products.all(): new_total += float(item.price) cart.total = new_total cart.save() return HttpResponseRedirect(reverse('cart')) My index.html(where I added pagination): {% extends 'base.html' %} {% block content %} <h1>Products</h1> <div class="container-md"> <div class="row"> {% for product in products %} <div class="col"> <div class="card-deck" style="width: 18rem;"> <img src="{{ product.image_url }}" class="card-img-top" alt="..."> <div class="card-body"> <a class="card-title text-dark" href="{% url 'detail-view' product.slug %}">{{ product.name }}</a> <p class="card-text">${{ product.price }}</p> {% if not product.cart_set.exists %} <a href="{% url 'add-to-cart' product.slug %}" class="btn btn-dark">Add to Cart</a> {% else %} <a href="{% url 'add-to-cart' product.slug %}" class="btn btn-dark">Remove from Cart</a> {% endif … -
Copying only data from model tables to new database
I have recently upgraded my django from 1.11 -> 3.0 and my python from 2.7 -> 3.6. During this process, I lost the abiltiy to use makemigrations and squashing without throwing an error about one of the previous migrations (of which i don't know which one is causing it.) During this process, I provisioned a new database and did a direct copy from the previous version using Heroku's CLI. I have data in the tables I still need and don't want to manually try to reinsert to a fresh database. To circumvent the issues with migrating, I deleted all of the migration files and did a new makemigrations call. It succeeded. The issue is now my migration status in my copied database don't match the migration numbers in the migration files, therefore cannot be executed via migrate. So the question is this: Is there a way to provision a blank database, apply the migrations, then copy only the data from the model tables into the new database; or Change the migration numbers in the copied database so they don't interfere with the updated number of migrations in the directory? -
How to remove ROWS column on django-rest-pandas
I have a django-rest-pandas viewset that exports an excel and csv, which works great, but I cant get rid of the rows column... here is my code if someone can help: from rest_pandas import PandasViewSet class FilteredCoursesView(PandasViewSet): queryset = models.XYZ.objects.all() serializer_class = serializers.CourseSerializer def filter_queryset(self, qs): qs = qs[:10] return qs def transform_dataframe(self, dataframe): columns = ['subject','begin_dt','name','description','department'] df = dataframe[columns] return df Here is my output: row,subject,begin_dt,name,description,department 0,TECH,2020-03-21,A,1A,2222 1,ABC,1900-01-01,ABC,Special AAA,AAA 2,ABC,1900-01-01,FCCC,TR,JJJJ