Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django child model with OneToOne parent does not inherit parent's fields?
I have a parent classs Dish and a child Pizza that inherits from Dish. They have a 1to1 relationship and I wrote them as follows: class Dish(models.Model): PIZZA = 'PIZZA' SUB = 'SUB' PASTASALAD = 'PASTASALAD' PLATTER = 'PLATTER' TYPE_CHOICES = ( (PIZZA, 'Pizza'), (SUB, 'Sub'), (PASTASALAD, 'PastaSalad'), (PLATTER, 'Platter') ) name = models.CharField(max_length=64, blank=True) type = models.CharField(max_length=64, choices=TYPE_CHOICES, blank=True) size = models.CharField(max_length=1, choices=SIZE_CHOICES, default=SMALL, blank=True) price = models.DecimalField(max_digits=6, decimal_places=2, default=None) def __str__(self): return f"{self.name} {self.size} - Price: ${self.price}" class Pizza(Dish): dish = models.OneToOneField(Dish, on_delete=models.CASCADE, related_name="dish_id_pizza", parent_link=True) REGULAR = 'REGULAR' SICILIAN = 'SICILIAN' STYLE_CHOICES = ( (REGULAR, 'Regular'), (SICILIAN, 'Sicilian'),) style = models.CharField(max_length=7, choices=STYLE_CHOICES, default=REGULAR) topping_count = models.IntegerField(default=0, validators=[MaxValueValidator(5), MinValueValidator(0)]) def __str__(self): return f"{self.size} {self.style} pizza with {self.topping_count} toppings: ${self.price}" Now I have a Dish object with ID=17 and a price of 21.95, type=Pizza, size=Small, type=Regular. I now try to create the corresponding Pizza object as follows: >>> parent=Dish.objects.get(pk=17) >>> new_17_pizza = Pizza(dish=parent, topping_count=2, style="Regular") >>> new_17_pizza.save() I would assume that all Dish fields and values are inherited, i.e. I don't have to repeat them, but I get: sqlite3.IntegrityError: NOT NULL constraint failed: orders_dish.price Why is that? I know I am not allowing blank=True for the price in Dish, but … -
Receiving "'hmset' with mapping of length 0" error
I want to store my session data on redis dataset. I have set SESSION_ENGINE = 'redis' in settings.py. Code for redis.py #redis.py from django.contrib.sessions.backends.base import SessionBase from django.utils.functional import cached_property from redis import Redis class SessionStore(SessionBase): @cached_property def _connection(self): return Redis( host='127.0.0.1', port='6379', db=0, decode_responses=True ) def load(self): return self._connection.hgetall(self.session_key) def exists(self, session_key): return self._connection.exists(session_key) def create(self): # Creates a new session in the database. self._session_key = self._get_new_session_key() self.save(must_create=True) self.modified = True def save(self, must_create=False): # Saves the session data. If `must_create` is True, # creates a new session object. Otherwise, only updates # an existing object and doesn't create one. if self.session_key is None: return self.create() data = self._get_session(no_load=must_create) session_key = self._get_or_create_session_key() self._connection.hmset(session_key, data) self._connection.expire(session_key, self.get_expiry_age()) def delete(self, session_key=None): # Deletes the session data under the session key. if session_key is None: if self.session_key is None: return session_key = self.session_key self._connection.delete(session_key) @classmethod def clear_expired(cls): # There is no need to remove expired sessions by hand # because Redis can do it automatically when # the session has expired. # We set expiration time in `save` method. pass I am receiving 'hmset' with mapping of length 0 error on accessing http://localhost:8000/admin in django. After removing SESSION_ENGINE='redis' I am not receiving … -
Is there a calendar module for Django in Bootstrap?
So I'm newbie in programming world. I've been looking for a calendar in my webpage, so that users can dynamically input their schedules on it. However I'm having hard time finding a fine module. There isn't much in pypi.org, lots of modules are quite outdated. Do you have any recommendations? Thanks a lot :) -
Customizing default auth form in Django for html template
I'm trying to use the CSS from an HTML template I downloaded online to work in my default Django login form, and I gather that to imbue {{ form.username }} with any styles, you must create a custom LoginView in forms.py and modify that as if it were any other form using attrs={}. I have already done what was suggested in this question before anyone says this is a duplicate. class UserLoginForm(AuthenticationForm): def __init__(self, *args, **kwargs): super(UserLoginForm, self).__init__(*args, **kwargs) username = forms.CharField(widget=forms.TextInput( attrs={ 'class': 'input100', } )) password = forms.CharField(widget=forms.PasswordInput( attrs={ 'class': 'input100', } )) The name of the CSS style I'm trying to apply to the username (and password) text fields is "input100" but the username and password don't seem to be affected by anything I'm putting in forms.py. In fact, even if I take out the username and password fields in the above file, it still works the same, so clearly changes to forms.py aren't reaching the template (but the template is using UserLoginForm fine as if I take the whole thing out it crashes). change to urls.py: urlpatterns = [ path('', subsmems, name='subsmems'), path('accounts/', include('django.contrib.auth.urls')), path('signup', signup, name='signup'), path( 'login/', views.LoginView.as_view( authentication_form=UserLoginForm, ), name='login' ) ] html … -
Django payment gateway clone
I want to create payment gateway clone like paypal ,razorpay in django but there is no reference about this in internet.How should i create models?.Any clone for payment gateway but not integration in django?.Please help Sir/Mam. -
Using the attribute value from IntegerField in another object attribute
So I am trying to learn django, and I am trying to enable image resizing from an image uploaded which is then assigned to an object via admin. I am using the django-stdimage lib. The idea is an instance as follows can be summoned: class Website_Post(models.Model): title = models.TextField(default='Enter title') intro = models.TextField(default='Enter post') image_width = models.IntegerField(validators=[MaxValueValidator(1000), MinValueValidator(0)], default=300) image_height = models.IntegerField(validators=[MaxValueValidator(1000), MinValueValidator(0)], default=300) cover = StdImageField(upload_to='images/', variations={'full': {'width': image_width, 'height': image_height}},null=True) def __str__(self): return self.title And then in /admin the image proportions can be defined, with a max value and a min value, which is then applied to the selected image. My reasoning for this is that the StdImageField variations are not easily accessible once the object has been created, so this way they can adjusted, at least from the backend. However when running this code, the object cannot be created, as the following error is given: TypeError: '>' not supported between instances of 'int' and 'IntegerField' with the error at this point: @staticmethod def is_smaller(img, variation): return img.size[0] > variation['width'] \ # <--- error in this line or img.size[1] > variation['height'] which to me indicates that the IntegerField value does not appear as an integer when used in … -
Bitbucket pipeline mssql database set port
I have a bitbucket pipeline that must execute django unittests. Therefore, I need a test database which should be a SQL SERVER datbase. The pipeline looks like this: # This is a sample build configuration for Python. # Check our guides at https://confluence.atlassian.com/x/x4UWN for more examples. # Only use spaces to indent your .yml configuration. # ----- # You can specify a custom docker image from Docker Hub as your build environment. image: python:3.7.3 pipelines: branches: master: - step: name: Setup sql image: fabiang/sqlcmd script: - sqlcmd -S localhost -U sa -P $DB_PASSWORD services: - sqlserver - step: name: Run tests caches: - pip script: # Modify the commands below to build your repository. - python3 -m venv my_env - source my_env/bin/activate - apt-get update && apt-get install - pip3 install -r req-dev.txt - python3 manage.py test - step: name: Linter script: # Modify the commands below to build your repository. - pip3 install flake8 - flake8 --exclude=__init__.py migrations/ definitions: services: sqlserver: image: mcr.microsoft.com/mssql/server:2017-latest variables: ACCEPT_EULA: Y SA_PASSWORD: $DB_PASSWORD And everytime when I run the pipeline I get: Sqlcmd: Error: Microsoft ODBC Driver 17 for SQL Server : Login timeout expired. Sqlcmd: Error: Microsoft ODBC Driver 17 for SQL Server … -
correct sending emails with django
Hi i have a smal question i've got user register form that sets new users to inactive and send me(admin) mail that they are awaiting for approval everything works fine but email i recieve looks like it comes from me to me it doesn't show me email i provide in the form i can fix it by movig "form.email" to a mail body place and then it works but i want this to be displayed how it should be. i'. sending those emails from my localhost to my gmail account: Function def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): user = form.save() user.is_active = False user.save() form.username = form.cleaned_data['username'] form.email = form.cleaned_data['email'] try: send_mail(f'New User requests for approval to log in', f'You have a new user and he is awaiting for approve'+'\n\n'+'User name: '+ form.username, form.email, [EMAIL_HOST_USER]) except BadHeaderError: return HttpResponse('Invalid header found.') username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You will be able to log in after Admin approval') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form, 'register': "active" }) -
django Multiple newtwork request to api cause unique violation error
So i have an API that takes a keyword and runs some logic, then inserts the data into Keyword table. The keyword model is: class Keyword(BaseModel): text = models.CharField(max_length=500, unique=True) key_id = models.CharField(max_length=20, null=True, blank=True) def __str__(self): return my_unicode(self.text) Now due to some bug in my frontend js code a api request was getting sent two times on a button click(not a major issue). But in the backend during the processing of the keyword following code runs which was creating UniqueViolation error: def get_data_for_keyword(key, region_id, language_id): # key is the keyword text that we need to save into db which is coming from network request # Some code keyword = Keyword.objects.filter(text__iexact=key) if keyword.exists(): keyword = keyword[0] # some code else: keyword = Keyword(text=key) keyword.save() # some code Scenrio: Two request come with the same keyword(due to the js bug). Expected behaviour: Both request check the existence of that keyword in DB, the one that runs first doesn't find it in DB creates it and the other one finds it in DB and further processing happens. But whats happening is somehow both request are getting executed simultaneously and both when filtering are not finding that keyword and both are trying to … -
Reformat request data DRF to create multiple model instances
I want to create three model instances using only one serializer, from one POST request. I need to update order, order_info, order_contact The data I receive looks like this: { "longitude": "67.929655", "latitude": "34.263974", "amount_from_client": "2600.00", "address": "New York", "datetime_client": "2019-08-01 16:31:00", "city": "New York", "partner_name": "Partner", "text": "", "client_name": "Qwerty", "client_order_code": 2174206, "datetime_partner": "2019-08-01 16:31:00", "amount_to_partner": "2000.00", "delivery_address_comment": "", "created": "2019-08-01 16:31:00", "client_phone": "74789", "partner_phone": "9988", "client_id": 6, } and here is my serializers: class OrderDetailsCreateSerializer(serializers.ModelSerializer): order_info = OrderInfoSerializer(many=False) order_contact = OrderContactSerializer(many=False) client_id = serializers.IntegerField(write_only=True) class Meta: model = Order fields: Tuple = ( 'address', 'amount_from_client', 'amount_to_partner', 'client_order_code', 'text', 'order_info', 'order_contact', 'client_id', ) def create(self, validated_data): client = Client.objects.get(id=validated_data.pop('client_id')) order_info = validated_data.pop('order_info', None) order_contact = validated_data.pop('order_contact', None) order = Order.objects.create(**validated_data) OrderInfo.objects.create(**order_info, order=order, client=client) OrderContact.objects.create(**order_contact, order=order) return order class OrderInfoSerializer(serializers.ModelSerializer): class Meta: model = OrderInfo fields: Tuple = ( 'datetime_client', 'datetime_partner', 'created', 'client', ) class OrderContactSerializer(serializers.ModelSerializer): class Meta: model = OrderContact fields: Tuple = ( 'client_name', 'client_phone', 'partner_name', 'partner_phone', ) In order to send data to OrderDetailsCreateSerializer my data format should be like this: { "longitude": "67.929655", "latitude": "34.263974", "amount_from_client": "2600.00", "address": "New York", "city": "New York", "text": "", "client_order_code": 2174206, "amount_to_partner": "2000.00", "delivery_address_comment": "", "client_id": 6, "order_info": { "datetime_client": … -
How to access a models attributes in Django
I'm trying to show users the product variations that they have selected. While the code is working and saving the variation in the database, I am not being able to show them on my html page. This is what I've tried: My models.py: class Variation(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE, null=True, blank=True) variation_type = models.CharField(max_length=120, choices=VAR_TYPES, default='Size') title = models.CharField(max_length=120, null=True, blank=True) price = models.FloatField(null=True, blank=True) is_available = models.BooleanField(default=True) objects = VariationManager() class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) item = models.ForeignKey(Item, on_delete=models.CASCADE) variation = models.ManyToManyField(Variation) quantity = models.IntegerField(default=1) ordered = models.BooleanField(default=False) My cart.html: {% for order_item in object.items.all %} <tbody> <tr> <th scope="row" class="border-0"> <div class="p-2"> <img src="{{ order_item.item.image_url }}" alt="" width="70" class="img-fluid rounded shadow-sm"> <div class="ml-3 d-inline-block align-middle"> <h5 class="mb-0"> <a href="{{ order_item.item.get_absolute_url }}" class="text-dark d-inline-block align-middle">{{ order_item.item.title }}</a> {% if order_item.variation.all %} <ul> {% for subitem in order_item.variation.all %} <li>{{ subitem.variation_type }} : {{ subitem.title }}</li> {% endfor %} </ul> {% endif %} </div> </div> </th> -
A problem with my ubuntu Linux text editor on the key word True and False
when i copy this default config of tinymce4 to text editor it shows no color change for the keyword True.TINYMCE_DEFAULT_CONFIG this is in black and rest all in rose color(default texteditor theme) but in sublime text of windows it shows a color different from all other parameters.for example in the below code ''' 'cleanup_on_startup': True, ''' i'm having True and clean_up_on_startup as same rose color..even reviewing the question in stackoverflow i'm getting a different color for true and false but not getting in my ubuntu linux text editor. ''' TINYMCE_DEFAULT_CONFIG = { 'height': 360, 'width': 1120, 'cleanup_on_startup': True, 'custom_undo_redo_levels': 20, 'selector': 'textarea', 'theme': 'modern', 'plugins': ''' textcolor save link image media preview codesample contextmenu table code lists fullscreen insertdatetime nonbreaking contextmenu directionality searchreplace wordcount visualblocks visualchars code fullscreen autolink lists charmap print hr anchor pagebreak ''', 'toolbar1': ''' fullscreen preview bold italic underline | fontselect, fontsizeselect | forecolor backcolor | alignleft alignright | aligncenter alignjustify | indent outdent | bullist numlist table | | link image media | codesample | ''', 'toolbar2': ''' visualblocks visualchars | charmap hr pagebreak nonbreaking anchor | code | ''', 'contextmenu': 'formats | link image', 'menubar': True, 'statusbar': True, } ''' -
How does Django knows which template to render when?
I am on 4th chapter the book Django 3 by example and I noticed one thing that we are only creating views from Django's authentication framework but we are not telling those views which template to render when. For example, how does my application would know that it needs to only render the logged_out.html template when we try to access the logout view? If I try to change the name of the file from logged_out.html to loggedout.html then it takes me to the Django's admin logout page. Why? -
Drop down list of images from model django ModelForm
I have a form where a user can update their profile. I want the user to choose from a dropdown list of all the available profile pictures (a gallery of profile pictures from the ProfilePictures Model) which they want to be their profile picture. At the moment the form returns the string of the image url. How can i make the actual image be in the drop down so that a user can see all the images before choosing the one they want? Models.py class ProfilePicture(models.Model): image = models.ImageField(upload_to='profile_pics', blank=True) def __str__(self): return f'{self.image.url}' class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(default='🐥 Your Bio 🙈 🙉 🙊', max_length=200) pic = models.ForeignKey(ProfilePicture, on_delete=models.SET_DEFAULT, default='1') def __str__(self): return f'{self.user.username} Profile' Forms.py class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['bio','image','pic'] # widgets = { # 'pic': ImageField(), # } Image of the current dropdown list -
Stuck with reverse lookup for getting dates of each course in django 2.2
I am building a form that has a radio button, of course, and dropdown of dates on which course would take place. Should look like the image shown below Model.py class CourseModel(models.Model): """ Name and Id for each course conducting """ id = models.CharField( primary_key=True, max_length=10 ) name = models.CharField(max_length = 100) def __str__(self): return self.name class Meta: verbose_name = 'Course' verbose_name_plural = 'Courses' class DateModel(models.Model): """ Each Course can have many Dates """ start_date = models.DateField() end_date = models.DateField(null=True) course_id = models.ForeignKey( CourseModel, on_delete = models.SET_NULL, null = True, blank = False ) def __str__(self): return "{} - {}".format(self.start_date, self.end_date) class Meta: verbose_name = 'Date' verbose_name_plural = 'Dates' I have tried various methods in form for reverse lookup but no success. forms.py class ApplyForm(forms.Form): username = forms.CharField(required = True) .... phone_number = forms.CharField() # courses = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect) # courses = forms.ModelChoiceField(widget=forms.RadioSelect, queryset = CourseModel.objects, empty_label=None ) # courses = forms.ModelChoiceField(queryset= CourseModel.objects) courses = forms.modelformset_factory(CourseModel, fields=('id', 'name',)) dates = forms.modelformset_factory(DateModel, fields=('start_date','end_date','course_id')) After reading a lot of StackOverflow forms, I found we have to use the reverse lookup to find out dates from course, therefore in forms.py I was trying to create a reverse lookup views.py def apply_page_copy(request): print(request.POST) form … -
What's the correct approach to Django css when filename functions are required?
In css, sometimes you need to reference a static file e.g: body { background-image: url("{% static 'folder/filename.jpg' %}"); } As far as I know in Django, this can't go into a .css file as the {% static '...' %} then can't be interpreted. That then causes me to write inline stylesheets within Django template files, but this seems wrong and is in practice proving very messy. What's the correct Django approach to this? -
Serializer data is not showing on the API
Hey Guys this is my first project in Django, I am trying to get my 'foreign keys' field into my API with Django Rest framework. I am trying to do a Post a product. since i cannot see input fields i am stuck here. It might be something very simpel, i might didn’t see it. Thank you in advance serializers.py from rest_framework import serializers from rest_framework.serializers import ModelSerializer from .models import * from django.contrib.auth.models import User from rest_framework.authtoken.models import Token class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'password') extra_kwargs = {'password':{'write_only':True,'required':True}} def create(self, validated_data): user = User.objects.create_user(**validated_data) print(user) Token.objects.create(user=user) return user class ProductSerializer(serializers.ModelSerializer): product_id = serializers.CharField(source='product.url', read_only=True) category_name = serializers.CharField(source='category.name', read_only=True) user_id = serializers.CharField(source='user.id', read_only=True) subject = serializers.CharField(source='subject.subject', read_only=True) condition = serializers.CharField(source='condition.condition', read_only=True) major = serializers.CharField(source='major.major', read_only=True) state = serializers.CharField(source='state.state', read_only=True) school = serializers.CharField(source='school.school', read_only=True) location = serializers.CharField(source='location.location', read_only=True) class Meta: model = Product fields = '__all__' class SubjectSerializer(serializers.ModelSerializer): model = Subject fields = '__all__' class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('url', 'id', 'name') class StateSerializer(serializers.ModelSerializer): # state_count = serializers.SerializerMethodField() class Meta: model = State fields = ['id', 'url', 'state'] # def get_state_count(self, obj): # if State.objects.count() # return obj.children().count() # return 0 … -
Django generating multiple urls for the same subcategory
In my app, there's a list of categories and subcategories with a ForeignKey relationship. Say, there're: Subcategory1 related to Category1 Subcategory2 related to Category2 I expect to get the following subcategory urls: http://127.0.0.1:8000/cat1/subcat1 http://127.0.0.1:8000/cat2/subcat2 These urls work fine. However, django also generates these urls that I don't need: http://127.0.0.1:8000/cat1/subcat2 http://127.0.0.1:8000/cat2/subcat1 Why do they appear in my app? How do I get rid of them? Thanks in advance! models.py: class Category(models.Model): categoryslug = models.SlugField(max_length=200, default="",unique=True) def get_absolute_url(self): return reverse("showrooms_by_category",kwargs={'categoryslug': str(self.categoryslug)}) class Subcategory(models.Model): subcategoryslug = models.SlugField(max_length=200, default="",unique=True) category = models.ForeignKey('Category', related_name='subcategories', null=True, blank=True, on_delete = models.CASCADE) def get_absolute_url(self): return reverse("showrooms_by_subcategory", kwargs={'categoryslug': str(self.category.categoryslug), 'subcategoryslug': str(self.subcategoryslug)}) views.py: class ShowroomCategoryView(DetailView): model = Category context_object_name = 'showrooms_by_category' template_name = "website/category.html" slug_field = 'categoryslug' slug_url_kwarg = 'categoryslug' class ShowroomSubcategoryView(DetailView): model = Subcategory context_object_name = 'showrooms_by_subcategory' template_name = "website/subcategory.html" slug_field = 'subcategoryslug' slug_url_kwarg = 'subcategoryslug' urls.py: urlpatterns = [ path('<slug:categoryslug>/<slug:subcategoryslug>/', views.ShowroomSubcategoryView.as_view(), name='showrooms_by_subcategory'), path('<slug:categoryslug>/', views.ShowroomCategoryView.as_view(), name='showrooms_by_category'), ] -
get() got an unexpected keyword argument 'pk': django
i'm creating like button for my django blog i import api to use ajex from django rest frameworks but i'm getting error in that the error is get() got an unexpected keyword argument 'pk' django view.py class PostLikeToggle(RedirectView): def get_redirect_url(self, *args, **kwargs): obj = get_object_or_404(Post, pk=kwargs['pk']) url_ = obj.get_absolute_url() user = self.request.user if user.is_authenticated: if user in obj.likes.all(): obj.likes.remove(user) else: obj.likes.add(user) return url_ from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import authentication, permissions from django.contrib.auth.models import User class PostLikeApiToggle(APIView): authentication_classes = [authentication.SessionAuthentication] permission_classes = [permissions.IsAuthenticated] def get(self, request, format=None): usernames = [user.username for user in User.objects.all()] return Response(usernames) def get_redirect_url(self, *args, **kwargs): obj = get_object_or_404(Post, pk=kwargs['pk']) url_ = obj.get_absolute_url() user = self.request.user updated = False liked =False if user.is_authenticated: if user in obj.likes.all(): liked = False obj.likes.remove(user) else: liked = True obj.likes.add(user) updated = True data = { "updated":updated, "liked":liked } return Response(data) urls.py path('blog/<int:pk>/like/', PostLikeToggle.as_view(),name='Like-Toggle'), path('blog/api/<int:pk>/like/', PostLikeApiToggle.as_view(),name='Like-Api-Toggle'), models.py class Post(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(User,on_delete=models.CASCADE) likes = models.ManyToManyField(User, blank=True,related_name='post_likes') content = models.TextField() img = models.ImageField(upload_to='pics',blank=True) time = models.DateTimeField(default=timezone.now) def __str__(self): return self.title def get_absolute_url(self): return reverse('LoveTravel-Details', kwargs={'pk': self.pk}) def get_like_url(self): return reverse('Like-Toggle', kwargs={'pk':self.pk}) def get_api_like_url(self): return reverse('Like-Api-Toggle', kwargs={'pk':self.pk}) can someone please help me get() got … -
Password reset email is not received
I very new to django. I'm working in resetting password through email in django. I'm using all the 4 default class views. I can get upto PasswordResetDoneView where the page saying instructions have been sent to my mail. But I haven't received any mail. Urls.py from django.urls import path from . import views from django.contrib.auth.views import ( LoginView,LogoutView,PasswordResetView,PasswordResetDoneView,PasswordResetConfirmView,PasswordResetCompleteView ) urlpatterns=[ path('',views.home), path('login/',LoginView.as_view(template_name='accounts/login.html'),name='login page'), path('logout/',LogoutView.as_view(template_name='accounts/logout.html'),name='logout page'), path('register/',views.registration,name='register page'), path('profile/',views.profile,name='profile'), path('profile/edit_profile/',views.edit_profile,name='edit-profile'), path('profile/change-password/',views.change_password,name='edit-profile'), path('profile/reset-password/',PasswordResetView.as_view(),name='paassword_reset_view'), path('profile/reset-password/done/',PasswordResetDoneView.as_view(),name='password_reset_done'), path('profile/reset-password/confirm/<uidb64>/<token>/',PasswordResetConfirmView.as_view(),name='password_reset_confirm'), path('profile/reset-password/complete/',PasswordResetCompleteView.as_view(),name='password_reset_complete'), ] Also I have configured the settings.py file with the necessary configurations. I have also enabled the less secure option for the mail from which I'm sending the url. setting.py EMAIL_BACKEND = "django.core.mail.backends.filebased.EmailBackend" EMAIL_FILE_PATH = os.path.join(BASE_DIR, "sent_emails") EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'projectexample@gmail.com' EMAIL_HOST_PASSWORD = 'Password' Also tried using send_mail separately in the shell. It returns 1. Hoping for a solution Thanks in advance -
How to fix permission error when uploading photos with django admin when deployed?
I am trying to upload photos using Django admin but I get the following error [Errno 13] Permission denied: '/static'. I am trying to deploy this project to a Linode server running ubuntu 18.04 LTS. I believe this is a problem with my permissions for the apache user because if I run manage.py runserver 0.0.0.0:8000 and access the site via port 8000 I can upload photos fine. I should also mention that I can use the admin page for any models that do not require photos. I have tried anything I can find online and have even chmodded 777 -R the directory to the project. This is the path to the project: /home/jonny/estate. These are the permissions from my home dir and the estate dir: jonny@django-server:~$ ls -la total 68 drwxrwxrwx 7 jonny jonny 4096 May 4 10:01 . drwxr-xr-x 3 root root 4096 May 1 17:49 .. -rwxrwxrwx 1 jonny jonny 4795 May 2 18:13 .bash_history -rwxrwxrwx 1 jonny jonny 220 May 1 17:49 .bash_logout -rwxrwxrwx 1 jonny jonny 3771 May 1 17:49 .bashrc drwxrwxrwx 3 jonny jonny 4096 May 1 18:16 .cache drwxrwxrwx 10 www-data www-data 4096 May 4 10:10 estate -rwxrwxrwx 1 jonny jonny 29 May 2 … -
How to add ManyToMany field with 'through' relation to fixtures?
In tests (fixtures) I want to add field with ManyToMany field with 'through' relation, i.e my_field = models.ManyToManyField(SomeModel, through=AnotherModel). Tried to add like regular ManyToManyField like object.my_field.add(my_field), but it gives me this warning message: enter image description here Also, tried this: object.my_field.add(my_field, through_defaults=AnotherModel), also didn't worked -
Original exception text was: 'TUser' object has no attribute 'tpr
Error: AttributeError: Got AttributeError when attempting to get a value for field tprofile on serializer TProfileSerializerUser. The serializer field might be named incorrectly and not match any attribute or key on the TUser instance. Original exception text was: 'TUser' object has no attribute 'tpr I have following model and serializer. class TUser(AbstractBaseUser, PermissionsMixin): email username user_type class UserProfile(model.Model): id user->foreign key to TUser f_name l_name phone class PartnerProfile(Mode.Model): id user-> Foreign key to TUser partner_type /*Serializers*/ class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields='__all__' class PartnerProfileSerializer(serializers.ModelSerializer): class Meta: model = PrtnerProfile fields='__all__' class TUserProfile(serializers.ModelSerializer): password1 password2 userprofile=UserProfileSerializer(required=True) class Meta: model=TUser fields=('email','username','userprofile') def create(self, validated_data): user_profile_data = validated_data.pop('userrofile') data = { key: value for key, value in validated_data.items() if key not in ('password1', 'password2','tprofile') } data['password'] = validated_data['password1'] user = self.Meta.model.objects.create_user(**data) if user_type in ['TUSER','Tuser'] and user_profile_data is not None: TUserProfile.objects.create(user=user, **user_profile_data) return user -
Django: Creating Nested Objects with Reverse Relationship
I have a problem while trying to create Nested object with a reverse relationship. I'm trying to POST a Work but at the SAME time trying to POST a Price which is a Work child. Here is my work_model: from django.db import models from django.contrib.auth import get_user_model User = get_user_model() from PIL import Image class Work(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) name = models.CharField(max_length=200) length = models.IntegerField(null=True) width = models.IntegerField(null=True) def save(self, *args, **kwargs): super(Work, self).save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) def __str__(self): return "{}".format(self.id) My price_model: from django.db import models from .model_work import * from .model_taxes import * from djmoney.models.fields import MoneyField class Price(models.Model): work = models.OneToOneField(Work, on_delete=models.CASCADE, related_name='price') price = MoneyField(max_digits=19, decimal_places=4, default_currency='USD', null=True) taxes = models.ForeignKey(Taxes, null=True, on_delete=models.SET_NULL) total = models.IntegerField(null=True) def __str__(self): return "{}".format(self.price) And my taxes_model: from django.db import models class Taxes(models.Model): tax_percentage = models.IntegerField(null=True) tax_country = models.CharField(max_length=200, null=True) tax_region = models.CharField(max_length=200, null=True) def __str__(self): return "{}".format(self.tax_country) Here is my work_serializer: from rest_framework import serializers from ..models.model_work import Work from .serializers_user import * from .serializers_price import * class WorkIndexSerializer(serializers.ModelSerializer): """ Serializer listing all Works models from DB """ user = UserIndexSerializer() price … -
Django 'utf-8' codec can't decode byte 0xe6 in position 830: invalid continuation byte
I have a problem with polish language on production. On my local server everything is working fine, but after put my website in the live on DigitalOcean I got error, when i use polish special characters like : "Ś, Ć, Ż" etc. I set charset UTF-8 also in setting.py I used LANGUAGE_CODE = 'pl' Excatly error code you can see on dwdagency.pl Many thanks for help