Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dynamic site elements not displaying after Django database change
So I recently changed databases on a Django-based website from SQLite to MySQL. I did it via dumping the data from the SQLite into a json file and then migrating it to the new MySQL db. The site is hosted on pythonanywhere and the tranistion there went flawless, however, on the local copy of the project I have(used to test implementing new features and debug), the dynamic elements on the front page wont load. I have a dynamic js table with information for various cryptocurrencies. This is how the head of the table looks on the live site: And this is how it looks on the local copy of my machine, with my own hosted MySQL server: What I've tried: -Collectstatic -Running ContentType.objects.all().delete() in python manage.py shell I also did research on stackoverflow but I could not find a similar issue. I am also new to Django so it might be something obvious I'm missing -
Why does APPEND_SLASH not work in Django 3.2
I am creating this new django project (v3.2). However the APPEND_SLASH does not seem to work. If I dont add / at the end of the url it throws an error. I even tried manully adding APPEND_SLASH = True in settings.py file, but it still did'nt work. (Note : I have 'django.middleware.common.CommonMiddleware', in my settings.py file) So any of you has any idea that why does this not work. (I created a project a month ago on django 3.1.7 and there I did'nt face this problem) -
Celery custom task state is not recognized
I have a Celery task that creates a CSV file and during the process of creation I want to set a custom state to the task so I can display it on the frontend. Here is my task from tasks.py @app.task(bind=True) def make_csv_file(self, schema_id, rows): schema = SchemaModel.objects.get(id=schema_id) salt = str(uuid.uuid4()) print(f"salt is {salt}") try: columns = [ column for column in schema.column_in_schemas.all().order_by("order") ] path = os.path.join(settings.MEDIA_ROOT, f"schema-{schema.id}---{salt}.csv") f = open(path, "w") f.truncate() csv_writer = csv.writer(f) csv_writer.writerow([column.name for column in columns]) # writerow? for x in range(rows): row_to_write = list() for column in columns: row_to_write.append(" ".join(generate_csv_data(column.id).split())) csv_writer.writerow( row_to_write ) # the line bellow is supposed to set a custom state to the task # https://docs.celeryproject.org/en/latest/userguide/tasks.html#custom-states if not self.request.called_directly: self.update_state(state='PROGRESS', meta={'done': x, 'total': rows}) schema.files.create(file=path, status=SchemaModelStatusChoices.READY) print("created") except Exception as exc: print(exc) schema.files.create(file='', status=SchemaModelStatusChoices.FAILED) finally: schema.save() Here comes my views.py def view_schema(request, pk): schema = SchemaModel.objects.get(pk=pk) form = RowsForm(request.POST or None) context = { 'schema': schema, 'form': form, } if request.method == 'POST': rows = int(request.POST.get('rows')) job = make_csv_file.apply_async((schema.id, rows)) request.session['task_id'] = job.id # here I write the task id so that I can get it's state from the view below return redirect('schemas:view_schema', pk=pk) return render(request, 'schemas/view_schema.html', context) @csrf_exempt def poll_state(request): … -
How to serialize an array of objects in Django
I am working with Django and REST Framework and I am trying to create a get function for one of my Views and running into an error. The basic idea is that I am creating a market which can have multiple shops. For each shop there can be many products. So, I am trying to query all those products which exist in one shop. Once I get all those products I want to send it to my serializer which will finally return it as a JSON object. I have been able to make it work for one product but it does not work for an array of products. My Product model looks like this: '''Product model to store the details of all the products''' class Product(models.Model): # Define the fields of the product model name = models.CharField(max_length=100) price = models.IntegerField(default=0) quantity = models.IntegerField(default=0) description = models.CharField(max_length=200, default='', null=True, blank=True) image = models.ImageField(upload_to='uploads/images/products') category = models.ForeignKey(Category, on_delete=models.CASCADE, default=1) # Foriegn key with Category Model store = models.ForeignKey(Store, on_delete=models.CASCADE, default=1) ''' Filter functions for the product model ''' # Create a static method to retrieve all products from the database @staticmethod def get_all_products(): # Return all products return Product.objects.all() # Filter the … -
Django: How to retrieve all attributes from related models for GeoJSON serialization?
I have two Models Site and Cell, every site has multiple Cells. from django.db import models from django.contrib.gis.db.models import PointField class SiteManager(models.Model): def get_by_natural_key(self, name, state_code, location): return self.get(name=name, state_code=state_code, location=location) class Site(models.Model): name = models.CharField(max_length=10) state_code = models.PositiveSmallIntegerField() location = PointField() objects = SiteManager() class Meta: unique_together = [['name', 'state_code', 'location']] def natural_key(self): return (self.name, self.state_code, self.location) class Cell(models.Model): tech = models.CharField(max_length=5) azimuth = models.IntegerField() sector_id = models.CharField(max_length=10) frequency_band = models.CharField(max_length=15) power = models.DecimalField(decimal_places=2, max_digits=4) site = models.ForeignKey(Site, on_delete=models.CASCADE) def natural_key(self): return (self.tech, self.azimuth,) + self.site.natural_key() natural_key.dependencies = ['astmaps.site'] I want to retrieve the complete Cell attributes with the related attributes in the Site model, for me to Serialize the resultant Cell's, into GeoJson data, I can easily Serialize the Site model like: from django.core.serializers import serialize # GeoJSON Serializer sites = Site.objects.all() sitesData = serialize('geojson', sites, geometry_field='location', fields=('name', 'state_code')) which gives me a GeoJson featureCollection object like: { "type":"FeatureCollection", "crs":{ "type":"name", "properties":{ "name":"EPSG:4326" } }, "features":[ { "type":"Feature", "properties": { "name":"02101", "state_code":2 }, "geometry":{ "type":"Point", "coordinates":[ 1.34944, 36.1586 ] } } ] } But when It comes to the Cell model, I can't successfully get the geometry field from the related model always null. Since the Cell model … -
getting the the field value based on the other value you entered in a form django
two models: class Branch(models.Model): name = models.CharField(max_length=50) square = models.CharField(max_length=50) branch_id = models.CharField(max_length=5, blank=True) class Worker(models.Model): w_branch = models.ForeignKey(Branch, on_delete=models.SET_NULL, null=True, blank=True) Form class PayForm(forms.Form): branch = forms.ModelChoiceField(label='branch', queryset=Branch.objects.all()) worker = forms.ModelChoiceField(label='customer', queryset=Worker.objects.filter()) I dont know how to get queryset of workers based on branch choise whithin the form. And im not sure that it is possible...can you help? -
IntegrityError at /post/new/ NOT NULL constraint failed: blog_post.author_id
Iam trying to learn django but this thing is stoppin me from doing that this is my views.py from django.shortcuts import render from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.http import HttpResponse from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .models import Post # Create your views here. def home(request): context = { 'posts' : Post.objects.all } return render(request,'blog/home.html',context) class PostListView(ListView): model = Post template_name = 'blog/home.html' context_object_name = 'posts' ordering = ['-date_posted'] # <app>/<model><viewtype>.html class PostDetailView(DetailView): model = Post class PostCreateView(LoginRequiredMixin,CreateView): model = Post fields = ['title','content'] class PostUpdateView(LoginRequiredMixin,UpdateView): model = Post fields = ['title','content'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin,CreateView): #LoginRequiredMixin, UserPassesTestMixin,DeleteView #LoginRequiredMixin, AuthorMixin, ListView model = Post success_url = '/' def test_func(self): post = self.get_object() if self.request.user == post.author: return True else: return False def about(request): return render(request,'blog/about.html',{'title':'About'}) This is my models.py: from django.db import models from django.contrib.auth.models import User from PIL import Image # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete= models.CASCADE) image = models.ImageField(default='default.jpg',upload_to="profile_pics") def __str__(self): return f'{self.user.username} Profile' def save(self): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size … -
Manually caching HTML pages in Django CMS
I'm trying o build an addon for Django CMS that would save a static copy of a site on disk. I have set up the addon and I have a button on the toolbar that triggers a view that goes through all the pages, renders them and saves them. The general setup seems to work fine, but when I check the static HTML files created, they are missing the content of the plugins in each page. My approach was to reuse the Django CMS details view, which is the one used to render the pages as a response to the browser's HTTP requests. I suspect the problem might have something to do with the request object passed to it, since the one I have available in my view is actually the admin page request, not the one I want to render. But I have tried to overwrite some of its values, I have also checked Django CMS GitHub to see how the request was used but I still can't manage to make the plugin's content show up. This is my view function: from django.contrib.auth.models import AnonymousUser from cms.views import details from cms.models.pagemodel import Page def create_html_files(request): cms_pages = Page.objects.filter(publication_date__isnull=False) request.user … -
ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2._psycopg' zappa
I am using zappa to deploy backend to the AWS Lambda. It worked well, until I decided to use PostgreSQL. I added it in the settings like this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': config('DATABASE_NAME'), 'USER': config('DATABASE_USER'), 'PASSWORD': config('DATABASE_PASSWORD'), 'HOST': config('DATABASE_HOST'), 'PORT': '5432' } } I am using AWS RDS. I installed psycopg2-binary and also psycopg2 (versions 2.8.6), but the issue remains. The python version is 3.8. The full error log: [1621168086542] [ERROR] ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2._psycopg' Traceback (most recent call last): File "/var/task/handler.py", line 609, in lambda_handler return LambdaHandler.lambda_handler(event, context) File "/var/task/handler.py", line 240, in lambda_handler handler = cls() File "/var/task/handler.py", line 146, in __init__ wsgi_app_function = get_django_wsgi(self.settings.DJANGO_SETTINGS) File "/var/task/zappa/ext/django_zappa.py", line 20, in get_django_wsgi return get_wsgi_application() File "/var/task/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/var/task/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/var/task/django/apps/registry.py", line 114, in populate app_config.import_models() File "/var/task/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/var/lang/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File … -
Getting this error when trying to execute "python manage.py runserver"
Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\yaswanth\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 600, in url_patterns iter(patterns) TypeError: 'module' object is not iterable The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\yaswanth\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Users\yaswanth\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\Users\yaswanth\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\yaswanth\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\yaswanth\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 419, in check all_issues = checks.run_checks( File "C:\Users\yaswanth\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\yaswanth\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\yaswanth\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\yaswanth\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 413, in check messages.extend(check_resolver(pattern)) File "C:\Users\yaswanth\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\yaswanth\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 412, in check for pattern in self.url_patterns: File "C:\Users\yaswanth\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "C:\Users\yaswanth\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 607, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'application.urls' from 'C:\Users\yaswanth\projects\calci\application\urls.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. -
ProgrammingError at /add-to-cart/ in Django
I'm using Django as a backend and PostgresSQL as a DB and HTML, CSS, JS as frontend. Well, I have successfully added data to Django and also in PostregsSQL with models. Well, I want to See the selected product in Cart product in Django but showing this error. What is error in below code can someone tell me? I'm getting this error ProgrammingError at /add-to-cart-5888/ column "quantity" of relation "app_cartproduct" does not exist LINE 1: ...app_cartproduct" ("cart_id", "product_id", "rate", "quantity"... models.py class Cart(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True) total = models.PositiveIntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return "Cart: " + str(self.id) class CartProduct(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() def __str__(self): return "Cart: " + str(self.cart.id) + " CartProduct: " + str(self.id) views.py class AddToCartView(TemplateView): template_name = "status.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # get product id from requested url product_id = self.kwargs['pro_id'] # get product product_obj = Product.objects.get(id = product_id) # check if cart exists cart_id = self.request.session.get("cart_id", None) if cart_id: cart_obj = Cart.objects.get(id = cart_id) this_product_in_cart = cart_obj.cartproduct_set.filter(product = product_obj) if this_product_in_cart.exists(): cartproduct = this_product_in_cart.last() cartproduct.quantity += 1 cartproduct.save() cart_obj.save() else: cartproduct = CartProduct.objects.create(cart = cart_obj, product = product_obj, quantity = … -
Can I use a for loop to generate field names inside a django model class
Can I use a for loop to generate field names inside a django model class. Example In the below example Task will be another model class written inside the same models.py class Task(models.Model): task_name = models.Charfield(max_length=120) def __str__(self): return self.task_name class subtask(models.Model): subtask_list = tasks.objects.all() for subtask in subtask_list: subtask.task_name = models.FloatField(default=0.0, null=True, blank=True) -
Django Calculate Similar Posts Based On Categories Not Working
I want to calculate similar posts based on categories. This is what I have so far in models: class Post(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, default=15) def get_related_posts_by_tags(self): category = get_object_or_404(Category, name=self.category.title) posts = Post.objects.filter(category=category) return posts class Category(models.Model): name = models.CharField(max_length=250, unique=True) And in my templates: {% for posts in object.get_related_post_by_tag %} {{ posts.title }} {% endfor %} For whatever reason, this does not work, and in my template, I do not seen any posts with the same category. This is why I am wonder if I am doing it wrong, or if I have little problem I easily fix. Thanks for all help. -
Django TypeError when trying to save the model
I am trying to create a todo add but when I try to save my model it says todo got an unexpected keyword argument . TypeError at / todo() got an unexpected keyword argument 'user' it throws the following error My models.py class todo(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) description = models.TextField() date= models.DateTimeField(auto_now = True) is_completed = models.BooleanField(default=False) def __str__(self): return self.user.username + self.title And my views looks like this def todo(request): if request.method == "POST": title = request.POST.get('title') description = request.POST.get('description') todo_list = todo(user=request.user, title=title, description= description) todo_list.save() messages.success(request, 'Successfully Created') return render(request, 'main/todo.html') Please help me out -
Django submit form in bootstrap modal
i know that there are a lot of posts with similar topic as this one, but none of them seem to be a useful fix in my case at least. As the headline describes i want to be able to send a new comment form to my database from a bootstrap modal. My data is being shown just fine so the only problem i got is that when i fill out the data for a new comment and press the submit button the modal is just being dismissed and no action has happened in my DB. My best guess for why it is not working is because i got my modal data in a separated html file detail.html. But otherwise i was not able to display the right data for each posts. button to open the modal in home.html: <a class="btn btn-outline-primary post_details-btn" class="open-modal" data-url="{% url 'post_detail' post.pk %}" width="17" height="17"><i class="fa fa-comments"></i></a> my modal in home.html where i display the data from detail.html in the div with the id = modal-div <div class="modal fade" id="myModal2"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="staticBackdropLabel">WINNER:</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <div id="modal-div"></div> </div> </div> </div> </div> my … -
Using a single index for multiple arrays in a single for loop
I'm working on a django project which takes multiple arrays from the view and shows it on a datatable. I can use loop to print a single element properly but can't for the other arrays. Is there any workaround for this issue? The code sample is given below: <tr> <td> {{x}} </td> <td> <a href="{{link|safe}}">link text</a> </td> <td> {{time|safe}} </td> <td> {{uploadername|safe}} </td> </tr> {% endfor %} In the given picture I want the other column elements to show properly like the first column. Is there any workaround for this? -
How to collect Data from a Website using Django?
I'm currently working on a project where I have a website that should give me information from various Github projects (username, projectname, ...). However, I don't know exactly how to read this data out of the Githubpage. The project is carried out using Django. Is there any way to get the information out with iframes or an API? I've done some research now but haven't come across anything useful. Thank you for your help! -
The view videos.views.add_comment_post didn't return an HttpResponse object. with the second object in Django
I try to build a blog and this blog consist of posts and these posts have comments, When I add comment to the first post it adds succussfuly but when I try to add comment the second or third this error raise ValueError: The view videos.views.add_comment_post didn't return an HttpResponse object. It returned None instead. and I tried to add comment form to the template without any widgets commentForm = PostCommentForm() to the template {{commentForm }} and I filled it and this proplem still My Post model class Post(models.Model): author = models.ForeignKey(Account, on_delete=models.CASCADE) article = models.TextField(null=True, blank=True) photo_article = models.ImageField(max_length=255, upload_to=get_poster_filepath) created_date = models.DateTimeField(auto_now_add=True) class PostCommentIDF(MPTTModel): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') author = models.ForeignKey(Account, on_delete=models.CASCADE) content = models.TextField() publish = models.DateTimeField(auto_now_add=True) status = models.BooleanField(default=True) My create comments view comment_form = PostCommentForm(request.POST) if comment_form.is_valid(): user_comment = comment_form.save(commit=False) user_comment.author = request.user user_comment.save() result = comment_form.cleaned_data.get('content') user = request.user.username return JsonResponse({'result': result, 'user': user}) My comments Form class PostCommentForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class Meta: model = PostCommentIDF fields = {'post', 'content'} widgets = { 'content': forms.Textarea(attrs={'class': ' form-control', 'rows': '1', 'placeholder': 'Comment', 'required': 'True', }) } def save(self, *args, **kwargs): PostCommentIDF.objects.rebuild() return super(PostCommentForm, … -
NotImplementedError: PostCreateView is missing the implementation of the test_func() method
Please help me solve this bug Iam in learning stage in django and here's my code: views.py: from django.shortcuts import render from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.http import HttpResponse from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .models import Post # Create your views here. def home(request): context = { 'posts' : Post.objects.all } return render(request,'blog/home.html',context) class PostListView(ListView): model = Post template_name = 'blog/home.html' context_object_name = 'posts' ordering = ['-date_posted'] # <app>/<model><viewtype>.html class PostDetailView(DetailView): model = Post class PostCreateView(LoginRequiredMixin, UserPassesTestMixin,CreateView): model = Post fields = ['title','content'] class PostUpdateView(LoginRequiredMixin,UpdateView): model = Post fields = ['title','content'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin,CreateView): #LoginRequiredMixin, UserPassesTestMixin,DeleteView #LoginRequiredMixin, AuthorMixin, ListView model = Post success_url = '/' def test_func(self): post = self.get_object() if self.request.user == post.author: return True else: return False def about(request): return render(request,'blog/about.html',{'title':'About'}) error : NotImplementedError: PostCreateView is missing the implementation of the test_func() method. Iam learning to code in django and Iam facing frequent bugs please help me Iam trying to do this with my full energy and Iam a self taught coder so I have no one to ask my questions or … -
Django Forms - How to make certain fields readonly except for superuser
I use UserChangeForm and UpdateView, to update user information the UpdateView is only accessible for the owner of the account and superuser. now, I need to make the username and subject fields to be read only when the owner wants to edit their profile info but it will be editable when superuser access wants to edit it. forms.py class TeacherUpdateForm(UserChangeForm): class Meta: model = Profile fields = ["username", "first_name", "last_name", "email", "phonenumber", "address", "subject"] views.py class TeacherUpdateView(UpdateView): model = Profile form_class = TeacherUpdateForm template_name = "account/update_form.html" def get_context_data(self, **kwargs): kwargs["user_type"] = "Teacher" return super().get_context_data(**kwargs) def get_object(self, *args, **kwargs): obj = super(TeacherUpdateView, self).get_object(*args, **kwargs) if obj.id is self.request.user.id or self.request.user.is_superuser: return obj else: raise PermissionDenied() def form_valid(self, form): form.save() return redirect(reverse("index")) I feel stuck because every solution I see is using get_readonly_fields and it doesn't work on the forms or views. For another info, the subject field is a foreignkey from another model. -
How to combine multiple querysets in django
Suppose there is an event model and for each event there is one client and one consultant. Also, one consultant can have multiple events. Each event has number of different documents. I am trying to display list of events when a consultant logs in and in that list od events it should display their respective documents. Models.py: class Client_Profile(models.Model): user_id = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE) # Field name made lowercase. first_name = models.CharField(db_column='First_name', max_length=50) # Field name made lowercase. last_name = models.CharField(db_column='Last_name', max_length=50) # Field name made lowercase. phone_number = models.PositiveIntegerField(db_column='Phone_number', max_length=10) # Field name made lowercase. # role_id = models.ForeignKey(Role, on_delete=models.CASCADE) def __str__(self): return self.first_name class Consultant_Profile(models.Model): user_id = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE) # Field name made lowercase. first_name = models.CharField(db_column='First_name', max_length=50) # Field name made lowercase. last_name = models.CharField(db_column='Last_name', max_length=50) # Field name made lowercase. phone_number = models.PositiveIntegerField(db_column='Phone_number', max_length=10) # Field name made lowercase. # role_id = models.ForeignKey(Role, on_delete=models.CASCADE) def __str__(self): return self.first_name class Event(models.Model): event_id = models.AutoField(db_column='event_id', primary_key=True) client_id = models.ForeignKey(Client_Profile, db_column='Client_ID', on_delete=models.CASCADE) # Field name made lowercase. consultant_id = models.ForeignKey(Consultant_Profile, db_column='Consultant_ID', on_delete=models.CASCADE) # Field name made lowercase. def __str__(self): return str(self.event_id) class Document(models.Model): document_id = models.AutoField(db_column='document_id', primary_key=True) document_name = models.CharField(db_column='document_name', max_length=50, null=True, blank=True) # Field name made lowercase. … -
Is select_related() still needed after defining only() in django query
select_related is used so whenever a defined foreign key accessed, it will be included in the first query and won't issue another query to db. But I have a case when only few fields are needed. Here is the example class PMapKomoditi(models.Model): id = models.IntegerField(primary_key=True) komoditi_fk = models.ForeignKey(PMastKomoditi, models.RESTRICT, db_column='id_komoditi') kd_komoditi = models.CharField(max_length=2) nm_komoditi = models.CharField(max_length=50, blank=True, null=True) uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) // ... class PMastKomoditi(models.Model): id = models.AutoField(primary_key=True) uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) // ... I only need kd_komoditi & komoditi_fk properties, so I do query the following: my_query = PMapKomoditi.objects.select_related( 'komoditi_fk' ).Only( 'kd_komoditi', 'komoditi_fk' ) Do I need to include the select_related or it's already covered with only()? -
I am getting type error white i'm fetching orders from logged in user . how i can solve it?
Error screenshot https://drive.google.com/file/d/1IBhNsKHGXc2SQNp4q4Q_N3k9LwOi50MO/view?usp=sharing views.py def orders(request): customer = request.session.get('id') print(type(customer)) get_order = Order.get_order_by_id(customer) print(type(get_order)) return render(request , "orders.html" , {'ord':get_order} ) model from django.db import models from .customer import Customer from .product import Product import datetime class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default=0) address = models.CharField(max_length = 100 ) phone = models.CharField(max_length = 20) price = models.IntegerField(default=0) date = models.DateField( default=datetime.datetime.today) def __str__(self): return self.product.p_name + " - " + self.customer.firstname @staticmethod def get_order_by_id(customer_id): return Order.objects.filter(customer = customer_id) -
need of postgraphile with django backend
My app is in frontend react-native and backend in django using graphene (for graphql apis), database is postgresql. Do i need postgraphile or hasura with it or let the django do the work? i m new to backend development , any help would be appreciated Thanks -
How can I use Django and React-js with AWS s3 bucket?
I am trying link my Django App (coupled with React-Js App) with my s3 bucket but despite the everything I have tried, something is still not working right. First, below is my settings.py; import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = os.environ.get("APP_SECRET_KEY") # SECURITY WARNING: don't run with debug turned on in production! #DEBUG = (os.environ.get("APP_DEBUG") == "True") DEBUG = False ALLOWED_HOSTS = ['127.0.0.1', '.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'account', 'products', 'orders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #installed apps 'rest_framework', 'corsheaders', 'storages', ] AUTH_USER_MODEL = 'account.User' 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', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ BASE_DIR / "build", ], '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', ], }, }, ] # Database import dj_database_url if DEBUG: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } else: DATABASES = {} DATABASES['default'] = dj_database_url.config(conn_max_age=600, ssl_require=True) #S3 bucket SETTINGS if not DEBUG: AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_URL = os.environ.get('AWS_URL') AWS_DEFAULT_ACL = None AWS_S3_REGION_NAME = 'eu-west-2' AWS_S3_SIGNATURE_VERSION = 's3v4' if DEBUG: STATICFILES_DIRS = [ BASE_DIR / "build/static", #removing this makes my app not to show up …