Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 3: Setting user email to be unique, minimal viable solution
I'm writing a simple app, and I'm totally happy with Django User model, except that I want a user email to be unique and obligatory field. I have developed a solution, but I'm wondering if I'm missing something. a) If you think that something is missing in the solution below please let me know b) If you think that you have a better solution please share This is what I did Created a custom user model # customers/models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): email = models.EmailField(verbose_name='Email', unique=True, blank=False, null=False) EMAIL_FIELD = 'email' REQUIRED_FIELDS = ['email'] Added AUTH_USER_MODEL = 'customers.User' to settings.py Changed a reference to User model: User = get_user_model() Modified admin.py in order to be able to add users using Django admin. # customers/admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth import get_user_model User = get_user_model() class CustomUserAdmin(UserAdmin): list_display = ('username', 'email', 'is_staff') add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('username', 'email', 'password1', 'password2'), }), ) admin.site.register(User, CustomUserAdmin) -
Data from django form is not being posted in Postgressql Database despite getting 200 OK from the server
I am using Django version 3.0 to create a sign up application for various departments at my school. I have connected the form to a model and the model is stored in a postgressql database. After I start the server using python manage.py runserver and I complete the form and click save, the form refreshes and I get the OK HTTP Code 200 from the server accessed through the terminal, but when I query the postgressql database using pg Admin interface the data has not been stored. Can anyone see where I am going wrong? This process worked before, I'm not sure if the data is just being stored in another table. Please help out if you can. This is my base.html file: {% load static %} <!DOCTYPE html> <html> <head> <title>Signup Prototype</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"> <link href='//fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext' rel='stylesheet' type='text/css'> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script src="{% static 'js/jquery.js' %}"></script> <link rel="stylesheet" href="{% static 'css/bootstrap.css' %}"> <script src="{% static 'js/bootstrap.js' %}"></script> <link type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/themes/redmond/jquery-ui.css" rel="Stylesheet" /> <script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js"></script> <script type="text/javascript"> $(function(){ $("#id_date").datepicker(); }); </script> {{form.media}} </head> <body> <header class="page-header"> <div class="container"> <a href="{% url 'Engineering' %}" class="top-menu"> </a> <h1><a href="/">Signup </a></h1> </div> </header> <main class="content container"> … -
self.assertContains fails; Couldn't find *word* in response
I'm having difficulty completely rendering the template of TopicsPage. It's suppose to render sub_heading.html which extends listing.html (both templates reside in the same templates folder). The test passes the self.assertTemplateUsed() assertion. However an AssertionError is raised at the point of: self.assertContains(response, "Looking for more?") AssertionError: False is not true : Couldn't find 'Looking for more?' in response How can I get the sub_heading.html content to render for the test to pass when the template is being used already? test_views.py class TestTopicsPage__002(TestCase): '''Verify that a topic and associated information is displayed on the main page once the topic is created''' @classmethod def setUpTestData(cls): user = User.objects.create_user("TestUser") python_tag = Tag.objects.create(name="Python") js_tag = Tag.objects.create(name="JavaScript") content = { 'heading': "Test Title", 'text': "Mock text content", 'posted': datetime.datetime.now() } cls.topic = Topic(**content) cls.topic.author = user cls.topic.save() cls.topic.tags.add(python_tag, js_tag) def test_topics_main_page_rendered_topics(self): response = self.client.get( reverse("listing") ) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "topics/sub_listing.html") self.assertContains(response, "Looking for more?") views.py class AbstractListingPage(TemplateView): template_name = "topics/sub_listing.html" extra_content = { 'query_links': ['interesting', 'hot', 'week', 'month'] } def get_context_data(self): context = super().get_context_data() context['topics'] = Topic.objects.all() context['search_form'] = SearchForm() context['login_form'] = UserLoginForm return context def post(self, request): context = self.get_context_data() form = context['login_form'](data=request.POST) if form.is_valid(): resolver = resolve(request.path) login(request, form.get_user()) if resolver.namespace: url = f"{resolver.namespace}:{resolver.url_name}" … -
how we can delete an element from ManyToMany realtion in django models?
i create a models in django , with ManyToMany relation , and i have a problem : class KeyCat(models.Model): category = models.CharField(max_length=255) def __str__(self): return self.category class Keyword(models.Model): category = models.ManyToManyField(KeyCat) that create two table : "keycat", "keyword" and "keyword_category" i want to delete from "keywords_keyword_category" a row where id=1 -
how to change model fields value in CreateView
I currently have the following in my CreateView: class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ["title", "content", "quiet_tag", "camera_tag"] def form_valid(self, form): form.instance.author = self.request.user user = self.request.user.profile print("hello") # print(form.instance.title) <--- what I want to pass into user.participating_in # user.participating_in = Post(form.instance.title) <--- where I'm stuck print(user.participating_in) <--- returns nothing even though form.instance.title gives me the correct title return super().form_valid(form) In my models I have the following class Profile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) participating_in = models.ForeignKey(Post, on_delete=models.CASCADE, default=None) image = models.ImageField(default="default.jpg", upload_to="profile_pics") def __str__(self): return f"{ self.user }'s Profile" When the user is created they automatically get a profile and their participating_in field is set to null. When the user makes a post I want participating_in to be set to the title of the post they're making but I can't seem to figure out how to change the value for participating_in inside of PostCreateView. -
How to import stl file from s3 for numpy stl properties evaluation?
I have my django application running on localhost. STL files get uploaded to aws S3 and I need to evaulate their properties, but I cannot get past getting the right path for numpy stl stl_file = mesh.Mesh.from_file(unknown path) Any help much appreciated -
Django REST Framework Object of type PhoneNumber is not JSON serializable
So, I have this error. I use a third party package named PhoneNumber. Now when I want to serialize my data I get this error: Object of type PhoneNumber is not JSON serializable I can guess what the problem is, but not how to solve it :/ Has anyone had this/similar problem before? :) serializer.py from rest_framework import serializers from phonenumber_field.serializerfields import PhoneNumberField from user.models import Account class RegistrationSerializer(serializers.ModelSerializer): password2 = serializers.CharField(style={'input_type': 'password'}, write_only=True) # country = serializers.ChoiceField( # choices=['US', 'DE', 'FR', 'CH', 'AT', 'GB', 'SE', 'NO', 'FI', 'DK', 'IT', 'ES', 'PT'] # ) phone_number = PhoneNumberField() class Meta: model = Account fields = ['phone_number', 'username', 'first_name', 'country', 'email', 'password', 'password2'] extra_kwargs = { 'password': {'write_only': True}, } def save(self): account = Account( email = self.validated_data['email'], username = self.validated_data['username'], first_name = self.validated_data['first_name'], country = self.validated_data['country'], phone_number = self.validated_data['phone_number'], ) password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != password2: raise serializers.ValidationError({'password': 'Passwords must match.'}) account.set_password(password) account.save() return account views.py from rest_framework import status from rest_framework.response import Response from rest_framework.decorators import api_view from .serializers import RegistrationSerializer @api_view(['POST', ]) def registration_view(request): if request.method == 'POST': serializer = RegistrationSerializer(data=request.data) data = {} if serializer.is_valid(): account = serializer.save() data['response'] = 'successfully registered new user.' … -
Django authenticate username not working with USERNAME_FIELD
I'm making a login for my app, with a custom user model and form, using an e-mail as username field in the model, and asking for email and password during the login process. The problem is that no matches are found in the authenticate method in my view, so I can't log in my users. Here is the code: user model class usuarios(AbstractBaseUser): nombre = models.CharField(max_length=32, null=False) apellido = models.CharField(max_length=32, null=False) correo = models.EmailField(null=False, unique=True) password = models.CharField(max_length=200, null=False) fecha_nacimiento = models.DateField(null=False) USERNAME_FIELD = 'correo' objects = userManager() def __str__(self): return self.correo+' '+self.nombre+' '+self.apellido login form class loginForm(forms.Form): correo = forms.EmailField() password = forms.CharField( widget=forms.PasswordInput() ) class Meta: model = usuarios fields = ("correo","password") login view class usuario_login(FormView): template_name = "user/usuario_login.html" form_class = loginForm success_url = reverse_lazy('user:crear') def form_valid(self, form): usuario = authenticate( username=form.cleaned_data['correo'], password=form.cleaned_data['password'] ) if usuario is not None: login(self.request, usuario) else: return HttpResponseRedirect( reverse_lazy('user:login') ) return super(usuario_login, self).form_valid(form) As you can see, in the login view I try to authenticate username (that's the email) and password before doing the login. I appreciate any help and then you. -
Docker compose with nginx, django backend and react frontend
I have some problem with configuring nginx with docker-compose (as production) for django+react project. I have followed the guide to configure django+postgres, nginx and gunicorn: Dockerizing Django with Postgres, Gunicorn, and Nginx Finally my backend is working correctly with staticfiles and gunicorn. I have some problem with configuring my frontend part. I was trying to follow Docker-Compose for Django and React with Nginx reverse-proxy and Let's encrypt certificate but still have some problems with my frontend. At this moment I have access to backend app using address 127.0.0.1:1337 (api/, admin/, auth/). So as I understand I should set up the frontend to be available using 127.0.0.1:1337, and the backend e.g. 127.0.0.1:1337/backend/. I'm not familiar with these topics at all. Maybe is there someone who would like to give me some tips? I have added my current configuration below: Docker-compose: version: '3.7' services: db: image: postgres:13.2 volumes: - ./postgres_data:/var/lib/postgresql/data/ env_file: - ./.env.prod.db django_bot_backend: build: context: ./backend/django_dashboard dockerfile: Dockerfile.prod command: gunicorn django_dashboard.wsgi:application --bind 0.0.0.0:8000 expose: - 8000 depends_on: - db env_file: - ./.env.prod restart: "on-failure" volumes: - static_volume:/home/backend/django_dashboard/django_bot_backend/staticfiles django_bot_frontend: image: frontend build: context: ./frontend/dashboard dockerfile: Dockerfile.prod volumes: - ./frontend/dashboard:/usr/src/frontend/dashboard expose: - 3000 env_file: - '.env.front' nginx: build: ./nginx ports: - 1337:80 depends_on: … -
how to handle relation fields in django_rest_framework
so i have product model and a ProductImage model, and they have a 1 to 1 relation, i want to have it so when i wanna add a product i can upload the image right their and not in a different page or something and i don't know how to go about it. class Product(models.Model): name = models.CharField(verbose_name=_("product Name"), help_text=_("Required"), max_length = 255, blank=False) category = models.ForeignKey(Category, on_delete=models.RESTRICT) class ProductImage(models.Model): product = models.ForeignKey('products.Product', on_delete=models.CASCADE, related_name="product_image") image = models.ImageField( verbose_name=_("image"), help_text=_("upload a product image"), upload_to="api/images", blank=False, null=True, max_length=None, ) and my very basic serializer from rest_framework import serializers from products.models import Product class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ('id', 'name', 'category', 'description', 'slug', 'regular_price', 'discount_price', 'stockAmount') I've tried to import the productimage model and just add it to the field but it gives me a drop-down to choose from previously uploaded image and wont let me upload one right their. -
django inlineformset_factory does not validate empty extra forms
So, I don't understand why my inlineformset is not being validated when the extra forms are empty. I mean, I do need the user to enter values for both 'host_type' and 'host_score', but Django throws an error asking for values in the fields for the empty extra forms! Isn't it supposed to ignore forms that have not been changed? Here is the code: class AddressPropertyForm(ModelForm): ''' Creates a modelform that contains fields from both property and address models ''' error_css_class = 'error' building_number = forms.IntegerField(min_value = 0, required = True) street_direction = forms.ChoiceField(choices = ( ('', '----'), ('E', 'East'), ('W', 'West'), ('N', 'North'), ('S', 'South'),), required = True) street_name = forms.CharField(max_length = 30) street_type = forms.ChoiceField(choices = STREET_TYPES) class Meta: model = Property fields = ['host_type', 'host_score'] field_order = ['building_number', 'street_direction', 'street_name', 'street_type', 'host_type', 'host_score' ] def __init__(self, *args, **kwargs): super(AddressPropertyForm, self).__init__(*args, **kwargs) self.fields['building_number'].widget.attrs.update({'placeholder': '(Optional)'}) self.fields['building_number'].required = False self.fields['street_direction'].widget.attrs.update({'placeholder': '(Optional)'}) self.fields['street_direction'].required = False self.fields['street_name'].widget.attrs.update({'placeholder': '(Optional)'}) self.fields['street_name'].required = False self.fields['street_type'].widget.attrs.update({'placeholder': '(Optional)'}) self.fields['street_type'].required = False self.fields['host_type'].required = True self.fields['host_score'].required = True def clean(self, *args, **kwargs): cleaned_data = super(AddressPropertyForm, self).clean(*args, **kwargs) return cleaned_data class BaseAddressPropertyInlineFormSet(BaseInlineFormSet): def __init__(self, *args, **kwargs): super(BaseAddressPropertyInlineFormSet, self).__init__(*args, **kwargs) def clean(self, *args, **kwargs): cleaned_data = super(BaseAddressPropertyInlineFormSet, self).clean(*args, **kwargs) assert False … -
'ImageField' object has no attribute '_committed'
I'm trying to add data to a model class from the django admin panel. After clicking the "Save" button, I get this error: AttributeError at /admin/filmapp/movies/add/ 'ImageField' object has no attribute '_committed' I tried this solution, but unfortunately it doesn't work for me: override save method - 'ImageFile' object has no attribute '_committed' This is my code: admin.py from django.contrib import admin from .models import Movies admin.site.register(Movies) models.py class Movies(models.Model): title = models.CharField(max_length=50, null=True, blank=False) year = models.PositiveIntegerField(null=True, blank=False) description = models.TextField(null=True, blank=False) rating = models.FloatField(null=True, blank=True) img = models.ImageField(upload_to='static/img') url = models.CharField(max_length=1000, null=True, blank=False) img_video = models.ImageField(upload_to='static/img/imgvideo', default=img) This is full Traceback: https://codeshare.io/21wAD3 -
Django how to set or update data from filtered data
my code like this def change_order_status(request): user = request.user teacher = Teacher.object.get(id = user.teacher.id) today = datetime.now() today = today + timedelta(minutes=30) today = today.strftime("%Y-%m-%d %H:%M") test = [] if request.method=="POST": teacher_time = Student_Time.object.filter(teacher_id = teacher.id, paid=0, status=2) for tt in teacher_time: if tt.order_date < today: **tt.update(paid=1)** return HttpResponseRedirect(reverse('teacherStatistic')) return HttpResponseRedirect(reverse('teacherStatistic')) i want set or update that tt.paid to 1(default 0). How can i do it using for loop with if. tt.paid = 1 or tt.update(paid = 1) both are not working pls help me; -
How to access self in Model validator django
I have a Model in django with a field: child = models.ForeignKey(Child, on_delete=models.SET_NULL) def validate_child(child): if child.parent = self: RAISE ERR HERE As you can see, I want to access self in the validate_child method. How can I do this? Thanks. -
Django - Saving function value to every model instance
So I have this model: class Profile(models.Model): ip = "placeholder" user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile") image = models.ImageField(default='default.jpg', upload_to='profile_pics') location = models.CharField(max_length=100, default=ip) def __str__(self): return f'{self.user.username} Profile' and the following function: def get_ip_address(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return ip ip = get_ip_address(request) What what I need to do to make it so that every time an instance of the model is created, the function runs and saves the returned value in the field called location. I assume that I have to put the function in the views.py file but how do I link it to the model instances. -
Trying to set user field in the nested form of a django nested inline formset - fails
I followed this: https://www.yergler.net/2009/09/27/nested-formsets-with-django/ and this: django inline formsets with a complex model for the nested form and overall my code works great. class Account(models.Model): user_username = models.ForeignKey(User, on_delete=models.CASCADE) account_name = models.CharField(max_length=30) class Classification(models.Model): user_username=models.ForeignKey(User, on_delete=models.CASCADE) data_id=models.ForeignKey(ImportData, on_delete=models.CASCADE) class ImportData(models.Model): user_username = models.ForeignKey(User, on_delete=models.CASCADE) data_id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) ClassificationFormset = inlineformset_factory(ImportData, Classification, exclude=('user_username',), extra=1) # below is just what came from the nested formset links above: pasted here for easy reference. class BaseNestedTransactionFormset(BaseInlineFormSet): def add_fields(self, form, index): # allow the super class to create the fields as usual super(BaseNestedTransactionFormset, self).add_fields(form, index) try: instance = self.get_queryset()[index] pk_value = instance.pk except IndexError: instance=None pk_value = hash(form.prefix) transaction_data = None if (self.data): transaction_data = self.data; # store the formset in the .nested property form.nested = [ CategoryFormset(data=transaction_data, instance = instance, prefix = 'CAT_%s' % pk_value)] def is_valid(self): result = super(BaseNestedTransactionFormset, self).is_valid() for form in self.forms: if hasattr(form, 'nested'): for n in form.nested: # make sure each nested formset is valid as well result = result and n.is_valid() return result def save_new(self, form, commit=True): """Saves and returns a new model instance for the given form.""" instance = super(BaseNestedTransactionFormset, self).save_new(form, commit=commit) # update the form’s instance reference form.instance = instance # update the … -
Django importing FileNotFoundError: [Errno 2] No such file or directory:
I tried to import the folder 'covid_data' with files, so that I can use functions from the file 'coviddata'(which reads csv files from its directory), but I've been stuck for a while here. It yields lines of errors with FileNotFoundError: [Errno 2] No such file or directory: 'restrictions.csv'. I tried joining directories, but to no avail. Tried creating a separate 'static' folder with csv files and moving coviddata.py to plots (the same directory as views.py) with then restrictions=pd.read_csv('static/restrictions.csv'), which also didn't work. screenshot -
Django 3rd party login duplicate email
I set up my django application to be able to sign in with google and facebook 3rd party applications. However, whenever I already have an account that signs up with a gmail account that already exists, I get a weird signup page that looks like this: Menu: Sign In Sign Up Sign Up You are about to use your Google account to login to example.com. As a final step, please complete the following form: Username: testuser An account already exists with this e-mail address. Please sign in to that account first, then connect your Google account. E-mail (optional): email@test.com Sign Up » Is there a way to fix this so it can ask the user for a different email instead of breaking like this? When the user hasn't been registered before through the application, this problem does not occur. -
How to filter a ManyToMany field from django template?
I have a model named Universities in which there is a ManyToMany field named bookmarks associated with User model. In template file, I have looped through all the universities {% for university in universities %} and I am trying to show a bookmark icon based on the logged in user has bookmarked that specific university or not. However, it seems like I can not filter the query in template directly. How do I do that? -
When I set CSRF_COOKIE_HTTPONLY = True then 403 (Forbidden) error occurred
In my settings.py: ... CSRF_COOKIE_HTTPONLY = True SESSION_COOKIE_HTTPONLY = True CSRF_COOKIE_SECURE = False CORS_ALLOW_CREDENTIALS = True authenticate.py: from rest_framework_simplejwt.authentication import JWTAuthentication from django.conf import settings from rest_framework import exceptions from rest_framework.authentication import CSRFCheck def enforce_csrf(request): """ Enforce CSRF validation. """ check = CSRFCheck() # populates request.META['CSRF_COOKIE'], which is used in process_view() check.process_request(request) reason = check.process_view(request, None, (), {}) print(reason) if reason: # CSRF failed, bail with explicit error message raise exceptions.PermissionDenied('CSRF Failed: %s' % reason) class CustomAuthentication(JWTAuthentication): def authenticate(self, request): ..... validated_token = self.get_validated_token(raw_token) enforce_csrf(request) return self.get_user(validated_token),validated_token Error: CSRF token missing or incorrect. Forbidden: /photos/photo_support/ when I set CSRF_COOKIE_HTTPONLY = False then all work very well. What's the reason when I set CSRF_COOKIE_HTTPONLY = True then they me throw 403 Forbidden error. My Frontend is ReactJS. TestMe.js: Axios.defaults.withCredentials = true Axios.defaults.xsrfCookieName = 'csrftoken'; Axios.defaults.xsrfHeaderName = 'X-CSRFToken'; const TestMe = () => { .... const payHandle = () => { Axios.post('http://localhost:8000/photos/photo_support/', { data:data }) .then(res => { console.log(res.data) }) .catch(error => alert(error.message)) } ... -
Generate Refer Code From Username in Django?
I have unique username in User model. I want to generate refer code based on username. My Member model is as. I want refer code to be success if correct username is set but the refer code is set to be in char field. how can I do that? class User(AbstractBaseUser) username = model.CharField(unique = True, max_length = 70) class Member(BaseModel): user = models.ForeignKey(User, on_delete=models.CASCADE) refer_code = models.CharField(max_length=20) class Meta: default_permissions = () def clean(self): if not self.user.is_member: raise DjangoValidationError({'user': _('User must member')}) if not self.refer_code not in self.user.username: # dummy code ' -
How to get field from django model by name from list
I got model like: class mymodel(models.Model): val1 = models.FloatField(default=0) val2 = models.FloatField(default=0) ...and more var with other names name = models.CharField(max_length=200) url = models.CharField(max_length=200) I need change values in many models but not all fields (only from list) list= ['val1', 'val2' .... 'val15'] for entry in list: mymodel.entry = data[entry] How can i do it? i tried {entry}, entry, [entry] -
Django allauth: Custom SignUp form doesn't save all of the fields
I have made a custom signup form but it seems that my app doesn't try to save all the data from a post request. SQL query that is executed is clearly missing few fields. Do you have any idea what's happening? Should I make a custom view for signup also? Error django.db.utils.IntegrityError: (1048, "Column 'birth_date' cannot be null") Post request body csrfmiddlewaretoken 'S6s1kocaG5nKQyeKfJd4cTD6do3Dv2VjrElQ4DYESybICDQtueQG5TkqQf5HgP7W' username 'User123' email 'mrjst1995@gmail.com' first_name 'John' last_name 'Doe' city '2' address 'blahblahblah' phone '005006007' birth_date '2006-06-09' password1 'somerandpass' password2 'somerandpass' Executed query db <_mysql.connection open to 'localhost' at 02154B30> q (b'INSERT INTO `users_user` (`email`, `username`, `password`, `date_joined`, `l' b'ast_login`, `is_admin`, `is_active`, `is_staff`, `is_superuser`, `first_name' b"`, `last_name`, `phone`, `city_id`, `address`, `birth_date`) VALUES ('mrjst1" b"995@gmail.com', 'User123', 'pbkdf2_sha256$216000$6H02ElhAxQ3y$y56l29/sTf0Oyy" b"+sa39MX2cgLlgvPzsA+K5HWOb/NjU=', '2021-03-21 18:05:49.199287', '2021-03-21 1" b"8:05:49.199287', 0, 1, 0, 0, 'John', 'Doe', '', NULL, '', NULL)") self <MySQLdb.cursors.Cursor object at 0x05194BB0> models.py from django.db import models from django.contrib.auth import get_user_model from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.contrib.auth.hashers import make_password class City(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=20,null=False) def __str__(self): return self.name class UserManager(BaseUserManager): def create_user(self, email, username, first_name, last_name, city, address,phone, birth_date, password=None): if not email: raise ValueError('Korisnik mora imati email adresu') if not username: raise ValueError('Korisnik mora imati korisničko ime') if … -
Django INNER JOIN and WHERE
Let me introduce you with the structure. Let's say I have 3 models defined as: class User(AbastractUser): some fields... class UserProfile(Model): gender = models.CharField(max_length=10, choices=GENDER_CHOICES, default='unknown', verbose_name=_('Gender')) ... user = models.OneToOneField(User, related_name='userprofile', on_delete=CASCADE) preferences = models.OneToOneField( Preferences, related_name='user_profile', null=True, on_delete=CASCADE ) class Preferences(TimestampedModel): some fields... method = models.CharField( max_length=10, null=True, blank=True, default=None, choices=[(x, x) for x in methods] ) I would like to write this query with django models, what would be the way? Query: SELECT * from users as u INNER JOIN users_profile as up ON u.id as up.user_id INNER JOIN preferences as p ON p.id as up.preference_id WHERE p.method = 'TEST' Any suggestions, what would be the cleanest way, also most optimised? -
How use Json variable in Django Template Tags?
How use json variable in Django template tags in srcipts? I cannot use variables in javascript strings when I use django template tags and my own custom tags like: {% if ${comment}|comment_like_ip:ip %} $(document).ready(function(){ const comments = document.getElementById('comments') const loadBtn = document.getElementById('load-btn') const loadBox = document.getElementById('loadBox') let visible = 3 vis = { num : visible, } let handleGetData = () => { $.ajax({ type: 'GET', data: vis, url: "{% url 'load-comments' video.slug %}", success: function(response) { max_size = response.max const data = response.data console.log(data) data.map(comment=>{ console.log(comment.id) if(comment.is_child) { comments.innerHTML += `<div class="comment"> ${comment.nickname} | ${comment.timestamp} <div style="background-color: black; width: 300px;"> <p>Ответ: ${comment.parent_name}</p> <p>Комментарий: "${comment.parent_text}"</p> </div> <p>${comment.text}</p> <p><a href="#" class="like-comment" data-id="${comment.id}"> {% if ${comment}|comment_like_ip:ip %} <i class="fas fa-heart" style="color: #BE0E61;"></i> {% else %} <i class="far fa-heart"></i> {% endif %} <span>${comment.likes}</span></a></p> <button style="background-color: black;" class="reply" data-id="${comment.id}" data-parent=${comment.get_parent}>Ответить</button> <form action="" method="POST" class="comment-form" id="form-${comment.id}" style="display:none;"> <textarea type="text" name="comment-text"> </textarea> <br> <input type="submit" class="btn submit-reply" data-id="${comment.id}" data-submit-reply="${comment.get_parent}" value="Отправить"/> </form> </div>` } else { comments.innerHTML += `<div class="comment"> ${comment.nickname} | ${comment.timestamp} <p>${comment.text}</p> <p><a href="#" class="like-comment" data-id="${comment.id}"> {% if True %} <i class="fas fa-heart" style="color: #BE0E61;"></i> {% else %} <i class="far fa-heart"></i> {% endif %} <span>${comment.likes}</span></a></p> <button style="background-color: black;" class="reply" data-id="${comment.id}" data-parent=${comment.get_parent}>Ответить</button> <form action="" method="POST" class="comment-form" …