Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How get data from database to modal popup page in Django?
I am developing an ecommerce website with Django.I bought this ready template and try write backend with Django. In my home page displayed product cards and as you see in the below image when I hower over (marked with red) from this cards I can click search icon which open modal page(quick view) as in next below image. home page modal popup page Modal page opens fine, but with static dates. I want take data from my models, for example image from my Product_image model, product name from my Product model. In my other pages for example in home.html page or in product_detail.html (single product page) I already can get datas from models, but in modal popup page I don't know how get data from my models. Please help me. My modal page codes in base.html file. base.html <!-- Quick-view modal popup start--> <div class="modal fade bd-example-modal-lg theme-modal" id="quick-view" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog modal-lg modal-dialog-centered" role="document"> <div class="modal-content quick-view-modal"> <div class="modal-body"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <div class="row"> <div class="col-lg-6 col-xs-12"> <div class="quick-view-img"><img src="{% static 'product/images/pro3/1.jpg' %}" alt="" class="img-fluid blur-up lazyload"></div> </div> <div class="col-lg-6 rtl-text"> <div class="product-right"> <h2>Women Pink Shirt</h2> <h3>$32.96</h3> <ul class="color-variant"> <li class="bg-light0"></li> </ul> <div class="border-product"> … -
FileInput does not update in UpdateView when using InlineFormSets
I'm trying to make a website to allow students to post study materials online. In this piece of code, I intended to create a View using django's UpdateView for users to update their posts. These posts are called 'Materiais' and referenced in models.py as: class Materiais(models.Model): id_materia = models.ForeignKey(Materia, on_delete=models.CASCADE) topico_mas = models.CharField(max_length=200) descr_mas = models.CharField(max_length=200, null=True, blank=True) data_mas = models.DateTimeField(auto_now=True) # data da última edição id_user = models.ForeignKey(User, on_delete=models.CASCADE, default=7) is_active = models.BooleanField(default=True) def __str__(self): return self.topico_mas def get_absolute_url(self): return reverse('materiais-detalhe', args=(self.id,)) For each 'Materiais', the user can upload any number of files to the server, to which I created a One to Many relationship in models.py: class Arquivo_materiais(models.Model): id_materiais = models.ForeignKey(Materiais, on_delete=models.CASCADE) nome_arq = models.CharField(max_length=200) file_mat = models.FileField( upload_to='materiais/', null=True, blank=True) is_active = models.BooleanField(default=True) In forms.py there are the forms for these fields and an InlineFormset: class EditarMateriaisForm(forms.ModelForm): class Meta: model = Materiais fields = ['id_materia', 'topico_mas', 'descr_mas']#, 'files_mas'] widgets = { 'topico_mas': forms.TextInput(attrs={ 'class': 'form-control', 'id': 'topico', 'name': 'topico', 'placeholder': 'Tópico do material'}), 'descr_mas': forms.Textarea(attrs={'class': 'form-control', 'id': 'descr', 'name': 'descr', 'rows': '3', 'placeholder': 'Descrição do material'}), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['id_materia'].queryset = Materia.objects.filter(is_active=True) self.fields['id_materia'].widget.attrs.update({'class': 'form-control' , 'id': 'mat'}) class ArquivosForm(forms.ModelForm): class Meta: model = … -
Get count of records even if zero
I have below query in my script which returns me the number of records added today per source name. I have added a filter created_at__gte=today. Using this information I am creating one table. Now the problem is if there are no media records for any particular source name, it doesn't appear in the output. I would like that too to appear with count as zero. Can you please guide me how can I achieve that? media_queryset = Media.objects.filter( created_at__gte=today ).values('source__name').annotate( total=Count('id'), last_scraped=Max('created_at') ).order_by('source__name') -
Message Object has no attribute 'fields' when updating model field across apps
I have two apps menu and table. In app table, I have this model: class Table(models.Model): available = models.BooleanField(verbose_name="Availability", default=True) def set_availability(self, avail=False): self.fields['available'] = avail self.save() def __str__(self): return "Table " + str(self.id_num) In one of the views of app menu, I have the following call: from table.models import Table def menu_category_view(request, table_pk): table = Table.objects.get(pk=table_pk) if table.available: table.set_availability(False) ... return render(request, ...) When my template calls this view, I receive this error message 'Table' object has no attribute 'fields'. Here, I am trying to update the value of field available of the instance being called (from True to False). And I got this implementation suggested from a book. Is this the right way to update model instance field value? Thanks. -
Tracking user visited page in a Django Project
I have added a new app to my Django Project to track users visited pages, so I have followed a tutorial step by step but I am now receiving an error: 'PostListView' object has no attribute 'get_object' My questions are: What is the reason behind it so I need some guidance on how to fix it. Is there another easier way to get the user's activity on the website or is this the best way to do it? Here is the models.py: from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey from django.conf import settings from django.contrib.auth.models import User from .signals import object_viewed_signal class History(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType, on_delete=models.SET_NULL, null=True) # product, post object_id = models.PositiveIntegerField() # 1,2,3 content_object = GenericForeignKey() # is the actual object viewed_on = models.DateTimeField(auto_now_add=True) def __str__(self): # return "%s viewed: %s" %(self.content_object, self.viewed_on) return self.user class Meta: verbose_name_plural = "History" def object_viewed_receiver(sender, instance, request, *args, **kwargs): new_history = History.objects.create( user = request.user, content_type = ContentType.objects.get_for_model(sender), object_id = instance.id, ) object_viewed_signal.connect(object_viewed_receiver) Here is the signal.py from django.dispatch import Signal object_viewed_signal = Signal(providing_args=['instance', 'request']) Here is the mixin.py from .signals import object_viewed_signal class ObjectViewMixin: def dispatch(self, request, *args, **kwargs): try: … -
Efficiency of Django filter that mixes indexed and nonindexed fields?
Suppose I have a model like: class Widget(models.Model): a = models.CharField(db_index=True, unique=True) b = models.CharField() and then I perform a filter like: Widgets.objects.filter(a=a, b=b).get() would you expect the performance of this to be (1) the same; or (2) worse ? - than if the model was instead defined as: class Widget(models.Model): a = models.CharField(db_index=True, unique=True) b = models.CharField(db_index=True) # <--- now b is indexed I mean, logically, because a is indexed and unique, at most one result could be found for some value of a, so the engine could just do the lookup on a and then check that the results b field is the expected value, without using any index on b. But in practice, will the generated SQL and underlying SQL engine be smart enough at query planning to figure that out? Is such query planning trivial? -
How to fix QuerySet' object has no attribute 'userrole_set' in django?
When I Adds the specified model objects to the related object set. Like as My view.py: role = UserRole.objects.get(id=user_role_id) s = SbTitle.objects.filter(user_role=1) d = s.userrole_set.add(role) # Associates Entry role with SbTitle s. Then QuerySet' object has no attribute 'userrole_set' error will occur. please tell me how to fix it. MY model.py: class SbTitle(models.Model): sb_title = models.CharField(max_length = 100, blank=True, null=True) user_role = models.ForeignKey(UserRole, blank=True, null=True, on_delete=models.CASCADE) def __str__(self): return self.sb_title -
override create_user() function used by third party app social-auth-app-django
Hello I have a project where I have created my own User model inheriting from BaseUserManager. Now I also want to add the option for users to log via facebook but it is giving me an exception saying that create_user() missing 2 required positional arguments: 'first_name' and 'last_name' because I modified the model to ask for those fields instead of username and other changes. How do I make it so that it can work correctly with my custom user model? -
How to manipulate SubFactory object post generation of DjangoModelFactory?
I've got a DjangoModelFactory like this: class Hello(models.Model): fk = models.ForeignKey("self", null=True, blank=True, on_delete=models.CASCADE) class HelloFactory(DjangoModelFactory): class Meta: model = Hello class BlahFactory(DjangoModelFactory): class Meta: model = Blah hello = factory.SubFactory("path.to.HelloFactory") where hello is a foreign key to Django model Hello. I use a path to HelloFactory since I have a circular import to HelloFactory. When hello is created by doing BlahFactory.create() and then getting hello.fk, you get None because it's not created. How would I create that object in BlahFactory, NOT HelloFactory using something like @post_generation (i.e. I only want to create fk during BlahFactory generation and not during HelloFactory generation)? Just note that Hello's foreign key is a self referencing foreign key. -
Django update some fields in page
I have a problem when I want to update one field in profile view. The problem is when I update social content in the profile the rest data change to empty. For instance, I have a user name called "waad" and Lastname 'WAADABDURHMA', and I have social content like Twitter and Instagram when I update Instagram and Twitter the user name and last name change to empty, and I have tow forms in my HTML one for the personal information and one for social accounts. model.py: class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) following = models.ManyToManyField(User,related_name='following',blank=True) bio = models.CharField(max_length=400) profile_image=models.ImageField(null=True,blank=True,default='defult.png') Twitter = models.CharField(max_length=100,blank=True) Facebook = models.CharField(max_length=100,blank=True) Instagram = models.CharField(max_length=100,blank=True) LinkedIn = models.CharField(max_length=100,blank=True) Athr = models.CharField(max_length=100,blank=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) Forms.py: class FormUpdateUser(forms.ModelForm): class Meta: model=User fields=['first_name','last_name','email'] class FormUpdateBio(forms.ModelForm): class Meta: model=Profile fields=['bio','profile_image','Athr','Facebook','Twitter','LinkedIn','Instagram'] Views.py: class ProfileUpdateView(LoginRequiredMixin, TemplateView): user_form = FormUpdateUser profile_form = FormUpdateBio template_name = 'profile/profile_update.html' def post(self, request): post_data = request.POST or None file_data = request.FILES or None user_form = FormUpdateUser(post_data, instance=request.user) profile_form = FormUpdateBio(post_data, file_data, instance=request.user.profile) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() messages.success(request, 'تم تحديث ملفك الشخصي بنجاح') return HttpResponseRedirect(reverse_lazy('update_bio')) context = self.get_context_data(user_form=user_form, profile_form=profile_form) return self.render_to_response(context) def get(self, request, *args, **kwargs): return self.post(request, *args, **kwargs) -
AWS copilot with Django never finishes deploying
I've followed the this short guide to create a django app with docker https://docs.docker.com/compose/django/ and then following copilot instructional to push up the container to ECS: https://aws.amazon.com/blogs/containers/introducing-aws-copilot/ I've also used this sample to test everything -- which works out fine: https://github.com/aws-samples/aws-copilot-sample-service The deploy completes and outputs and URL endpoint. In my case, the everything is successfully built, but once the test environment is being deployed it just continuously builds at this: 72ff4719 size: 3055 ⠏ Deploying load-bal:7158348 to test. and never finishes. I've even downsized my requirements.txt to a bare minimum. My Dockerfile FROM python:3.7.4 ENV PYTHONUNBUFFERED=1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt EXPOSE 80 COPY . /code/ docker-compose.yml version: "3.8" services: db: image: postgres environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db requirements.txt Django==3.0.8 djangorestframework==3.11.0 gunicorn==20.0.4 pipenv==2020.6.2 psycopg2-binary==2.8.5 virtualenv==16.7.6 Instructions I follow: sudo docker-compose run web django-admin startproject composeexample . Successfully creates the Django App copilot init Setup naming for app and load balancer Choose to create test environment Everything builds successfully and then just sits here. I've tried a number of variations, but the only … -
I'm trying to graphic with django using python but jump IndentationError: expected an indented block
Looks like simple but I'm starting code and I don't know what to do or why this error happened. What I'm trying is to make an example graphic in django that's all not with success, all the information showed is confusing me. this is my views.py from django.shortcuts import render import matplotlib.pyplot as plt def home(request): plt.plot(range(10)) return render(request, 'app1/home.html') def about(request): return render(request, 'app1/about.html', {'title': 'About'}) and jump the next error Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.9/threading.py", line 950, in _bootstrap_inner self.run() File "/usr/lib/python3.9/threading.py", line 888, in run self._target(*self._args, **self._kwargs) File "/home/corbin/ProyectoDB/venv/lib/python3.9/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/corbin/ProyectoDB/venv/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "/home/corbin/ProyectoDB/venv/lib/python3.9/site-packages/django/core/management/base.py", line 392, in check all_issues = checks.run_checks( File "/home/corbin/ProyectoDB/venv/lib/python3.9/site-packages/django/core/checks/registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/home/corbin/ProyectoDB/venv/lib/python3.9/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/corbin/ProyectoDB/venv/lib/python3.9/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/home/corbin/ProyectoDB/venv/lib/python3.9/site-packages/django/urls/resolvers.py", line 408, in check for pattern in self.url_patterns: File "/home/corbin/ProyectoDB/venv/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/corbin/ProyectoDB/venv/lib/python3.9/site-packages/django/urls/resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/corbin/ProyectoDB/venv/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/corbin/ProyectoDB/venv/lib/python3.9/site-packages/django/urls/resolvers.py", line 582, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python3.9/importlib/__init__.py", line … -
Django annotation filter by annotated value
here is my models: Seller (user, name) Order (seller, customer, amount) Discount (seller, required_amount, value) I need to annotate some current customer stats to each seller (amount sum from customer orders and max discount value with required_amount less then total customer amount) Sellers.objects.filter(orders__customer=request.user).annotate( customer_amount=models.Sum( 'orders__amount', filter=models.Q(orders__customer=request.user) ), discount_value=models.Max( 'discounts__value', filter=models.Q(discounts__required_amount__lte=models.F('customer_amount')) ) ) And I have an error aggregate functions are not allowed in FILTER LINE 1: ...ue") FILTER (WHERE "clients_discount"."amount" <= SUM("order... -
Django: Why isn't my url path using the namespace I've created?
When trying to render my url "http://127.0.0.1:8000/welcomeLiteApp/new", I get the error TemplateDoesNotExist at /welcomeLiteApp/new . My templates all live inside of a namespaced directory in my templates file, i.e. the directory that holds my new.html file is Documents/Code/welcomeLite/welcomeLiteApp/templates/welcomeLiteApp Django is not including the namespace directory when it looks for my new.html template. I can tell this from this error message: Django tried loading these templates, in this order: Using engine django: django.template.loaders.app_directories.Loader: Documents/Code/welcomeLite/welcomeLiteApp/templates/new.html (Source does not exist) I tried to set up my views/urls very similarly to in the Django documentation on namespacing (https://docs.djangoproject.com/en/3.1/intro/tutorial03/) I think the namespaced directory is properly included in the new.html file and my urls.py file. new.html file: <li><a href="{% url 'welcomeLiteApp:new' %}">"This is the new.html template"</a></li> urls.py file: from django.contrib import admin from django.urls import include, path from . import views app_name = 'welcomeLiteApp' urlpatterns = [ path('', views.index, name='index'), path('new', views.create, name='new'), ] I tried simply taking my new.html file out of the name spaced directory so it was in the directory that Django said it was looking for it in originally (Documents/Code/welcomeLite/welcomeLiteApp/templates/new.html), and at least was able to get a different error (NoReverseMatch at /welcomeLiteApp/new Reverse for 'new' not found. 'new' is not … -
Sub categories Django
I am new to Django and i came across this blog project. The blog is categorized into 3 category. There are posts already organized into each category. I wanted to add subcategory to further classify the post. Admin should be able to add new subcategories through the admin portal. I made class SubCategory model and register it to the admin and add foreign key = Post 2.Admin should be able to specify which subcategory a post belongs to through the admin portal. [Nice to have] Admin should be able to select which subcategory a post belongs to through the post list in the admin portal (/admin/blog/post). 3.A post can exist with or without a subcategory. Users on a blog category page should see a dropdown where they can select a subcategory and the results get filtered to display posts under that subcategory. “All” should be selected by default. The dropdown should look nice on all screen sizes (mobile, tablet, desktop). [Nice to have] The subcategories are displayed in the dropdown in an alphabetical order. [Nice to have] If a category does not have subcategories, the dropdown is not displayed. How do i proceed further ? Especially bring the filter to … -
Serializing a Django object
I am trying to serialize an object so that I can use it to build an API. The model I want to serialize is my Profile model. The problem is when I go to the url: \users the output is: ["[{\"model\": \"network.profile\", \"pk\": 2, \"fields\": {\"friends\": []}}, {\"model\": \"network.profile\", \"pk\": 3, \"fields\": {\"friends\": []}}, {\"model\": \"network.profile\", \"pk\": 4, \"fields\": {\"friends\": []}}]"] I was expecting something like: [{"user": "one", "friends":["foo", "bar", "baz"]}, {"user": "two", "friends":["one", "bar"]}] models.py class User(AbstractUser): pass class Profile(models.Model): user = models.OneToOneField("User", on_delete=models.CASCADE, primary_key=True) friends = models.ManyToManyField("User", related_name='following', blank=True, symmetrical=False) def serialize(self): return { "user": self.user, "friends": [user.username for user in self.friends.all()] } @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): try: instance.profile.save() except Profile.DoesNotExist: Profile.objects.create(user=instance) class Post(models.Model): creator = models.ForeignKey("Profile", on_delete=models.CASCADE) content = models.TextField(max_length=250, blank=True) created = models.DateTimeField(auto_now_add=True) likes = models.PositiveIntegerField(default=0) def serialize(self): return { "id": self.id, "creator": self.creator.user.username, "content": self.content, "created": self.created.strftime("%d %b %Y, %H:%M"), "likes": self.likes } views.py def allUsers(request): if request.method == "GET": profiles = serializers.serialize("json", Profile.objects.all()) else: return JsonResponse({"error": "Error displaying all users"}, status=400) return JsonResponse([profiles], safe=False) def allPosts(request): if request.method == "GET": posts = Post.objects.all() else: return JsonResponse({"error": "Error displaying all posts"}, status=400) posts = posts.order_by("created").all() return JsonResponse([post.serialize() for post in posts], safe=False) … -
Data Manager Role in Django
I'm a beginner in Django and I'm building a prison management system. I require three types of users -- superuser, data manager, and police officer. The superuser should be able to add any kind of user. The data manager should be able to add a police officer and perform CRUD on prisoner details. The police officer should only be able to view prisoner details. Nobody should be able to register themselves to the website. Here's part of my models.py file for the prison app: from django.db import models as md class User(AbstractUser): is_police = md.BooleanField(default=False) is_data_manager = md.BooleanField(default=False) After doing this, I found that the superuser can no longer add any users, they can only add groups. It would also be desirable for the data manager to be able to use the django-admin interface. -
UnicodeDecodeError at / 'utf-8' codec can't decode byte 0xcf in position 27: invalid continuation byte
Good afternoon! I'm Learning Django. I'm writing my first website in Visual Studio. The following problem occurred. I CAN't solve it. Can you please tell me what to do. When the site starts, the server outputs the following: UnicodeDecodeError at / 'utf-8' codec can't decode byte 0xcf in position 27: invalid continuation byte Request Method: GET Request URL: http://localhost:8000/ Django Version: 3.1.2 Exception Type: UnicodeDecodeError Exception Value: 'utf-8' codec can't decode byte 0xcf in position 27: invalid continuation byte Exception Location: C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.17 76.0_x64__qbz5n2kfra8p0\lib\codecs.py, line 322, in decode Python Executable: C:\Users\DNS\AppData\Local\Microsoft\WindowsApps\PythonSoftw areFoundation.Python.3.8_qbz5n2kfra8p0\python.exe Python Version: 3.8.6 Python Path: ['C:\\Users\\DNS\\djangoset1\\learning_log', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.8_3.8 .1776.0_x64__qbz5n2kfra8p0\\python38.zip', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.8_3.8 .1776.0_x64__qbz5n2kfra8p0\\DLLs', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.8_3.8 .1776.0_x64__qbz5n2kfra8p0\\lib', 'C:\\Users\\DNS\\AppData\\Local\\Microsoft\\WindowsApps\\Pyt honSoftwareFoundation.Python.3.8_qbz5n2kfra8p0', 'C:\\Users\\DNS\\AppData\\Local\\Packages\\PythonSoftwareFou ndation.Python.3.8_qbz5n2kfra8p0\\LocalCache\\local-packages\\Python38\\site-packages', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.8_3.8 .1776.0_x64__qbz5n2kfra8p0', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.8_3.8 .1776.0_x64__qbz5n2kfra8p0\\lib\\site-packages'] Server time: Sat, 31 Oct 2020 21:15:37 +0000 -
clone a specific attribute from Class A to Class B OneToOneField Django
i want to clone some attributes from user class from django, to an "Employee" class, so when i register a new user with the fields: "First Name" and "Last Name" clone and save on the "Employee" class too. The idea is something like this. class Employee(models.Model): id_em= models.AutoField(primary_key=True) user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = ATTRIBUTE "FIRST_NAME" FROM DJANGO USER AUTH MODEL. last_name = ATTRIBUTE "LAST_NAME" FROM DJANGO USER AUTH MODEL. bye! -
Django: Referencing uploaded file name in django web pages
Hello I am very new to python / django and I am working on a web app that will take a file that a user uploads, push it to a public S3 bucket and return a link to the file that the user can use elsewhere. After lots of trial and error I was able to get the basic functionality of the system to work. The one part I am struggling with is returning the link of the file that has been uploaded. Here is my views.py: def index(request): """The home page for the upload tool""" if request.method == 'POST': uploaded_file = request.FILES['image'] fs = FileSystemStorage() fs.save(uploaded_file.name, uploaded_file) get_uploaded_file() return render(request, 'upload_tool_app/success.html') return render(request, 'upload_tool_app/index.html') Here is my sucess.html file that I want to contain the link to the uploaded file: {% block content %} <h1>SUCCESS!</h1> <h2>Your image can be accessed from the following link:</h2> <a href="https://{bucket_name}.s3.amazonaws.com/{{ uploaded_file }}"> https://{bucket_name}.s3.amazonaws.com/{{ uploaded_file }}</a> {% endblock %} My question is how do I reference the request.Files['image'] from views in the HTML? I would really appreciate any input on this matter. -
Refactoring a field and it's references in Django
I have a model that is as follows: class Car(models.Model): make = models.CharField(max_length=128, verbose_name=_("car make"), blank=True) I now need to refactor this so that make becomes a class of it's own. class Car(models.Model): make = ForeignKey(CarMake, verbose_name=_("car make"), null=True, on_delete=models.CASCADE, blank=True) One way I thought of was changing make to legacy_make and adding a new field, _make, and then a property / getter, but it doesn't work (I understand you can't do queries this way?) Is the best ways really to a) Migrate old data to use new make class or b) Change all references to take into account possible new car make if it is present -
Django form: phone field not showing
I would like to create a contact form on my Django website. For now, this is my code: models.py: from django.db import models from phonenumber_field.modelfields import PhoneNumberField class Client(models.Model): phone = PhoneNumberField(null=False, blank=True, unique=True) forms.py: from django import forms from phonenumber_field.modelfields import PhoneNumberField class ContactForm(forms.Form): fullName = forms.CharField(max_length=100) email = forms.EmailField() phone = PhoneNumberField() message = forms.CharField(widget=forms.Textarea) views.py: def contact(request): # return render(request, 'contact.html') if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): # send email code goes here return HttpResponse('Thanks for contacting us!') else: form = ContactForm() return render(request, 'contact.html', {'form': form}) html: <form method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit" /> </form> I of course installed phonenumber_field and added it in settings.py This is the result, phone field missing: Any help is hugely appreciated! Thanks for your time. -
How to make the filter not be deleted when changing pages with django-filter and paginate
I have a problem, it turns out that I made a filter with django_filter in my ListView, the situation is that the filter works perfect but when performing a search that has more than 4 results (I have my paginate_by = 4) and want to go to On page 2 the filter is erased and shows everything as in the beginning before filtering, I will attach my code and images so you can see. My views.py @method_decorator(staff_member_required, name='dispatch') class EmployeeListView(ListView): model = Employee paginate_by = 4 def dispatch(self, request, *args, **kwargs): if not request.user.has_perm('employee.view_employee'): return redirect(reverse_lazy('home')) return super(EmployeeListView, self).dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = EmployeeFilter(self.request.GET, queryset = self.get_queryset()) return context def get_queryset(self): queryset = super().get_queryset() return EmployeeFilter(self.request.GET, queryset=queryset).qs filter.py import django_filters from .models import Employee, Accident class EmployeeFilter(django_filters.FilterSet): class Meta: model = Employee fields = { 'rutEmployee' : ['startswith'] } my employee_list.html {% extends 'core/base.html' %} {% load bootstrap %} {% load static %} {% block title %}EMPLEADOS{% endblock %} {% block content %} <main role="main"> <div class="row"> <div class="col-md-12 stretch-card"> <div class="card"> <div class="card-body"> <p class="card-title">Lista de Empleados</p> <div class="table-responsive"> <form method="GET"> {{ filter.form|bootstrap }} <button type="submit" class="btn btn-primary">Filtrar</button> </form> <hr> <table class="table table-bordered"> … -
Django backend, make email or phone required
Is an email automatically set to required when using Django? I'm trying to build an API where email or phone is required. This is the backend I built from django.contrib.auth.backends import ModelBackend from django.contrib.auth.models import User from accounts.models import User class UserBackend(ModelBackend): def authenticate(self, request, **kwargs): email = kwargs['username'] phone_number = kwargs['username'] password = kwargs['password'] try: app_user = User.objects.get(email=email) if app_user.check_password(password) is True : return app_user except User.DoesNotExist: app_user = User.objects.get(phone_number=phone_number) if app_user .check_password(password) is True : return app_user except User.DoesNotExist: pass -
Django Geolocation with API maps
I am making an IP address tracker with Django, I am using the Google Maps API to create the map and geolocate this API https://ip-api.com/docs/api:json, I want my location to be displayed on the map automatically when you open the page and if it's another IP address the location on the map of that IP address, but I don't know how to integrate the Javascript code with Django or if there is another way to make it easier or with other APIs. views.py: from django.shortcuts import render from django.views.generic import View import requests def home(request): response = requests.get('http://ip-api.com/json/') geodata = response.json() data= { 'query': geodata['query'], 'country': geodata['country'], 'timezone':geodata['timezone'], 'lat': geodata['lat'], 'lon': geodata['lon'], 'isp':geodata['isp'], 'api_key':'My api key', } return render(request, 'geolocationip/home.html', data) script.js: function initMap(){ var coord = {lat: -34.397, lng: 150.644}; var map = new google.maps.Map(document.getElementById('map'),{ zoom: 10, center: coord }); var marker = new google.maps.Marker({ position: coord, map: map }); } home.html: {% extends 'base.html' %} {% load static %} {% block content %} <h1 id="ip">IP Address Tracker</h1> <form method="get"id="form"> <input><button type="submit">Search</button> </form> <div id="card"> <p>Your ip address is <strong>{{ query }}</strong>, and you are probably in <strong>{{ country }}</strong> right now, and <strong>{{timezone}}</strong> and <strong>{{isp}}</strong></p> </div> <div id="map"></div> …