Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django returns UserLazyObject: TypeError: Field 'id' expected a number but got <channels.auth.UserLazyObject object
I'm using Django Channels to make a chat app following a tutorial. in my code I have a custom manager for my models. here is the manager: from import models from django.db.models import Count class ThreadManager(models.Manager): def get_or_create_personal_thread(self, user1, user2): threads = self.get_queryset().filter(thread_type='personal') threads = threads.filter(users__in=[user1, user2]).distinct() threads = threads.annotate(u_count=Count('users')).filter(u_count=2) if threads.exists(): return threads.first() else: thread = self.create(thread_type='personal') thread.users.add(user1) thread.users.add(user2) return thread def by_user(self, user): return self.get_queryset().filter(users__in=[user]) the problem is that when i introduce the model class in my consumer, I get this unfamiliar error: TypeError: int() argument must be a string, a bytes-like object or a number, not 'UserLazyObject' what is a UserLazyObject ? and is there any way around it? here is my consumer.py: the model is introduce by this line of code below, commenting it or uncommenting it removes or reintroduces the error again and again. thread_obj = Thread.objects.get_or_create_personal_thread(me, other_user) from channels.consumer import SyncConsumer from asgiref.sync import async_to_sync from chat.models import Thread from django.contrib.auth.models import User class ChatConsumer(SyncConsumer): def websocket_connect(self, event): # get the two users me = self.scope['user'] other_username = self.scope['url_route']['kwargs']['username'] other_user = User.objects.get(username=other_username) # get or create incase thread_obj = Thread.objects.get_or_create_personal_thread(me, other_user) self.room_name = 'presonal_thread_' async_to_sync(self.channel_layer.group_add)(self.room_name, self.channel_name) self.send({ 'type': 'websocket.accept' }) print(f'[{self.channel_name}] - connected now') … -
_set.all() not working in Django Template returning AttributeError
I am trying to add the no. of comments related to a post in my Django Project. but I keep receiving a 'Post' object has no attribute 'comment_set' AttributeError for some reason I don't understand why. My project has a Post Model class Post(models.Model): title = models.CharField(max_length=100, unique=True) ---------------------------------------- # To know how many comments def num_comments(self): return self.comment_set.all().count() <--------- Error from here class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="commented_users") post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="commented_posts") content = models.TextField(max_length=160) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now=True) Here is sthe views.py class UserOnlyPostListView(ListView): model = Post template_name = "score/user_only_posts.html" context_object_name = 'posts' paginate_by = 4 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(designer=user).order_by('-date_posted') def get_context_data(self, *args, **kwargs): context = super(UserOnlyPostListView, self).get_context_data() user = get_object_or_404(User, username=self.kwargs.get('username')) return context Here is the template: {% for post in posts %} <td>{{ post.num_comments }}</td> {% endfor %} My question: Why am I receiving this error and how to fix it? Thank you -
How to display self-joined fields in Django?
I'm trying to build a comment section to a social-media-esque web app I'm building. I have a datatable storing comments using Django, and would like to build in a reply feature. Here is my model: class Comments(models.Model): id = models.AutoField(primary_key=True) text = models.TextField() author = models.CharField(max_length=50) creation_time = models.DateTimeField(auto_now_add=True) answer = models.ForeignKey(Answers, on_delete=models.CASCADE) replyto = models.ForeignKey('self', null=True, on_delete=models.CASCADE) def __str__(self): return self.author + ' commented: ' + self.text Essentially, whenever someone replies to a previous comment, I'd store that previous comment's ID in the "replyto" field, with which I'd like to link the current comment to that previous comment. In getting the current comment from the view I set up, I'd like to get all fields of the current comment (as outlined above) as well as the text and author of the previous comment (i.e. comment being replied to). In base SQL, I'd figured this would be a bit of self join logic. How do I do this in Django (and show the additional text and author fields of the being-replied-to comment as described above)? Thanks! -
Django inline model formset and inline model form handle initial differently
I'm using a StackedInline to populate a OneToOneField, but I want to make it optional, so I set min_num=0 and extra = 0. I also want to include default values when the user presses the "➕ Add another" button. class MyForm(forms.ModelForm): def __init__(self, *args, **kwargs): kwargs['initial'] = {'hello': 'world'} class MyInline(admin.StackedInline): form = MyForm extra = 0 min_num=0 This works. When someone presses the "➕ Add another" button, the hello field is populated with world. I also want to and do some custom validation, so it looks like I have to use BaseInlineFormSet. I moved the initial stuff to MyFormSet.__init__ class MyFormSet(BaseInlineFormSet): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if not self.forms: return self.forms[0].fields['hello'].initial = 'world' def clean(self): # My custom validation class MyInline(admin.StackedInline): formset = MyFormSet extra = 0 min_num=0 But the initial values are no longer populated when the user presses the "➕ Add another" button, only when the form is initially displayed with extra = 1. Is there another thing I need to do in MyFormSet to preserve the MyForm behavior? -
Django AWS S3 403 (Forbidden)
I'm hosting my Static and Media Files of my Django Project on AWS s3. The static files for admin and the image files are working fine, but some of the static files CSS & JS are giving a 403 error(URL for reference- https://maruthi-static.s3.amazonaws.com/static/css/customer_view/main/main.css). I'm using boto3-1.16.40 and django-storages-1.11, with AWS IAM user with AmazonS3FullAccess permission. The following is my code. Settings.py # STORAGES # ------------------------------------------------------------------------------ AWS_ACCESS_KEY_ID = "----" AWS_SECRET_ACCESS_KEY = "----" AWS_STORAGE_BUCKET_NAME = "maruthi-static" AWS_QUERYSTRING_AUTH = False _AWS_EXPIRY = 60 * 60 * 24 * 7 AWS_S3_OBJECT_PARAMETERS = { "CacheControl": f"max-age={_AWS_EXPIRY}, s-maxage={_AWS_EXPIRY}, must-revalidate" } AWS_S3_REGION_NAME = "us-east-2" AWS_S3_CUSTOM_DOMAIN = None aws_s3_domain = f"{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com" AWS_DEFAULT_ACL = None # STATIC # --------------------------------------------------------------------------------------- AWS_STATIC_LOCATION = 'static' STATICFILES_STORAGE = "tps.storages.StaticRootS3Boto3Storage" COLLECTFAST_STRATEGY = "collectfast.strategies.boto3.Boto3Strategy" STATIC_URL = f"https://{aws_s3_domain}/{AWS_S3_REGION_NAME}/static/" # MEDIA # ------------------------------------------------------------------------------ AWS_PUBLIC_MEDIA_LOCATION = 'media/public' DEFAULT_FILE_STORAGE = "tps.storages.MediaRootS3Boto3Storage" MEDIA_URL = f"https://{aws_s3_domain}/{AWS_S3_REGION_NAME}/media/" AWS_PRIVATE_MEDIA_LOCATION = 'media/private' PRIVATE_FILE_STORAGE = 'mysite.storages.PrivateMediaRootS3Boto3Storage' storages.py from storages.backends.s3boto3 import S3Boto3Storage from django.conf import settings class StaticRootS3Boto3Storage(S3Boto3Storage): location = settings.AWS_STATIC_LOCATION default_acl = "public-read" class MediaRootS3Boto3Storage(S3Boto3Storage): location = settings.AWS_PUBLIC_MEDIA_LOCATION file_overwrite = False class PrivateMediaRootS3Boto3Storage(S3Boto3Storage): location = settings.AWS_PRIVATE_MEDIA_LOCATION default_acl = 'private' file_overwrite = False custom_domain = False All my static and media files were uploaded to my s3 bucket when I ran collectstatic. I have set the … -
Joining tables in a nested serializer in django?
I am kind of at my wits end here. Been searching for hours but i can't wrap my head around it. I have the following models: class Word(models.Model): sentence = models.ForeignKey(Sentence) vocabulary = models.ForeignKey(Vocabulary) class Sentence(models.Model): text= models.ForeignKey(Text) class Text(models.Model): ... class Vocabulary(models.Model): ... class VocabularyStatus(models.Model): vocabulary = models.ForeignKey(Vocabulary) user = models.ForeignKey(User) status1 = models.IntegerField(default=1) status2 = models.IntegerField(default=1) My desired output is in the form of: text = { "sentences": { "words": { "id": 1 "vocabulary": 1 "status1": 1 "status2": 1 } } } So basically the hirarchy is Text > multiple sentences > multiple words. And the status is different based on the user who is doing the query. The reason why Vocabulary is different from Word is because multiple words can have the same vocab (e.g uppercase/lowercase words) Serializers: class TextSerializer(serializers.ModelSerializer): sentences = SentenceSerializer(many=True) class SentenceSerializer(serializers.ModelSerializer): words = WordSerializer(many=True) class WordSerializer(serializers.ModelSerializer): ... With the queryset: queryset = Text.objects.prefetch_related('sentences', 'sentences__words') It works fine for that. But i have no idea how to link the data from VocabularyStatus into that. It is already a nested serializer. I tried: queryset = Text.objects.prefetch_related('sentences', Prefetch('sentences__words', Word.objects.prefetch_related('vocabulary__vocabularystatus_set'))) But now i have no idea how to filter for the user with that or how to … -
Task schedules for django database in python
Im starting a web app with a mongo database. I want to update this database every 5 minutes so the users can have the newest data available. Before i started with django, i used crontab to execute my crawling scripts in an external server and update automatically my DB. However, ive read that it is better not to use cron with django because it should only be applied to system operations and it is not portable. What task scheduler is the best for django? Some posts suggest Celery and some others suggest RQ. Which is the way to go? Thank you in advance. -
raise ValidationError on inlineformset not showing errors
I am trying to raise ValidationError if a duplicate entry found in an inlineformset, just like in the docs: (Custom formset validation) I am debugging my code and followng it's progress and when it reaches the line: raise ValidationError("Check Duplicate Entry"), the code jumps to render the form again. The template renders with the form data left filled out but there are no validation errors appearing to say what is wrong. I'm missing something for sure. Any help appreciated. class MyInlineFormSet(BaseInlineFormSet): def __init__(self, *args, **kwargs): super(MyInlineFormSet, self).__init__(*args, **kwargs) for form in self.forms: form.empty_permitted = False def clean(self): if any(self.errors): return mylist = [] for form in self.forms: myfield_data = form.cleaned_data.get("myfield") if myfield_data in mylist: raise ValidationError("Check Duplicate Entry") mylist.append(myfield_data) My tempate just has this: {% block content %} <section class="container-fluid"> {% crispy form %} </section> {% endblock content %} -
Back button to a related object
I'm building an app where I can add recipes and add ingredients to those recipes. On view recipe_details I have a button to add_new_ingredient. When I'm on new_ingredient_form I want to have back button to get back to the details of recipe. I'm trying to pass recipe's pk but it doesn't work. How am I able to pass recipe's pk to be able to back to previous view? models.py class Recipe(Timestamp): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) title = models.CharField(max_length=100, unique=True) preparation = models.TextField() def __str__(self): return self.title class Ingredient(Timestamp): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) name = models.CharField(max_length=100) amount = models.PositiveSmallIntegerField(blank=True, null=True) unit = models.ForeignKey('Unit', on_delete=models.SET_NULL, blank=True, null=True) def __str__(self): return self.name views.py class RecipeView(generic.DetailView): model = Recipe context_object_name = 'recipe' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['ingredients_list'] = Ingredient.objects.filter(recipe=self.object.pk) return context class AddIngredientView(generic.edit.CreateView): model = Ingredient fields = [ 'name', 'amount', 'unit' ] success_url = '/' template_name = 'recipes/add_ingredient.html' def dispatch(self, request, *args, **kwargs): self.recipe = get_object_or_404(Recipe, pk=self.kwargs['pk']) return super().dispatch(request, *args, **kwargs) def form_valid(self, form): form.instance.recipe = self.recipe return super().form_valid(form) def get_success_url(self): if 'add_another' in self.request.POST: url = reverse_lazy('recipes:add_ingredient', kwargs={'pk': self.object.recipe_id}) else: url = reverse_lazy('recipes:recipe', kwargs={'pk': self.object.recipe_id}) return url add_ingredient.html {% extends "base.html" %} … -
Django: Unable to login with user
When I have registered a user, they get redirected to the login-page but I seems that my error message triggers which means that my login function is not working properly working. Any suggestions what I'm doing wrong, it worked well before. My function in views.py def LoginUser(request): if request.method == "POST": email = request.POST.get('email') password = request.POST.get('password') user = authenticate(request, email=email, password1=password) if user is not None: print(user) login(request, user) return redirect('/start.html') else: messages.info(request, 'Incorrect user details') context = {} return render(request, "/login.html", context) My forms.py from django.contrib.auth.forms import AuthenticationForm, UserCreationForm from django.contrib.auth import login, authenticate from django.contrib.auth.models import User from django import forms from .models import Account, MyAccountManager class RegisterForm(UserCreationForm): #firstname = forms.EmailField() #lastname = forms.EmailField() email = forms.EmailField(required=True) class Meta: model = Account fields = ["email", "password1", "password2"] -
How to manually clear DB in a Django test?
I am using: python = "3.8.3", django="3.0.5" I have written a django test with APITestCase. I am running other tests inside my test class. I am trying to call other functions inside my test class. In order to do this I have a dictionary in a list which i mapped like this: [ { "class_name": class_name, "func_name": "test_add_product", # Comes test name "trigger_type": trigger_type, # Comes from model choices field. "request_type": RequestTypes.POST, "success": True, }, { ... }, ] I am looping these with a for loop and running each one. After each loop db should be cleared in order to not get error. I tried to do this using: # Lets say that, we have a Foo model Foo.objects.all().delete() This method works, but I want a better solution. How can I manually clear the test db before the test finishes? -
ContactForm not showing up in footer
I am trying to add a contact form in the footer of my base.html. Try tracking down everything I can but can't seem to find why the 3 fields in my form are not showing up. This is my codes: forms.py from django import forms class ContactForm(forms.Form): contact_name = forms.CharField(max_length = 50) email_address = forms.EmailField(max_length = 150) message = forms.CharField(widget = forms.Textarea) views.py from django.shortcuts import render, get_object_or_404, redirect from .models import CoollegeProductModel, NonCoollegeProductModel from .forms import ContactForm from django.core.mail import send_mail, BadHeaderError from django.http import HttpResponse def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): subject = "Website Inquiry" body = { 'contact_name': form.cleaned_data['contact_name'], 'email': form.cleaned_data['email_address'], 'message': form.cleaned_data['message'], } message = "\n".join(body.values()) try: send_mail(subject, message, 'admin@example.com', ['admin@example.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('product/home.html') form = ContactForm() return render(request, "product/contact.html", {'form':form}) contact.html <!--Contact form--> <div style="margin:80px"> <h1>Contact</h1> <h4>Contact us directly if you have any questions</h4> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> </div> base.html <footer style="background-color: #e3f2fd"> {% include "product/contact.html" %} </footer> This is what the footer display: enter image description here Appreciate your help!! -
Operational Error while running unit tests Django
I have dockerized my Django app together with my postgres Database. However after the dockerization, the unit tests that i have written (not the SimpleTestCase but the TestCase ones) stopped running. I thought it could be because of the new db so I modifies the setting for the tests to run with the default DJango db: import sys if 'test' in sys.argv: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3' } } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': 5432, } } Still, I get the following error: Creating test database for alias 'default'... Traceback (most recent call last): File ".../.local/lib/python3.8/site-packages/django/db/backends/utils.py", line 82, in _execute return self.cursor.execute(sql) File ".../.local/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 411, in execute return Database.Cursor.execute(self, query) sqlite3.OperationalError: near "[1]": syntax error Any ideas what might be the problem and how it can be fixed? -
Django: Create superuser() got an unexpected keyword argument 'password'
I am trying to define my own user module by following the documentation, but I receive the following error message whenever I try to create my first super user. TypeError: create_superuser() got an unexpected keyword argument 'password' Some people seem to have solved it by commenting user.is_staff and user.is_admin but it didn't work for me. Any suggestions? My models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin # Create your models here. class MyAccountManager(BaseUserManager): def create_user(self, email, first_name, last_name, password=None): if not email: raise ValueError("Users must have an email address") if not first_name or last_name: raise ValueError("Users must have a first and last name") user = self.model( email=self.normalize_email(email), first_name=first_name, last_name=last_name, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, first_name, last_name): user = self.model( email=self.normalize_email(email), password=password, first_name=first_name, last_name=last_name, ) #user.is_staff = True user.is_superuser = True #user.is_admin = True user.save(using=self._db) return user class Account(AbstractBaseUser, PermissionsMixin): email = models.EmailField(verbose_name="email", max_length=60, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now_add=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) # Stupid name in Django - Basically is the "Login field" USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] objects = MyAccountManager() def … -
Files in django template
i have a problem when i am trying to show files download link in django templates error: AttributeError: 'NoneType' object has no attribute 'split' File "c:\users\ramin\appdata\local\programs\python\python36-32\Lib\wsgiref\simple_server.py", line 35, in close self.status.split(' ',1)[0], self.bytes_sent ---------------------------------------- AttributeError: 'NoneType' object has no attribute 'split' ---------------------------------------- models.py: from django.db import models class Book(models.Model): Title = models.CharField(max_length=100) Writer = models.CharField(max_length=100) Description = models.TextField() Image = models.ImageField(default='default.txt') File = models.FileField(upload_to='PDF/') def __str__(self): return self.Title views.py: from django.views.generic.list import ListView from . import models class BookListView(ListView): queryset = models.Book.objects.all() template_name = 'Book/BookList.html' template: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Books List</title> </head> <body> {% for x in object_list %} <h2><a href="">{{ x.Title }}</a></h2> <img style="width:100px" src="{{ x.Image.url }}"> <p><a href="{{ x.File.url }}" download="{{ x.Title }}">Download</p> {% endfor %} </body> </html> when i click on download link , i can download file successfully but i see this message -
Response time is so slow in Django API connected with Apache and mod_wsgi
I have a Django API in the ubuntu ec2 which is connected to Apache web server and installed mod_wsgi in python itself using pip. The Django API takes about 4 seconds to run. When I make concurrent requests the response time increases to a minute sometimes even more. Modwsgi supposed to make all those call work independent of each other right rather than making it work one after the other. I have no solution right now -
How is it possible to pass class attributes as arguments of my model class in django
How is it possible to pass class attributes as arguments of my model class? Maybe I am missing something For example: from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) I can get an instance of the above just by doing for example user=User.objects.filter(username='me')[0] Post(title='random title', content='dqwdf', author=user) which I find strange since the fields of the class are class attributes and not instance attributes. For example from Python: class Whatever: pay = 3 profit = 2 I know I cannot do Whatever(pay=3,profit=2) On topic another question: Does models.Model have its own init ? If yes since my Post class inherits from it then it should have same init. Is it correct for me to assume that it takes no arguments other than self? -
Django media files are not being display
I am trying to display the uploaded media files to a user on Django, however, although the GET request returns 200 which means the file exists I still cannot the image being displayed properly below is my configuration for uploading media files. MEDIA_URL = '/media/' MEDIA_DIRS = [ os.path.join(BASE_DIR,'media') ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') and in my project urls.py I have: static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT ) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) On my model the upload path is: image = models.ImageField(upload_to=upload_to_uuid('media/users_images/'), blank=True) which when an image is uploaded I can see that the file is added however, on my page I do not see the file and it shows me a thumbnail. How can I fix this? -
Unify multiple records of a cvs file - Django
I'm generating a CVS file from a database but I want to unify some records in only one row. The original CVS look like this: Model Name Configurations_variatons MODEL-1 Lipstick Grand Rouge Mate cod=23432, color=23432-150 MODEL-1 Lipstick Grand Rouge Mate cod=23770, color=23770-151 And I want to show with only one row per model but unifying the Configurations_variatons column: Model Name Configurations_variatons MODEL-1 Lipstick Grand Rouge Mate cod=23432, color=23432-150 - cod=23770, color=23770-151 The code to generate the cvs file: def cvs_file_generator(request): # Get all data from UserDetail Databse Table products = Products.objects.all() # Create the HttpResponse object with the appropriate CSV header. response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="csv_database_write.csv"' writer = csv.writer(response) writer.writerow(['Model', 'Name', 'Configurations_variatons']) for product in products: writer.writerow([product.model, product.name, product.configurations_variatons]) return response -
Cannot commit relation 'workorder_images' on an unsaved model
I am implementing an email_dispatch app, which contains an EmailObjectManager manager class that implements create_email_object, which creates the respective model EmailObject. My end goal is to use Celery to query the database and dispatch these emails at a periodic interval. I tried to do this in the save() function, but since EmailObject has a foreign key to the model being saved (WorkOrder), I have determined I need to use a post_save signal. I am getting an error relating to my WorkOrder's Image orderable, but am not sure how to resolve this issue. Here's my code: post_save signal function definition def create_email(sender, instance, created, **kwargs): if (EmailObject.objects.all(related_workorder=instance, status=instance.status).count() == 0): EmailObject.objects.create_email_object(workorder=instance, workorder_status=instance.status) print("Email created!") EmailObject & Manager class EmailObjectManager(models.Manager): """EmailObject Manager""" def create_email_object(self, workorder, workorder_status): email_object = self.create(related_workorder=workorder, status=workorder_status) print("Workorder email created") return email_object class EmailObject(models.Model): """EmailObject model.""" STATUS_CHOICES = ( ('o', 'Open'), ('c', 'Closed'), ('x', 'Cancelled'), ) related_workorder = models.ForeignKey('workorders.WorkOrder', related_name="emails", on_delete=models.CASCADE) status = models.CharField(max_length=1, blank=False, default="o", choices=STATUS_CHOICES) has_sent = models.BooleanField(default=False) objects = EmailObjectManager() def get_context(self, request): context = super().get_context(request) return context def __str__(self): return self.related_workorder.related_customer.name def save(self, *args, **kwargs): return super(EmailObject, self).save(*args, **kwargs) WorkOrder(models.Model) class WorkOrder(index.Indexed, ClusterableModel, models.Model): """Workorder model.""" same_as_customer_address = models.BooleanField(blank=True, default=False, verbose_name="Same as Customer") ....more Django … -
How to move from page refresh to dynamic in django
My Django website currently runs everything through page refresh. If i click on an upvote button, it updates the model and refreshes the page to show the question as voted up. What is the best way to move from this page refresh to a more dynamic in-page refresh? I have heard i should be using Ajax and Django rest framework. Is there a difference between this method and using something like React? -
How to limit Django's builtin auth allowed username characters?
I'm using the builtin auth app of Django not the django-allauth. Is it possible to limit the allowed special characters in Django's builtin auth app usernames? the default allowed characters are: Letters, digits and @/./+/-/_ I want to be: Letters, digits and ./_ Regards -
how to solve it when i get 'pythn is not found' as message?
hello everyone i hope you're all doing great basically i start developing in python using django , and for the editor im using VScode , i did already install python,django,pip and all of what is necessary in the terminal but i have a problem when try execute a command in the terminal using python (ig: python .\manage.py makemigrations) i get this message (Python cannot be found. Execute without argument to proceed) and literally i couldn't find any solution to this problem in the intrnet , i hope i can find some answers ps: i have windows 10 as ES thanks for everyone -
Django tag showing errors in html
I have this block of code in my django project: <div class="avatar-preview"> <div id="imagePreview" style="background-image: url({{ request.user.img_url }});"> </div> In Virtual Studio Code, it returns these errors: VSCODE PROBLEMS IMAGE But it's actually working, I mean, like the 'syntax' is wrong but the code works, the image is displayed correctly. How can I get rid of these errors? -
what is wroung in this code after data in this view?
I'm trying to save values in respected model by it shows error like this: File "/home/bikash/tt/nascent/nascent_backend/home/views.py", line 72, in dispatch user.save() AttributeError: 'NoneType' object has no attribute 'save' class CheckoutSessionView(TemplateView): def dispatch(self, request, *args, **kwargs): if request.method == 'POST': price1 = request.body price2 = price1.decode('utf-8') price11 = json.loads(price2) print(price11) print(type(price11),990, price11['json_data']['priceId']) password1 = price11['json_data']['password1'] password2 = price11['json_data']['password2'] name = price11['json_data']['name'] company = price11['json_data']['company'] contact = price11['json_data']['contact'] email = price11['json_data']['email'] user = User(name = name, username = company, email = email, contact=contact ) if password1==password2: user = user.set_password(password1) user.save() company = Company(title = company) company.owner = user company.save() company.members.add(user) how can i save this?