Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModuleNotFoundError: No module named 'djangoherokuapp'
When deploying my django application on heroku I am getting the error 2022-03-29T03:17:52.079107+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1014, in _gcd_import 2022-03-29T03:17:52.079107+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 991, in _find_and_load 2022-03-29T03:17:52.079108+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked 2022-03-29T03:17:52.079108+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed 2022-03-29T03:17:52.079108+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1014, in _gcd_import 2022-03-29T03:17:52.079108+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 991, in _find_and_load 2022-03-29T03:17:52.079109+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked 2022-03-29T03:17:52.079109+00:00 app[web.1]: ModuleNotFoundError: No module named 'djangoherokuapp' 2022-03-29T03:17:52.079153+00:00 app[web.1]: [2022-03-29 03:17:52 +0000] [10] [INFO] Worker exiting (pid: 10) 2022-03-29T03:17:52.116083+00:00 app[web.1]: [2022-03-29 03:17:52 +0000] [4] [INFO] Shutting down: Master 2022-03-29T03:17:52.116122+00:00 app[web.1]: [2022-03-29 03:17:52 +0000] [4] [INFO] Reason: Worker failed to boot.``` -
I want to use a filter regardless of whitespace in djangorestframework
i have class KceeService: def getTbBookCrwalingByTitleAndWriter(title, writer): bookData = [] queryset = tb_book_crawling.objects.filter(title__icontains=title, writer__icontains=writer).order_by('-publish_date') for query in queryset: bookData.append(TbBookCrawlingSerializer(query).data) return bookData but title = 'new york 1' , real column data = 'new york1' so, bookData is [] how to use title & column data overcome the whitespace? I want your help. thank,you i removed the whitespace . but , many title is same problems. how to use filter() overcome the whitespace. -
Deploy django rest to apache on window
I follow this link for deploying django https://github.com/Johnnyboycurtis/webproject#apache-and-mod_wsgi i'm using apache on xampp and this is my text adding to httpd.conf Listen 8080 ServerName localhost:8080 #first i try to use port 80 but it not work so i change to 8080 it not work too #Django Project LoadFile "C:/Users/Anaconda3/envs/ar-django/python39.dll" LoadModule wsgi_module "C:/Users/Anaconda3/envs/ar-django/lib/site-packages/mod_wsgi/server/mod_wsgi.cp39-win_amd64.pyd" WSGIPythonHome "C:/Users/Anaconda3/envs/ar-django" WSGIScriptAlias / "C:/xampp/htdocs/tutorial/tutorial/wsgi.py" WSGIPythonPath "C:/xampp/htdocs/tutorial/" <Directory "C:/xampp/htdocs/tutorial/tutorial/"> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static "C:/xampp/htdocs/tutorial/static/" <Directory "C:/xampp/htdocs/tutorial/static/"> Require all granted </Directory> and when i run mod_wsgi-express module-config this is my output LoadFile "C:/Users/Anaconda3/envs/ar-django/python39.dll" LoadModule wsgi_module "C:/Users/Anaconda3/envs/ar-django/lib/site-packages/mod_wsgi/server/mod_wsgi.cp39-win_amd64.pyd" WSGIPythonHome "C:/Users/Anaconda3/envs/ar-django" when i run apache server. apache PID keep changing what wrong with setting in httpd.conf file and how to fix it Thanks for any kind of help -
Keep getting Django form error "this field is required" even though the field has been filled
I am creating a Django web app and I'm starting out on using Django forms. I keep getting this error even though this project name field is entered. <tr><th><label for="id_title">projectName:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="title" maxlength="100" required id="id_title"></td></tr> Below is my code. I'm not sure on what I'm missing. index.html: <form id="project_form" action="{% url 'createproject' %}" method="post"> {% csrf_token %} <div class="form-group row"> <label for="projectName" class="col-sm-2 col-form-label">Project Name:</label> &nbsp; <div class="col-sm-9"> <input type="text" class="form-control" placeholder="Enter Project Name" name="projectName" id="projectName"> </div> </div> <input type="submit" class="btn btn-primary" id="submit-project-btn"> </form> forms.py: class CreateEditProjectForm(forms.Form): title = forms.CharField(label="projectName", max_length=100, required=True) models.py: class TestProject(models.Model): creator = models.ForeignKey(User,on_delete=models.CASCADE,related_name="testcreatorId") projectName = models.CharField(max_length=200, default=None) created_dt = models.DateTimeField(auto_now_add=True, auto_now=False) last_modified_dt = models.DateTimeField(auto_now_add=False, auto_now=True) views.py: def create_project(request): print("in create_project") print(request.method) if (request.method == "POST"): form = forms.CreateEditProjectForm(request.POST) print(form) if form.is_valid(): projectName = form.cleaned_data["projectName"] print(projectName) if (len(projectName) > 0): creator = User.objects.get(id=request.session['_auth_user_id']) project = TestProject(projectName=projectName, creator=creator) print(project) project.save() return HttpResponseRedirect(reverse("index")) return render(request, "index.html", { "form": form }) return render(request, "index.html", { "form": form }) else: form = forms.CreateEditProjectForm() return render(request, "index.html", { "form": form }) -
AWS SES Setup with Django
I am trying to add AWS SES into my project. Where I get a different region listed MessageRejected at / An error occurred (MessageRejected) when calling the SendRawEmail operation: Email address is not verified. The following identities failed the check in region US-EAST-1: email@hotmail.com In the AWS verified identities it is listed: email@hotmail.com Email address Verified I have the permissions for the SES for my policy for that user. Attached from group AmazonSESFullAccess AWS managed policy from group AmazonSESFullAccess Also my settings.py EMAIL_BACKEND = 'django_ses.SESBackend' EMAIL_HOST = 'email-smtp.us-west-2.amazonaws.com' EMAIL_PORT = 465 EMAIL_USE_SSL = True EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' Where it's used from django.core.mail import send_mail from django.conf import settings send_mail(email_subject, email_message,'arundeepchohan2009@hotmail.com',['arundeepchohan2009@hotmail.com']) -
Post and Delete vs. Post and Patch for Model's BooleanField?
I'm using Postgres. I've seen threads comparing DELETE and INSERT vs. UPDATE but my use case is slightly different: I want to allow users to "check" and "uncheck" an Item model to be true or false with the default state being false. Does it make more sense to: 1) Post and Delete Create a CheckedItem model (with a ForeignKey to the Item) when they check. Delete that object when they uncheck. If a CheckedItem does not exist, its Item is unchecked. 2) Post and Patch Create a CheckedItem model (with a ForeignKey to the Item) with a check BooleanField as true when they check. Patch the BooleanField to false when they uncheck. If a CheckedItem does not exist or has a false check field, its Item is unchecked. If it matters, there's two other ForeignKeys I would have on every CheckedItem - one for the user and one for the ItemParent. -
HOW to send authentication number by e-mail
I want to send an 8-digit authentication number by e-mail. No matter how hard I try, I don't know what I'm doing wrong. First, I set the smtp. Then, I filled out the form. After creating the view, I created a template. After entering e-mail and username, I pressed the Send button. WHAT? id: email: [29/Mar/2022 09:43:39] "GET /recovery/pw/?email=wlgns000%40gmail.com&username=wlgns HTTP/1.1" 200 2030 However, only these logs appear, and the authentication number does not come by e-mail. How can I send an authentication number by e-mail? #settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.naver.com' EMAIL_PORT = 465 EMAIL_HOST_USER = #email EMAIL_HOST_PASSWORD = #password EMAIL_USE_TLS = True DEFAULT_FROM_MAIL = EMAIL_HOST_USER {% load static %} <!DOCTYPE html> <html lang="KO"> <head> .... <link href="{% static 'users/css/recovery_pw.css' %}" rel="stylesheet"> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="{% static 'users/js/recovery_pw.js' %}"></script> <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"> <script> $.ajaxSetup({ headers: { "X-CSRFToken": '{{csrf_token}}' } }); </script> </head> <body> {% block content %} <form method="get" enctype="multipart/form-data"> {% csrf_token %} <div class="container"> <div class="inner-box"> ... <div class="input-box"> <div class="id"> <input type="email" placeholder="등록하신 메일로 인증번호가 발송됩니다." name="email" maxlenth="20" autocomplete="off" value="{{ form.email.value|default_if_none:'' }}" required /> </div> <div class="password"> <input type="username" placeholder="아이디를 입력하세요" name="username" maxlength="20" value="{{ form.username.value|default_if_none:'' }}" required /> </div> </div> <div class="btn"> <div class="btn-white" id="btn_white"><button type="submit">send … -
DRF: how to create custom FilterSet to filter nearest users by distance
I'm trying to create custom FilterSet for filtering nearby users by distance. For example if I send GET /api/list/?distance=300, I want to get all nearby users who are lower or equals to 300m far away My model has 2 fields: latitude = models.DecimalField( # [-90.000000, 90.000000] max_digits=8, decimal_places=6, null=True ) longitude = models.DecimalField( # [-180.000000, 180.000000] max_digits=9, decimal_places=6, null=True ) objects = ClientManager() My ClientManager has function for getting coords from model: def get_geo_coordinates(self, pk): """ :param pk: - client id :return: client's coords """ instance = self.get(pk=pk) data = (instance.latitude, instance.longitude) return data` My GetListAPIView class GetClientListAPIView(ListAPIView): """ Returns list with filtering capability Available filter fields: gender, first_name, last_name, distance """ serializer_class = ClientSerializer queryset = Client.objects.all() permission_classes = [IsAuthenticated] filter_backends = [DjangoFilterBackend] filter_class = ClientFilter` My ClientFilter class ClientFilter(FilterSet): distance = filters.NumberFilter(method='get_nearest_clients') def get_nearest_clients(self, queryset, name, value): sender_coords = Client.objects.get_geo_coordinates(pk=self.request.user.id) test_coords = Client.objects.get_geo_coordinates(pk=31) dist = get_great_circle_distance(sender_coords, test_coords) class Meta: model = Client fields = ['gender', 'first_name', 'last_name'] Here I'm using my function for calculating distance between two clients: def get_great_circle_distance(first_coords, second_coords): """ :param first_coords: (first_client_latitude, first_client_longitude) in degrees :param second_coords: (second_client_latitude, second_client_longitude) in degrees :return: distance """ earth_radius = 6_400_000 # in metres la_1, lo_1 = map(radians, first_coords) … -
Include parentheses in django 'layout.html'
I have a line in my layout.html file: <a class="nav-link" href="{% url 'index' %}">Watchlist <span class="badge bg-secondary">{{ user.watchlist.all() | length }}</span></a> But the Django template does not allow () inside of {{ }}. I cannot even do a check in views.py and pass it on in the render function as this is the layout.html file which is not rendered in any view. How do I perform the user.watchlist.all() function then? -
What is the recommended approach to create managed identities in python?
We are trying to use Azure sdk to create managed identities. Seeing the documentation on python sdk on MSI it seems it is the suggested approach. However the last update was 2.5 years ago, we also see managed identities for Azure resources seems to be the new name- "Managed identities for Azure resources is the new name for the service formerly known as Managed Service Identity (MSI)." But I was not able to find SDK for it. What would be the current recommended approach to use python sdk to create managed identities? Any help is appreciated. Thanks! -
Is there something I am doing wrong with my Content Aggregator Website? I cannot get the articles to show up
I followed an online tutorial, but was able to scrape different websites. I cannot get the article headlines to show up. I am not sure if it is a problem with my return function or my HTML file. This is the code for the views.py file from django.shortcuts import render import requests from bs4 import BeautifulSoup as bs4 soup = requests.get("https://www.washingtonpost.com/") content = bs4(soup.content, 'html5lib') headings = content.findAll("div", {"class": "headline relative gray-darkest pb-xs"}) wpnews = [] for span in headings: wpnews.append(span.text) soup2 = requests.get("https://abcnews.go.com/") content2 = bs4(soup2.content, 'html5lib') headings2 = content2.findAll("div", {"class": "News__Content__Container"}) for h2 in headings2: abcnews.append(h2.text) def index(req): return render(req, 'news/index.html', {'Washington Post News': wpnews, 'ABC News': abcnews} And this is the portion of the HTML file that's supposed to show the headlines: <div class="row"> <div class="col-6"> <h3 class="text-centre"> Washington Post News </h3> {% for n in wpnews%} <h5> - {{n}} </h5> <hr> {% endfor %} <br> </div> <div class="col-6"> <h3 class="text-centre">ABC News</h3> {% for htn in abcnews %} <h5> - {{htn}} </h5> <hr> {% endfor %} <br> </div> </div> python html django -
Django pagination and current page with other value currency name button "USD" or "EUR"
I try to pass 2 values in my Django crypto currency project page_number and currency for example USD. Page Load Crypto currencies with defalut converter to price in USD User have possibility to change currency from USD to EUR or JPY or CNY When Im on 1 page it works fine but on second and further takes me back to the first page convert only crypto currencies belonging that page My question is how to convert crypto to USD to EUR or JPY or CNY like on first page that the page I am currently on would be sent(saved) index_buttons.py <div class="row mb-4"> <div class="col-md mb-4"> {% for item in buttons %} <a href="{% url 'index' %}?currency_type={{item.currency_type}}" class="btn btn-outline-dark {{item.active}}" role="button">{{item.display_text}}</a> {% endfor %} </div> </div> views.py def index(request): selected_currency_type = request.GET.get('currency_type', "USD") buttons = [ {"currency_type": "USD", "active": "", "display_text": "USD"}, {"currency_type": "EUR", "active": "", "display_text": "Euro"}, {"currency_type": "CNY", "active": "", "display_text": "Chinese Yuan"}, {"currency_type": "JPY", "active": "", "display_text": "Japanese Yen"}, ] for button in buttons: if button['currency_type'] == selected_currency_type: button['active'] = 'active' currecies_list = load_currencies(selected_currency_type) paginator = Paginator(currecies_list, 12) page_number = request.GET.get("page") page_obj = paginator.get_page(page_number) context = { "user": request.user, "page_obj": page_obj, "buttons" : buttons, "active_currency_name" : selected_currency_type, … -
How to redirect if error occurs inside class-based view Django
I have a class-based view (lets say, DetailView) which renders a page with a list of objects based on slug in the URL. But if an object with the given slug does not exist, it gives me an error. What I want is to redirect to the main page instead of raising an error. It should be easy, but I can't understand how to do this, so I wanna ask for help here. Example: views.py class ShowExerciseRecords(ListView): def get_queryset(self): exercise = Exercise.objects.get(slug=self.kwargs['slug']) return exercise.record__set.all() urls.py urlpatterns = [ path('/exercise/<slug:slug>/', ShowExerciseRecords.as_view()) path('', index, name='home') ] -
Pytest to verify the existence of fields listed in list_display
I'm writing unit tests and want to know if it's possible to make a test of the existence of all list_display fields in the admin interface. for example for this model: class Order(models.Model): class PaymentStatuses(models.TextChoices): PENDING = "pending" PAID = "paid" REFUNDED = "refunded" order_ref = models.CharField(max_length=128, unique=True) payment_status = models.CharField(max_length=50, choices=PaymentStatuses.choices) user = models.ForeignKey( "users.User", on_delete=models.CASCADE, related_name="orders" ) shipping_cost = models.DecimalField(max_digits=9, decimal_places=2, default=0) delivery_datetime = models.DateTimeField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) @property def total_price(self) -> Decimal: total_price = Decimal(0) for item in self.items.all(): total_price += item.unit_price * item.quantity return total_price I want to add total_price field to the list of Orders displayed in the admin interface and make a test for that. how to verify the existence of the field in the content of response = client.get('/admin/orders/order/') -
Can I use the values from a form in other form with Django?
I have a Django app with two forms where the views.py looks like this: import pandas as pd import numpy as np from django.contrib.auth.decorators import login_required from django.shortcuts import render from django.template.response import TemplateResponse from pbmcalculator.models import PbmCalculator, simulator from django.core.cache import cache import json @login_required def subs_calc(request): # this is from the first form # selection = request.GET.get("id", None) customer = request.GET.get("customer", None) initial_date = request.GET.get("initial_date", None) final_date = request.GET.get("final_date", None) if selection is not None and 'initial_date' in request.GET: calculation_target = PbmCalculator(customer, initial_date, final_date) html = TemplateResponse( request, "pbmcalculator/table.html", { some operations }, ) return html if 'generico_sim' in request.GET: # this is from the second form # brand_sim = request.GET.get("brand_sim",None) generico_sim = request.GET.get("generico_sim",None) marca_sim = request.GET.get("marca_sim",None) initial_date_sim = '2021-08-08' final_date_sim = '2021-08-15' calculation_sim = simulator(brand_sim, initial_date_sim, final_date_sim) html = TemplateResponse( request, "pbmcalculator/table1.html", { some operations }, ) return html return render(request, "pbmcalculator/subs_calc.html", {"selected": False}) So I want to use the variables initial_date and final_date in the second if statement to fill the initial_date_sim and final_date_sim. I tried several ways but none worked. Some idea? -
Django UpdateView only possible within 15 minutes
I have a small app. In the model I have: created_at = models.DateTimeField(auto_now_add=True, default = 'time and date created'), Now I want that after 15 minutes of the created_at the UpdateView is no longer executable. however I just can't even display the creats_at class update_post(UpdateView): print(Posts.created_at) model = Posts ... This show only (<django.db.models.fields.DateTimeField>,) -
How can I run multiple Django servers from one Pycharm Project?
I want to be able to run three different Django servers from within 1 Pycharm project, however, when you go into: settings -> languages & frameworks -> Django it seems that you can only set 1 Django project root, 1 Django settings.py file, and 1 Django manage.py file for all the Django servers you have running. Short of creating a new Pycharm project for each Django server, which I do not want to do, is there any way I can have a separate configuration for each of the three Django projects? -
Saving centroid of a (multi)polygon as point geometry in a model
I have two tables, one with multipolygon geometries, the other with a column for point geometries. I want the centroid of the selected polygon to be saved as the point geometry for the other table. class matview_all_administrative_units(models.Model): lau_id = models.IntegerField(primary_key=True) ortsgemeinde = models.CharField(max_length=150) verwaltungsgemeinde = models.CharField(max_length=150) landkreis_bezirk = models.CharField(max_length=150) bundesland_kanton = models.CharField(max_length=150) staat = models.CharField(max_length=150) geom = models.MultiPolygonField(srid=4326) class Meta: managed = False db_table = 'administrative_hierarchy_full_geom' class site(models.Model): sid = models.AutoField(primary_key=True) site_name = models.CharField(max_length=250) site_notes = models.CharField(max_length=2500, blank=True, null=True) municipality = models.ForeignKey('local_administrative_unit', on_delete=models.PROTECT) geom = models.PointField(srid=4326) def __str__(self): return '{}, {} ({})'.format(self.sid, self.site_name, self.municipality) To add a new site, an existing administrative unit must be associated with it and the center of it's polygon should be used as the location/geometry of the site. For now I made this: class NewSiteView(CreateView): model = models.site form_class = forms.NewSiteForm template_name = 'datamanager/newsite.html' success_url = '/sites/' calling this form: from django.forms import ModelForm, HiddenInput from django.contrib.gis.db.models.functions import Centroid from . import models class NewSiteForm(ModelForm): class Meta: model = models.site fields = ['site_name', 'site_notes', 'municipality','geom'] widgets = { 'geom': HiddenInput(), } def clean(self): super().clean() self.cleaned_data['geom'] = Centroid(models.matview_all_administrative_units.objects.values('geom').filter(lau_id=self.cleaned_data['municipality'].lau_id)) however, this leads to this error: So I am basically not calculating a point but a 'centroid object' … -
Django: constraint with nullable multiple field conditions
I have a model in Django/PostgreSQL project and want to add following constraints to three nullable fields: either all fields are NULL, either all of them aren't. Here's code (simplified): class SomeModel(models.Model): ... a = models.IntegerField(nullable=True) b = models.DateTimeField(nullable=True) c = models.DateTimeField(nullable=True) ... class Meta: constraints = [ models.CheckConstraint( check=( (Q(a__isnull=True) & Q(b__isnull=True) & Q(c__isnull=True)) | (Q(a__isnull=False) & Q(b__isnull=False) & Q(c__isnull=False)) ) ) ] If I understand correctly, I've just described two possible states of those three fields. First is "all three are NULL", second is "none of them are NULL". But what I got, actually, is "none of them can be NULL". Django admin panel insists on filling all of the fields, they all are mandatory. How can I fix this behaviour? Thanks! -
After deploy django projcet,emal send doesn't work.Can anyone help me to fix that?
In my django project when ı am working localhost sending mail is working.After that ı deployed my project on aws,but at this time email send doesn't work.Can anyone explain this? My settings/base.py file EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_PASSWORD = env('EMAIL_HOST_PASSWORD') EMAIL_HOST_USER = env('EMAIL_HOST_USER') EMAIL_PORT = '587' # EMAIL_USE_SSL = True DEFAULT_FROM_EMAIL = EMAIL_HOST_USER EMAIL_USE_TLS = True -
How can I show mi profile picture?
The photo is uploaded and saved in the database but I can't show the picture in the template. Now, what can I do? Where is the problem? What will be the logic? Settings: STATIC_URL = '/static/' STATICFILES_DIRS = [STATIC_DIR] MEDIA_URL = '/media/' Urls: urlpatterns = [ path('admin/', admin.site.urls), path('', include('business_app.urls')), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Views: def change_profile_picture(request): if request.user.is_authenticated: if request.method == "POST": profile_picture = request.FILES['profile_picture'] if 'profile_picture' in request.FILES else None user = get_object_or_404(User, pk=request.user.pk) if request.user.pk != user.pk: return redirect("/") Profile_picture.objects.create( Profile_picture = profile_picture, USer = request.user, ) return redirect("/") return render(request,'0_index.html') Models: class Profile_picture(models.Model): USer = models.ForeignKey(User,default=None,on_delete=models.CASCADE, related_name="user_propic") Profile_picture = models.ImageField(upload_to="3_profile_picture/",default='3_profile_picture/avatar.png', null=True, blank=True) templates: <img src="static/1_images/3_about.jpg" alt="" width="100" class="img-fluid rounded-circle mb-3 img-thumbnail shadow-sm"> -
Can a textfield in postgres be used with a charfield in django?
I have a table in postgres with a column description that had the type varchar(2000), so in django: description = serializers.CharField(......., max_length = 2000) I want to change the description column in postgres to type text Can I leave the description as a charfield? Or do I have to change it to a textfield? I still want to have max_length specified but change it to 5000, ie: description = serializers.CharField(......., max_length = 5000) I've tried to read the docs: https://www.django-rest-framework.org/api-guide/fields/#charfield, but I didn't see it being stated explicitly. From what I've seen, it says: CharField corresponds to django.db.models.fields.CharField or django.db.models.fields.TextField I'm guessing that means it's ok? I also looked around on stackoverflow: What's the difference between CharField and TextField in Django?, but I didn't see it being stated explicitly either. -
how to store user data from user model inside a database table in django
I have a Buyer table in mysql database and I want to take the username , email, password from User model ( default django model ) and store it inside Buyer table, Buyer model in models.py: class Buyer(models.Model): row_id = models.AutoField(primary_key=True) user_name = models.CharField(unique=True, max_length=50) user_password = models.CharField(max_length=16) first_name = models.CharField(max_length=50) middle_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50) email = models.CharField(unique=True, max_length=100) home_phone = models.CharField(max_length=20, blank=True, null=True) mobile_phone = models.CharField(unique=True, max_length=20) personal_id = models.CharField(max_length=30, blank=True, null=True) idtype_fk = models.ForeignKey('Idtype', models.DO_NOTHING, db_column='idType_FK', blank=True, null=True) # Field name made lowercase. personal_id_country_fk = models.ForeignKey('Country', models.DO_NOTHING, db_column='personal_id_country_FK',related_name='personal_id_country_fk') # Field name made lowercase. address_line_1 = models.CharField(db_column='address_Line_1', max_length=200) # Field name made lowercase. address_line_2 = models.CharField(db_column='address_Line_2', max_length=200, blank=True, null=True) # Field name made lowercase. p_o_box = models.CharField(max_length=20, blank=True, null=True) city = models.CharField(max_length=50) country_fk = models.ForeignKey('Country', models.DO_NOTHING, db_column='country_FK' , related_name='country_fk') # Field name made lowercase. gender_fk = models.ForeignKey('Gender', models.DO_NOTHING, db_column='gender_FK') # Field name made lowercase. bdate = models.DateField() def __str__(self): return 'User: ' + self.user_name class Meta: managed = False db_table = 'buyer' and after the registration User/Buyer can add more information such as first name , mobile phone etc.. in the profile page -
Django - details of one account showing up on another account
I've have a pet registration system where the customer can log into their account and register their animals. However once you have registered the animal and log out and another user logs in that user can see all the pets of all users. I'm not sure what's causing this. my views.py def customer_profile(request): if request.method == "GET": if request.user.is_authenticated: get_pets = PetRegistration.objects.filter() context = { "pets": get_pets, } return render( request, "registration/customer-profile.html", context=context ) return redirect("login") if request.method == "POST": context = {} return render(request, "registration/customer-signup.html", context=context) def pet_register(request): if request.method == "GET": if request.user.is_authenticated: form = PetRegistrationForm() context = { "form": form, } return render(request, "registration/pet-register.html", context=context) return redirect("login") if request.method == "POST": form = PetRegistrationForm(request.POST, request.FILES) context = { "form": form, } if form.is_valid(): form = form.save(commit=False) form.user = request.user form.save() return redirect("customer_profile") return render(request, "registration/pet-register.html", context=context) model.py class PetRegistration(models.Model): user = models.ForeignKey(Account, on_delete=models.CASCADE) name = models.CharField(max_length=30) image = models.ImageField(null=True, blank=True) age = models.CharField(max_length=30) animal_type = models.CharField(max_length=30) vaccination_status = models.CharField(choices=STATUS, max_length=20) def __str__(self): return self.name -
Create relation number based on PK in Django
I am trying for a couple of days to find a way to create a relation number based on the PK in models.py when I make a new object. The reason why I try this is, is to have a 8 digit number starting from 00000001 till 999999999. I already tried the following: client.objects.latest('pk') Result NameError: name 'client' is not defined from clients.models import client Result: ImportError: cannot import name 'client' from partially initialized module 'clients.models' (most likely due to a circular import) def save(self, *args, **kwargs): self_pk = self.objects('pk') self.relation_number =self_pk self.save(*args, **kwargs) Result: AttributeError: Manager isn't accessible via Section instances Hope someone can help me with this.