Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sorting DataTable by recent date
I have a table and it is sorted by the old date. I just want to make its default sorting is the recent date. the code is: <script> $(document).ready( function () { $('#table_id').DataTable({ dom: 'B<"clear">lfrtip', buttons: { name: 'primary', buttons: [ 'copy', 'csv', 'excel', 'pdf' ] } }); }); </script> and it looks like: I tried many solutions on the net but all didn't work! <script> $(document).ready( function () { $('#table_id').DataTable({ dom: 'B<"clear">lfrtip', buttons: { name: 'primary', buttons: [ 'copy', 'csv', 'excel', 'pdf' ] } }).asSorting([[0, "desc"]]); }); </script> and this <script> $(document).ready( function () { $('#table_id').DataTable({ dom: 'B<"clear">lfrtip', buttons: { name: 'primary', buttons: [ 'copy', 'csv', 'excel', 'pdf' ] } }).fnSort([[1, "acs"]]); }); </script> and this too <script> $(document).ready( function () { $('#table_id').DataTable({ "order": [[ 3, "desc" ]] dom: 'B<"clear">lfrtip', buttons: { name: 'primary', buttons: [ 'copy', 'csv', 'excel', 'pdf' ] } }); }); </script> and this one > <script> > $(document).ready( function () { > $('#table_id').DataTable({ > "aoColumnDefs": [ > { "asSorting": [ "asc" ], "aTargets": [ 0 ] } > ] > dom: 'B<"clear">lfrtip', > buttons: { > name: 'primary', > buttons: [ 'copy', 'csv', 'excel', 'pdf' ] > } > }); }); </script> any suggestions? -
Django ManifestStaticFilesStorage and imports within javascript files
The Django 3.2 ManifestStaticFilesStorage adds a hash value to javascript files called from within a template and this is working as expected. However, some javascript files import from other javascript files and those imported filenames are not translated to a hashed value. The ManifestStaticFilesStorage documentation indicates that this is done for for CSS files when it finds the import rule and url() statement but is silent on how to do it for javascript. Any suggestions on how to get this to work? As an example, this line in the html template: <script src="{% static 'myapp/js/myjavascript.js' %}" type="module"></script> is rendered like this in the browser (works as expected): <script src="/static/myapp/js/myjavascript.12345abc.js" type="module"></script> But within the myjavascript.js file, this line is left untouched, meaning that the browser could still have a cached version of the imported javascript file and use that instead of an updated version. import {func1, func2, func3} from './javascript_helper_lib.js'; -
django adds 127.0.0.1 to the links while running on a real server and not real web address
I run django on a Nginx server. The website is available at this address on the internet: www.website-example.com I have some links in one of the pages. But when I click on the I get this: 127.0.0.1:8000/books/book1.jpeg I should get the below address: www.website-example.com/books/book1.jpeg my allowed hosts in setting is like below: ALLOWED_HOSTS = ['www.website-example.com', '127.0.0.1'] What is wrong that I still get 127.0.0.1? I also removed 127.0.0.1 but the website stops working and says you should add 127.0.0.1 to allowed hosts. -
user with only password required
I want the user to authenticate only with his password and a field from another model that is not shown.I have here the BaseUser of django that I am trying to customize. In the code following the password and email are required.I don't want email to be required anymore class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): if not email: raise ValueError("L'adresse e-mail donnée doit etre definie") email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, **extra_fields): extra_fields.setdefault("is_staff", False) extra_fields.setdefault("is_superuser", False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault("is_staff", True) extra_fields.setdefault("is_superuser", True) if extra_fields.get("is_staff") is not True: raise ValueError("Superuser must have is_staff=True") if extra_fields.get("is_superuser") is not True: raise ValueError("Superuser must have is_superuser=True") return self._create_user(email, password, **extra_fields) class User(AbstractUser): username = None email = models.EmailField('email adress', unique=True) telephone = models.CharField(max_length=20) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] I want only the password to be required. What should I do so that the email is no longer required? -
Nothing happens after hitting the form button , how to return to the main page of the site after payment? [Django]
i'm studying django and i'm trying to get some practice with this e-commerce site. The problem I have is that at the time of paying with the card (in reality it is not a real payment) the user should be redirected to the home page but in reality nothing happens. Can you help me ? These are the main files. models.py from django.db import models from django.contrib.auth.models import User class Admin(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) full_name = models.CharField(max_length=50) image = models.ImageField(upload_to="admins") mobile = models.CharField(max_length=20) def __str__(self): return self.user.username class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) full_name = models.CharField(max_length=200) address = models.CharField(max_length=200, null=True, blank=True) joined_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.full_name class Category(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(unique=True) def __str__(self): return self.title class Product(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(unique=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) image = models.ImageField(upload_to="products") selling_price =models.DecimalField(max_digits=10,default=0,decimal_places=2,null=True) marked_price = models.DecimalField(max_digits=10,default=0,decimal_places=2,null=True) description = models.TextField() warranty = models.CharField(max_length=300, null=True, blank=True) return_policy = models.CharField(max_length=300, null=True, blank=True) view_count = models.PositiveIntegerField() def __str__(self): return self.title class ProductImage(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) image = models.ImageField(upload_to="products/images/") def __str__(self): return self.product.title class Cart(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True) total = models.DecimalField(max_digits=10,default=0,decimal_places=2,null=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return "Cart: " + str(self.id) class CartProduct(models.Model): cart = models.ForeignKey(Cart, … -
Integrating Stripe - JSONDecodeError
Hello I am integrating stripe with my Django App and i struggle, because I get an error. I put all of the code which I think is needed for Stripe integration. I would be pleased for any advice. ERROR: "JSONDecodeError, Expecting value: line 1 column 1 (char 0) " views.py @csrf_exempt def create_checkout_session(request, pk): request_data = json.loads(request.body) cart = Cart.objects.filter(order_user = request.user) stripe.api_key = os.environ.get('stripeAPI') checkout_session = stripe.checkout.Session.create( customer_email = request_data['email'], payment_method_types=['card'], line_items=[ { 'price_data': { 'currency': 'usd', 'product_data': { 'name': cart.order_items, }, 'unit_amount': cart.total, }, 'quantity': 1, } ], mode='payment', success_url=request.build_absolute_uri( reverse('success-page') ) + "?session_id={CHECKOUT_SESSION_ID}", cancel_url=request.build_absolute_uri(reverse('cancel-page')), ) HTML template: <form action="{% url 'checkout-page' 5 %}" method="GET"> <button type="submit">Checkout</button> </form> URL path: path('create_checkout_session/<int:pk>', views.create_checkout_session, name='checkout-page'), models.py class OrderItem(models.Model): order_item = models.ForeignKey(Item, on_delete=CASCADE, null=True) quantity = models.IntegerField(default=1) class Cart(models.Model): order_user = models.OneToOneField(User, on_delete=CASCADE) order_items = models.ManyToManyField(OrderItem) ordered = models.BooleanField(default=False) class Item(Visits, models.Model): title = models.CharField(max_length=150) price = MoneyField( decimal_places=2, default=0, default_currency='USD', max_digits=11, ) image = models.ImageField(upload_to='pictures', default='static/images/man.png') description = models.TextField(default="Item") visits = models.IntegerField(default=0) total = MoneyField( default=0.00, decimal_places=2, max_digits=11, default_currency='USD') -
Where is ID saved in django ModelAdmin autocomplete_fields?
I am rewriting some administration interface to django 2.2, currently using django autocomplete_fields admin feature. Simply said I have ModelAdmin object OrderAdmin, which has nested TabularInline ProductAdmin: variable-length table of products which might be added to order. Each of these ProductAdmin holders just contains ForeignKey to actual product class, with some other attributes. Now I wonder: where does django store id - ForeignKey - of item selected with autocomplete field? It doesn't mark OPTION in selectbox as selected, and although there is suspicious hidden input field with #cashregisterproduct_set-0-id on page, it doesn't have any value. Or is there some special way how to access it? I was thinking about adding id to __str__ method of model and parsing, but thats just ugly. Thanks for tip. -
How to get the current projct_id in Django
I have a view where in the options input I want to list just those users who related to the current project but I can't. I don't know how to write a query that list just these users without I use the project_id from the url. I don't want the projekt_id in the url. This is the point, where I stuck: views.py def kapcsolodasok(request, projekt_id): if request.method == 'POST': kap_bar_01 = request.POST.get('kap_bar_01') kap_bar_02 = request.POST.get('kap_bar_02') kapcsolodasok = kapcsolodasok(kap_bar_01=kap_bar_01, kap_bar_02=kap_bar_02) kapcsolodasok.save() related_users = Profile.objects.raw('SELECT stressz_profile.id, last_name, first_name, stressz_profile.projekt_id FROM stressz_projekt JOIN stressz_profile ON stressz_projekt.id = stressz_profile.projekt_id JOIN auth_user ON auth_user.id = stressz_profile.user_id WHERE stressz_projekt.id = %s', [projekt_id]) //how to replace projekt_id with the related projekt_id of the request.user context = { 'related_users': related_users, } return render(request, 'stressz/kapcsolodasok.html', context) models.py class Kapcsolodasok(models.Model): def __str__(self): return str(self.user_name) user_name = models.ForeignKey(User, on_delete=models.CASCADE, default=1) date = models.DateField(auto_now_add=True, auto_now=False, blank=True) kap_bar_01 = models.TextField(max_length=200) kap_bar_02 = models.TextField(max_length=200) class Profile(models.Model): def __str__(self): return str(self.user) user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) date = models.DateField(auto_now_add=True, auto_now=False, blank=True) projekt = models.ForeignKey(Projekt, on_delete=models.CASCADE, default=3) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() class Projekt(models.Model): def __str__(self): return str(self.projekt) projekt = models.TextField(max_length=150) date = models.DateField(auto_now_add=True, … -
Unable to import DefaultAccountAdapter from settings.py
I would like to use a custom account adapter, but as soon as I import: from allauth.account.adapter import DefaultAccountAdapter in settings.py, I get the error django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Here is the whole error dump: (env) (base) C:\Dropbox\Parnasa\Web\drmeir>python manage.py runserver Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\django\core\management\__init__.py", line 363, in execute settings.INSTALLED_APPS File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\django\conf\__init__.py", line 82, in __getattr__ self._setup(name) File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\django\conf\__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\django\conf\__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "c:\users\meir\anaconda3\lib\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 "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Dropbox\Parnasa\Web\drmeir\mysite\settings.py", line 180, in <module> from allauth.account.adapter import DefaultAccountAdapter File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\allauth\account\adapter.py", line 17, in <module> from django.contrib.auth.models import AbstractUser File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\django\contrib\auth\models.py", line 3, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\django\contrib\auth\base_user.py", line 48, in <module> class AbstractBaseUser(models.Model): File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\django\db\models\base.py", line 108, in __new__ app_config = apps.get_containing_app_config(module) File … -
Django REST Framework : How to define a viewset
Context I have two viewsets, with their own routers to automatically generate the URLs from them : ModelAViewset ModelBViewset For now, the ModelAViewset details can be retrieved through the following URL : {base_url}/model-a/<slug> With '<slug>' being the ModelA 'slug' field, as a lookup_field. Questions Is there a way to use a more explicit lookup_field value, dynamically based on the model name ? Like this : {base_url}/model-a/<model_a_slug> Note : To keep it simple in the model, I would rather like to leave the 'slug' field name of ModelA as is Based on Viewsets and Routers, is there a way to retrieve the JoinRequestViewset details through a multi lookup_fields ? With an URL like : {base_url}/model-a/<model_a_slug>/model-b/<model_b_pk> Thanks, by advance -
cart session in django
I use the session to create a shopping cart. I have a product model and a model for Variant, which I color and size my products in the Variant model. So that I can have products with different colors and sizes as well as different prices. The shopping cart I created with Session has a problem. The problem I have is that if the product has 3 different colors and each color has a different price, I have trouble displaying the price in the cart and I do not know how to act. How should I display the prices of my Variant model in the template? my Product model: class Product(models.Model): name = models.CharField(max_length=200) price = models.IntegerField(default=0) my Variant model: class Variants(models.Model): name = models.CharField(max_length=100) product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='product_var',) size = models.ForeignKey(Size, on_delete=models.CASCADE) color = models.ForeignKey(Color, on_delete=models.CASCADE) price = models.IntegerField(default=0) my session cart : CART_SESSION_ID = 'cart' class Cart: def __init__(self, request): self.session = request.session cart = self.session.get(CART_SESSION_ID) if not cart: cart = self.session[CART_SESSION_ID] = {} self.cart = cart def __iter__(self): product_ids = self.cart.keys() products = Product.objects.filter(id__in=product_ids) cart = self.cart.copy() for product in products: cart[str(product.id)]['product'] = product def add(self, product, quantity): product_id = str(product.id) if product_id not in self.cart: … -
make decorator Only the creator of Content can manipulate it
I have created Two decorator to block anyone to Access to specific content like: @method_decorator(login_required(login_url='core:login'), name='dispatch') @method_decorator(allowed_users(allowed_roles=['writer']), name='dispatch') class BookDeleteView(BSModalDeleteView): model = Book template_name = 'book/book_delete.html' success_message = 'Success: book was deleted.' success_url = reverse_lazy('core:book_list') i want to create decorator seems like this book=Book.objects.get(id=pk) if request.user==book.writer.profile.user: -
How to put data to html but to look like excel sheet in django?
I have been studying how to put data from my excel document to the html, and I have found a way but it is bit tricky, maybe you can help me with this? (Link of documentation) This is where I have been studying, but in this case it is defined what is a 'choice' and 'question'. Is there a way to do this without defining these? Tu upload random document and to load in html? -
django-mptt: How to auto select children in admin when selecting parent?
I have some troubles when selecting parent - children are not auto selected. For example when I select Cluster #2 its children (Store #1 and Store #2) are not being selected: How can I fix that? It's important because I need to create many-to-many (Deviation-Orgunit) links only with stores (with leafs). Models: from django.db import models from mptt.fields import TreeForeignKey from mptt.models import MPTTModel class Orgunit(MPTTModel): name = models.CharField( max_length=100 ) type = models.CharField( choices=[ ('MACRO', 'Макро'), ('CLUSTER', 'Кластер'), ('KUST', 'Куст'), ('STORE', 'Магазин') ], max_length=100 ) parent = TreeForeignKey( 'self', on_delete=models.CASCADE, null=True, blank=True, related_name='children' ) def __str__(self): return self.name class Deviation(models.Model): name = models.CharField(max_length=100) number = models.PositiveIntegerField(null=True) orgunits = models.ManyToManyField('orgunits.Orgunit') def __str__(self): return self.name Admin: from django.contrib import admin from deviations.forms import MyForm from deviations.models import Deviation @admin.register(Deviation) class DeviationAdmin(admin.ModelAdmin): form = MyForm Form: from django.forms import ModelForm, widgets from mptt.forms import TreeNodeMultipleChoiceField from orgunits.models import Orgunit class MyForm(ModelForm): orgunits = TreeNodeMultipleChoiceField(queryset=Orgunit.objects.all(), widget=widgets.SelectMultiple()) class Meta: model = Orgunit fields = '__all__' -
Django Serialiser get sibling records
In Django DRF, I am trying to work out I can return objects siblings. For instance, I have record B, can i return records A and B also? I can then use these to cycle blog posts for example with previous and next article links. At the moment, i am getting the current object, and then calling the database again looking for record with same parent. I am thinking there might be more efficient way. -
hide table heading if all values in table are null
I have a model form that I am displaying in a table. The form has about 40 fields broken down into 6 different tables. I have setup an if statements to not display the table elements if the field is empty in the db. This works as expected the only issue is that if all the elements are hidden the table header is still displayed. How could I hide the table header if all if the elements in that particular table are hidden. <table class="post-table"> <tr> <th class="table-header" colspan="2"> <h3>Pool Details</h3> </th> </tr> <tbody> {% if post.pool_size != '' %} <tr> <td>pool size:</td> <td>{{ post.pool_size }}</td> </tr> {% endif %} {% if post.pool_style != '' %} <tr> <td>Pool Style:</td> <td>{{ post.pool_style }}</td> </tr> {% endif %} </tbody> </table> -
Verify if user has already submitted form in Django
class Attest(models.Model): CURRENT_STATUS = ( ('yes', 'Yes'), ('no', 'No') ) owner = models.ForeignKey(Profile, null=True, blank=True, on_delete=models.CASCADE) value =models.CharField(max_length=200, choices=CURRENT_STATUS, default="no") created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default =uuid.uuid4, unique=True, primary_key=True, editable=False) class AttestForm(ModelForm): class Meta: model = Attest fields =['value'] widgets = { 'value': forms.RadioSelect() } {% if request.user.profile.id in ..attesters %} <p>you have already submitted your reponse!</p> {% elif request.user.is_authenticated %} <h3>1. Supplier code of conduct</h3> <p>1.1 The Supplier Code of Conduct <strong>(hereinafter referred to as the 'Code') </strong>defines minimum standards that our suppliers and anyone under their from django import forms from django.db import models import uuid from users.models import Profile # Create your models here. class Attest(models.Model): CURRENT_STATUS = ( ('yes', 'Yes'), ('no', 'No') ) owner = models.ForeignKey(Profile, null=True, blank=True, on_delete=models.CASCADE) value =models.CharField(max_length=200, choices=CURRENT_STATUS, default="no") created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default =uuid.uuid4, unique=True, primary_key=True, editable=False) class Meta: unique_together = [['owner']] def __str__(self): return self.value @property def attesters(self): queryset = self.attest_set.all().values_list('owner__id', flat=True) return queryset {% if request.user.profile.id in ..attesters %} I am unable to construct this statement well because im not sure the property im using is right. @property def attesters(self): Would be glad if someone could explain it better to me. >>> profile = Profile.objects.get(username="ichinexx@xxxxx.com") >>> print(profile) ichinexx@xxxxx.com" … -
Dgango( version 2.1.1) Admin panel change after upgrade to Django( version 3.2)
What did you do? Ans - I have upgrade Django(version 2.1.1) from Django(version 3.2) on Ubuntu 18.04 server What did you expect to happen? Ans - I was expecting a same admin panel but got different admin panel. As you can see in screenshot OS: Ubuntu 18.04.4 LTS (GNU/Linux 5.4.0-1048-aws x86_64) enter image description here Python: Python 3.6.9 (default, Jan 26 2021, 15:33:00) -
How to get the field of the model in Django in templates without ModelForm?
How to have an access to the field of our model without using the ModelForm object in Django ? forms.py class ChoiceAppointmentForm(forms.Form): appointment = forms.ModelChoiceField( queryset=None, widget=forms.RadioSelect) conference_method = forms.ChoiceField(choices=METHOD_CHOICES) conference_details = forms.CharField(required=False) conference_secret_code = forms.CharField(required=False) def __init__(self, *args, **kwargs): appointments = kwargs.pop('appointments') super().__init__(*args, **kwargs) self.fields['appointment'].queryset = appointments models.py class Appointment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, null = True, on_delete = models.CASCADE) student = models.ForeignKey(Student, null=True, blank = True, on_delete=models.CASCADE) is_confirmed = models.BooleanField(default = False) date = models.DateField(null = True) choice_appointment.html <div class="fieldWrapper"> {{ form.appointment.errors }} {{ form.appointment.date }} {{ form.appointment }} </div> But It does not display the date of the appointment. I can only access the appointment object but not the date, the student, etc. How can I do ? -
Can't get CSRF token from Django REST Framework response
The problem is that the server responds with a header set-cookie with a csrftoken, but it is not displayed in the storage. The client lies at the address: https://quiz-client-app.herokuapp.com The server is located at: https://quiz-server-app.herokuapp.com Also, it is not possible to access the cookie using JS getCookie.js const csrfTokenHeader = () => { let csrftoken = null return () => { if (document.cookie && document.cookie !== '' && !csrftoken) { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); if (cookie.substring(0, 'csrftoken'.length + 1) === ('csrftoken' + '=')) { csrftoken = decodeURIComponent(cookie.substring('csrftoken'.length + 1)); break; } } } return { 'X-CSRFToken': csrftoken } } } How can I access the cookie? Here is server CSRF settings and example of view: settings.py ALLOWED_HOSTS = ['quiz-client-app.herokuapp.com'] # On production # CSRF CSRF_COOKIE_SAMESITE = "None" CSRF_COOKIE_HTTPONLY = False CSRF_COOKIE_SECURE = True CSRF_TRUSTED_ORIGINS = ['quiz-client-app.herokuapp.com'] CSRF_COOKIE_DOMAIN = "quiz-server-app.herokuapp.com" # SESSION SESSION_COOKIE_SAMESITE = "None" SESSION_COOKIE_HTTPONLY = False # CORS CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_HEADERS = [ "content-type", "x-csrftoken" ] CORS_ALLOW_METHODS = [ "OPTIONS", "GET", "POST", "PUT", "DELETE" ] CORS_ALLOWED_ORIGINS = [ 'https://quiz-client-app.herokuapp.com' ] views.py @method_decorator(ensure_csrf_cookie, name='post') class LoginView(APIView): def post(self, request): ... return Response() -
How to check two time period for overlap in django?
For e.g., I have two time periods 02:00:00 - 03:00:00 now I want to check that new incoming start time and end time does not fall between this range. 01:00:00 to 02:00:00 and 03:00:00 to 04:00:00 should be acceptable. -
django rest fraemwork. Save extendet user data to db
I try implement regestration endpoint fow user with additional attributes like phone_number and full_name. I implement logick for saving user data, which come from request, bit i xan't unserstand how i can save profile data, like phone_number and full_name. I have user model: class User(AbstractUser): email = models.EmailField(_('email address'), unique=True) is_verified = models.BooleanField(_('is verified by admin'), default=False) EMAIL_FIELD = 'email' USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = UserManager() def __str__(self): return self.email def save(self, *args, **kwargs): if not self.username: self.set_username() super().save(*args, **kwargs) def email_user(self, subject, message, from_email=None, **kwargs): """Send an email to this user.""" send_mail(subject, message, from_email, [self.email], **kwargs) def set_username(self): pass And profile model: class Profile(TimeStampedModel): STATUS = Choices( ("inactive", _("inactive")), ("active", _("active")), ("banned", _("banned")) ) user = models.OneToOneField( User, verbose_name=_('related user'), on_delete=models.CASCADE, related_name='profile', related_query_name='profile' ) description = models.TextField( _("description of user's profile"), blank=True, default='' ) status = StatusField( _("status of the user") ) birth_date = models.DateField( _("Date of birth"), validators=[ MinValueValidator( datetime.date(1910, 1, 1) ), MaxValueValidator( datetime.date.today ) ], null=True, blank=True ) avatar = models.OneToOneField( "files.Avatar", on_delete=models.SET_NULL, null=True, blank=True, related_name="profile" ) full_name = models.CharField( max_length=30, default='', blank=False ) phone_number_regex_validator = RegexValidator(regex=COMPILED_REGEXP) phone_number = models.CharField( max_length=16, default='', blank=False, validators=[phone_number_regex_validator] ) objects = ProfileQuerySet.as_manager() def __str__(self): return f"profile of … -
How to extend a Django form in template?
i have an html of base step0.html i extend it {% extends "step0.html" %} all it's good but only my Django form not extends how can I do this? -
drf_spectacular schema generation threw exception when using ./manage.py makemigrations
I get this error when I run ./manage.py makemigrations and I don't know what is causing it (no relevant logs). ERRORS: ?: (drf_spectacular.E001) Schema generation threw exception "relation "global_preferences" does not exist LINE 1: ..."preferences"."preferences" FROM "global_prefer... Django 3.2.4 DRF: 3.12 -
How to return an HttpResponse object instead of None
can you help me out through this problem?, I'm a beginner and trying to learn django..even tho i tried so many other ways but it just wont work out. i hope you can help me models.py from django.db import models from django.db.models.fields import CharField , IntegerField, EmailField class Member(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=50) email = models.EmailField() age = models.IntegerField() password = models.CharField(max_length=100,null=True) def __str__(self): return self.first_name + " " + self.last_name form.py from django.db.models import fields from django.forms import ModelForm from django import forms from .models import Member class MemberForm(forms.ModelForm): class Meta: model = Member fields = ["first_name", "last_name", "age", "email", "password"] views.py from django.shortcuts import render from .models import Member from .form import MemberForm # Create your views here. def join(request): if request.method == "POST": form = MemberForm(request.POST or None) if form.is_valid(): form.save() return render(request, "HTML/join.html",{}) else: form = MemberForm() return render(request, "HTML/base.html",{}) error The view myapp.views.join didn't return an HttpResponse object. It returned None instead.