Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Profile page is showing error under postlist href since pk number is increasing?
in blog page, i have made profile pages link for every user. there is also a view for userlist where users linked to their own profile page. here is my blog/models.py: class Post(models.Model): title = models.CharField(max_length=255) body=RichTextField(blank=True,null=True) image=models.FileField(upload_to="mediaphoto",validators=[validate_file_size]) topImage=ImageSpecField(source='image',processors=[ResizeToFill(750,300)],format='PNG',options={'quality':60}) date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User,on_delete=models.CASCADE) category=models.ForeignKey(Category,on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail', args=[str(self.id)]) blog/views.py: class CustomContentMixin: def get_context_data(self, **kwargs): context = super(CustomContentMixin, self).get_context_data(**kwargs) context['user_list']= Profile.objects.all() context['category_list']=Category.objects.all() return context class BlogappListView(CustomContentMixin,ListView): model = Category,Profile template_name = 'home.html' context_object_name='post_list' queryset=Post.objects.all() paginate_by=7 class BlogappUpdateView(CustomContentMixin,UpdateView,LoginRequiredMixin,UserPassesTestMixin): model=Post template_name='post_edit.html' fields=('title','body','image','category') login_url='login' def test_func(self): obj = self.get_object() return obj.author == self.request.user class BlogappDetailView(DetailView,LoginRequiredMixin,FormMixin): model=Post template_name='post_detail.html' login_url='login' form_class=CommentForm def get_success_url(self): return reverse_lazy('post_detail', kwargs={'pk': self.object.pk}) def get_context_data(self, **kwargs): context = super(BlogappDetailView, self).get_context_data(**kwargs) context['comments']=Comment.objects.filter(post=self.object) context['comment_form']=CommentForm() context['user_list']= Profile.objects.all() context['category_list']=Category.objects.all() return context def post(self, request, *args, **kwargs): self.object = self.get_object() comment_form = self.get_form() if comment_form.is_valid(): return self.form_valid(comment_form) else: return self.form_invalid(comment_form) def form_valid(self, comment_form): comment_form.instance.post = self.object comment_form.instance.author=self.request.user comment_form.save() return super().form_valid(comment_form) class BlogappDeleteView(CustomContentMixin,DeleteView,LoginRequiredMixin,UserPassesTestMixin): model=Post template_name='post_delete.html' success_url=reverse_lazy('home') login_url='login' def test_func(self): obj = self.get_object() return obj.author == self.request.user class BlogappCreateView(CustomContentMixin,CreateView,LoginRequiredMixin): model=Post template_name='post_new.html' login_url='login' fields=('title','body','image','category') def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) acounts/models.py: class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True) name=models.CharField(max_length=30, blank=True) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birthdate = models.DateField(null=True, blank=True) def … -
how do I post a foreign key by some other field rather than primary key in django rest framework
I am developing a pet management api and this is what I post to the body when assigning a day of the week to a pet : { "day": "Sunday", "pet_name": 2 <-- how to add pet name (rather than the primary key)(this is a foreign key) } How do I pass in the pet name which is the foreign key's field rather than the primary key field. -
updating an user's object in django
i have a problem in updating an exsited object in my models ,when i update and change the user object its gonna save and everything is looked ok but i guess its just save ,because when i change the user and i want to login ,beside of login view this user dosnt authenticated and dosnt login. here my code def profile_edit(request): user = request.user profile = request.user.profile context = { 'user': user } if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') email = request.POST.get('email') user.profile.address = request.POST.get('address') user.profile.phone = request.POST.get('phone') user.set_password('password') user.username = username user.save() user.profile.save() authenticate(user) context = { 'profile': profile } return render(request, 'helpdesk/profile.html', context) return render(request, 'helpdesk/profile_edit.html', context) and login view def login_view(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) profile = request.user.profile context = { 'profile': profile } return render(request, 'helpdesk/user_desk.html', context) else: context = { 'username': username, 'error': 'user not find!' } else: context = {} return render(request, 'helpdesk/login.html', context) -
Django calendar clickable days
I'm implementing an events calendar and i'm trying to make clickable days that automatically fill in day field in my models is there a way to pass selected day to the day field in models.py or is there any widget that i can use instead of this one? Here is my models.py models.py class Event(models.Model): day = models.DateField() start_time = models.TimeField(u'Starting time', help_text=u'Starting time') end_time = models.TimeField(u'Final time', help_text=u'Final time') notes = models.TextField(u'Textual Notes', help_text=u'Textual Notes', blank=True, null=True) class Meta: verbose_name = u'Scheduling' verbose_name_plural = u'Scheduling' def check_overlap(self, fixed_start, fixed_end, new_start, new_end): overlap = False if new_start == fixed_end or new_end == fixed_start: #edge case overlap = False elif (new_start >= fixed_start and new_start <= fixed_end) or (new_end >= fixed_start and new_end <= fixed_end): #innner limits overlap = True elif new_start <= fixed_start and new_end >= fixed_end: #outter limits overlap = True return overlap def get_absolute_url(self): url = reverse('admin:%s_%s_change' % (self._meta.app_label, self._meta.model_name), args=[self.id]) return u'<a href="%s">%s</a>' % (url, str(self.start_time)) def clean(self): if self.end_time <= self.start_time: raise ValidationError('Ending hour must be after the starting hour') events = Event.objects.filter(day=self.day) if events.exists(): for event in events: if self.check_overlap(event.start_time, event.end_time, self.start_time, self.end_time): raise ValidationError( 'There is an overlap with another event: ' + str(event.day) … -
Unable to Create with OneToOneField Django
I'm stuck with this issue for a while now and couldn't find a solution. Here is the issue: Background: I have CustomUser(AbstractUser) model and HeroesUser which has OneToOneField relationship with CustomUser model. (Hero user is a user type, later on I'll have more fields but at the moment I just put in "city" to be simple) I want to be able to create a hero user for each custom user, but unable to do so with this OneToOneRelationship. So please please if you have experience, please help me!!! Here are my codes: models.py from django.contrib.auth.models import AbstractUser import datetime class CustomUser(AbstractUser): is_hero = models.BooleanField(default=False) is_host = models.BooleanField(default=False) want_newsletter = models.BooleanField(default=False) def __str__(self): return self.username class HeroesUser(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, primary_key=True) city = models.CharField(max_length=50, default="") serializers.py from .models import CustomUser, HeroesUser from django.utils import timezone class CustomUserSerializer(serializers.Serializer): id = serializers.ReadOnlyField() username = serializers.CharField(max_length=200) email = serializers.CharField(max_length=200) password = serializers.CharField(write_only=True) first_name = serializers.CharField(max_length=200) last_name = serializers.CharField(max_length=200) is_hero = serializers.BooleanField(default=False) is_host = serializers.BooleanField(default=False) is_staff = serializers.BooleanField(default=False) def create(self, validated_data): return CustomUser.objects.create_user(**validated_data) class CustomUserDetailSerializer(CustomUserSerializer): def update(self, instance, validated_data): instance.email = validated_data.get('email', instance.email) instance.first_name = validated_data.get('first_name', instance.first_name) instance.last_name = validated_data.get('last_name', instance.last_name) instance.is_hero = validated_data.get('is_hero', instance.is_hero) instance.is_host = validated_data.get('is_host', instance.is_host) instance.is_staff = validated_data.get('is_staff', instance.is_staff) instance.save() … -
Is there a way to get the columns from a joined table in the model instance dict object?
t = PurchaseHeader.objects.first() t.__dict__ { '_state': <django.db.models.base.ModelState object at 0x7f4b34aa7fa0>, 'id': 3, 'ref': 'jhkh', 'goods': Decimal('-100.00'), 'discount': Decimal('0.00'), 'vat': Decimal('-20.00'), 'total': Decimal('-120.00'), 'paid': Decimal('-120.00'), 'due': Decimal('0.00'), 'date': datetime.date(2020, 11, 7), 'due_date': datetime.date(2020, 11, 14), 'period': '202007', 'status': 'c', 'created': datetime.datetime(2020, 11, 7, 15, 46, 48, 191772, tzinfo=<UTC>), 'cash_book_id': None, 'supplier_id': 1128, 'type': 'pc' } When I joined the supplier table I was disappointed to find that the columns are not included in the dict. Below, t.__dict__ is the same as above. I noticed that the Supplier model instance is cached inside of t._state so I guess I could create my own method which all models inherit from which does what i want - all the columns from all tables inside a dict. But I wondered if anybody knew a way of doing this sort of thing out of the box? t = PurchaseHeader.objects.select_related("supplier").first() t.__dict__ -
Ckeditor texteditor not appearing in django admin where RichTextfield is applied
I have tried everything but the texteditor is not appearing in the admin page in the richtextfield type. I installed django ckeditor and have the following in the settings.py: Richtextfield pic CKEDITOR_BASEPATH = "/static/ckeditor/ckeditor/" CKEDITOR_UPLOAD_PATH = "uploads/" #ckeditor configs #todo CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'full', 'width': 1000, 'height': 400 }, } DEBUG = False STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') My urls is as follows: urlpatterns = [ path('admin/', admin.site.urls), path('', admin.site.urls), path('', include('apps.accounts.urls')), path('', include('apps.blogs.urls')), path('', include('apps.enquiry.urls')), path('', include('apps.packages.urls')), path('', include('apps.booking.urls')), path('ckeditor', include('ckeditor_uploader.urls')), ]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # ]+static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) if settings.DEBUG is True: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I have even tried collectstatic and every files are collected but still the richtextfield appears blank. How to solve this?? -
Django enum named groups
I want a listing to be able to have a specific category, so the seller will choose a general category and then onto a more specific one, for example: Men's Wear: Jeans: Skinny Fit Slim Fit Regular Fit Pants: Slim Fit Formal Casual Women's Apparel: Tops: Tunics Denim: Jeans I tried the named groups like in django docs: https://docs.djangoproject.com/en/3.0/ref/models/fields/#field-choices-named-groups MEDIA_CHOICES = [ ('Audio', ( ('vinyl', 'Vinyl'), ('cd', 'CD'), ) ), ('Video', ( ('vhs', 'VHS Tape'), ('dvd', 'DVD'), ) ), ('unknown', 'Unknown'), ] But when I tried, it gives the error product.Listing.category: (fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples. here is my code: class Listing(models.Model): CATEGORY = [ ('Women\'s Apparel', ( ('Dresses', ( ('party_dresses', 'Party Dresses'), ) ), ), ), ] id = models.AutoField(primary_key=True) title = models.CharField(max_length=255) description = models.CharField(max_length=255) new_condition = models.BooleanField() category = models.CharField(choices=CATEGORY, max_length=255) why is it showing error ? is it because the enum groups cant be nested more than 1 level ? thank you -
Is there a way to send a form class as parameter to a function in a template in django?
I'm creating a website that has multiple pages that each has one form. This one form on each page has an "add", "modify" and "delete" button. I need to create a lot functions to process all this because they are on different pages working with different form classes and model classes. To create a more general approach it would be usefull if I could just pass the form class and/or model class as a parameter in a template to a view (se example below). When writing a capture pattern for this in the urls.py file I cant find anything to capture a reference to an object though like a form class or model class... I only see that you can capture strings, integers and so on. What im thinking about is something like this: {% url '' id form_class %} where id and form class are the parameters to the view. Is there any way to actually do this ? I want to do this so I dont have to write add, modify and delete view functions for every form on every page and instead have one add, modify and delete for every form without having if loops and checking … -
Delete an object with a large number of CASCADE models on Django
I am running into an issue where I cannot delete user accounts with Django. The problem is that there are several other models in code that have the field: user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) These models themselves have other models that are set to be deleted with on_delete=models.CASCADE when they are deleted. So when I try to delete a user that had a lot of activity on my website, it can quickly become tens of thousands of items to delete. This causes the delete operation to never end and the account to not get deleted. Worse, only some of the content gets deleted as the operation is interrupted. How should I handle deleting a model with many CASCADE delete linked to it? I am using Django 3.1 with a MySQL db. -
Django: posting information to multiple models with one html form
I'm building my first solo django project right now so I'm learning a lot. I've run into a problem that I can't think how to fix. For a fantasy football app project, I've represented each type of player position with their own model. Like this... class Quarterback(models.Model): name = models.CharField(max_length=20) class Runningback(models.Model): name = models.CharField(max_length=20) class Widereceiver(models.Model): name = models.CharField(max_length=20) class Tightend(models.Model): name = models.CharField(max_length=20) class Kicker(models.Model): name = models.CharField(max_length=20) I have a "choose player" page that uses javascript to fill in model forms that I've made for each player model. This is my forms.py class Quarterbackform(forms.ModelForm): class Meta: model = Quarterback fields = "__all__" widgets = { 'name': forms.TextInput(attrs={'id':'QB_name'}) } class Runningbackform(forms.ModelForm): class Meta: model = Runningback fields = "__all__" widgets = { 'name': forms.TextInput(attrs={'id':'RB_name'}) } class Widereceiverform(forms.ModelForm): class Meta: model = Widereceiver fields = "__all__" widgets = { 'name': forms.TextInput(attrs={'id':'WR_name'}) } class Tightendform(forms.ModelForm): class Meta: model = Tightend fields = "__all__" widgets = { 'name': forms.TextInput(attrs={'id':'TE_name'}) } class Kickerform(forms.ModelForm): class Meta: model = Kicker fields = "__all__" widgets = { 'name': forms.TextInput(attrs={'id':'K_name'}) } My views.py has this function to save player selections to their respective model. def emp(request): url = 'hidden' r = requests.get(url.format()).json() player_data = [] #print(r) … -
django import export error: Line number: 1 - import_obj() takes 3 positional arguments but 4 were given
I've upgraded a django project to the latest version of django 3.1.2 and also one of it's dependencies django-import-export which as it says helps import data to models, previously importing csv was working ok but with the update of it also to the latest version i get this error Line number: 1 - import_obj() takes 3 positional arguments but 4 were given DAVAN, LEMETEI, M, 37291003, , 4827, , KAMPI YA KANZI, , , , , , , , , 7/9/2020, N/A, N/A, N/A, , N/A, N/A, N/A, N/A, N/A, N/A, N/A, , N/A, N/A, N/A, N/A, N/A, N/A, N/A, N/A, N/A, N/A, N/A, N/A, N/A, Traceback (most recent call last): File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/import_export/resources.py", line 662, in import_row self.import_obj(instance, row, dry_run) TypeError: import_obj() takes 3 positional arguments but 4 were given Line number: 2 - import_obj() takes 3 positional arguments but 4 were given PARASHINA, NTANIN, M, 12740086, , 4828, , KAMPI YA KANZI, , , , , , , , , 7/9/2020, N/A, N/A, N/A, , N/A, N/A, N/A, N/A, N/A, N/A, N/A, , N/A, N/A, N/A, N/A, N/A, N/A, N/A, N/A, N/A, N/A, N/A, N/A, N/A, Traceback (most recent call last): File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/import_export/resources.py", line 662, in import_row self.import_obj(instance, row, … -
RuntimeWarning: You're running the worker with superuser privileges: this is absolutely not recommended
When I am daemonizing the celery worker it is giving me the above warning along with the following error: Traceback (most recent call last): File "/var/app/venv/env/lib/python3.7/site-packages/celery/worker/worker.py", line 205, in start self.blueprint.start(self) File "/var/app/venv/env/lib/python3.7/site-packages/celery/bootsteps.py", line 119, in start step.start(parent) File "/var/app/venv/env/lib/python3.7/site-packages/celery/bootsteps.py", line 370, in start return self.obj.start() File "/var/app/venv/env/lib/python3.7/site-packages/celery/worker/consumer/consumer.py", line 316, in start blueprint.start(self) File "/var/app/venv/env/lib/python3.7/site-packages/celery/bootsteps.py", line 119, in start step.start(parent) File "/var/app/venv/env/lib/python3.7/site-packages/celery/worker/consumer/consumer.py", line 592, in start c.loop(*c.loop_args()) File "/var/app/venv/env/lib/python3.7/site-packages/celery/worker/loops.py", line 91, in asynloop next(loop) File "/var/app/venv/env/lib/python3.7/site-packages/kombu/asynchronous/hub.py", line 299, in create_loop item() File "/var/app/venv/env/lib/python3.7/site-packages/vine/promises.py", line 170, in call return self.throw() File "/var/app/venv/env/lib/python3.7/site-packages/vine/promises.py", line 167, in call retval = fun(*final_args, **final_kwargs) File "/var/app/venv/env/lib/python3.7/site-packages/kombu/transport/SQS.py", line 336, in _schedule_queue queue, callback=promise(self._loop1, (queue,)), File "/var/app/venv/env/lib/python3.7/site-packages/kombu/transport/SQS.py", line 352, in _get_bulk_async return self._get_async(queue, maxcount, callback=callback) File "/var/app/venv/env/lib/python3.7/site-packages/kombu/transport/SQS.py", line 362, in _get_async qname, count=count, connection=self.asynsqs, File "/var/app/venv/env/lib/python3.7/site-packages/kombu/transport/SQS.py", line 456, in asynsqs region=self.region File "/var/app/venv/env/lib/python3.7/site-packages/kombu/asynchronous/aws/sqs/connection.py", line 27, in init **kwargs File "/var/app/venv/env/lib/python3.7/site-packages/kombu/asynchronous/aws/connection.py", line 186, in init **http_client_params) File "/var/app/venv/env/lib/python3.7/site-packages/kombu/asynchronous/aws/connection.py", line 151, in init self._httpclient = http_client or get_client() File "/var/app/venv/env/lib/python3.7/site-packages/kombu/asynchronous/http/init.py", line 22, in get_client client = hub._current_http_client = Client(hub, **kwargs) File "/var/app/venv/env/lib/python3.7/site-packages/kombu/asynchronous/http/init.py", line 13, in Client return CurlClient(hub, **kwargs) File "/var/app/venv/env/lib/python3.7/site-packages/kombu/asynchronous/http/curl.py", line 43, in init raise ImportError('The curl client requires the pycurl library.') ImportError: The curl client requires the … -
Django 1.6.5 urlreverse change default directory name
import django from django.core.urlresolvers import reverse print django.get_version() # 1.6.5 app -> inventory url = reverse('product', slug='foo-bar') url = '/inventory/foo-bar/ How do I get the django url to reverse and change the name of directory? For example, I am trying to achieve url='/product/foo-bar/' -
How can I search data from a table using a field from the 2 tables below
So, maybe my questions is noth enaught clearly... I'll try to show it in example. I have 3 tables: models.py class Department(models.Model): department = models.CharField(max_length=100) activate = models.BooleanField(default=True) def __str__(self): return self.department class Employee(models.Model): noEmployee = models.DecimalField(max_digits=8, decimal_places=0, default=10) # name = models.CharField(max_length=50) surname = models.CharField(max_length=100) department = models.ForeignKey(Department, on_delete=models.CASCADE, default=1) activate = models.BooleanField(default=True) def __str__(self): return str(self.noEmployee) class List_of_tasks(models.Model): myData = datetime.now() formatedDate = myData.strftime("%Y-%m-%d") task = models.CharField(max_length=250) description = models.TextField(blank=True, null=True) responsible = models.ForeignKey(Employee, on_delete=models.CASCADE, default=1) start_date = models.DateField('Start date', default=formatedDate) finish_date = models.DateField('Finish date', default=formatedDate) finished = models.BooleanField(default=False) def __str__(self): return self.task And small class in views.py def filter(request): qs = List_of_tasks.objects.all() task_query = request.GET.get('task_contains') department_query = request.GET.get('department_contains') print(task_query) if department_query is not None: dep = Employee.objects.filter(department__department__icontains=department_query) for d in dep: print('department: ', d.noEmployee, d.name, d.surname) for d in dep: dep2 = List_of_tasks.objects.filter(responsible__noEmployee__exact=d.noEmployee) for d2 in dep2: print('Tasks: ', d2.task, d2.responsible) if is_valid_queryparam(task_query): qs = qs.filter(task__icontains=task_query) context = {'queryset': qs,} return render(request, 'appl01/export.html', context) Finding TASKS or RESPONSIBLE persons in table List_of_tasks is easy but I would like to find for example all tasks assigned to department... two tables down... As you can see I created my own method which works as I want but is not … -
Registration user with multiple usernames - Django REST
I'm trying to implement a user registration and authentication using django rest framework and I'm not sure how to implement it. The thing is that I want a user to have multiple usernames/nicknames so that's why I have a little bit troubles. The current models I have: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=50, unique=True, error_messages={ 'unique': _("Email already exists."), }, ) is_active = models.BooleanField( _('active'), default=True, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of deleting accounts.' ), ) gender = models.IntegerField(default=GENDER_MALE, choices=GENDER_CHOICES) date_of_birth = UnixDateTimeField(null=True, blank=True, ) ip = models.GenericIPAddressField(null=True) USERNAME_FIELD = 'email' class Meta: verbose_name = _('user') verbose_name_plural = _('users') class UserNicknames(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) username = models.CharField(max_length=10, null=False, unique=True, validators=[username_validator], error_messages={ 'unique': _("A user with that username already exists."), }, ) is_current = models.BooleanField(default=False) As you can see I have the User model just like the django one but without the username and UserNicknames which contains the user nicknames (the UserNicknames.user field is the foreign key to the User.id field). The question is what is right way to implement the registration serializer? Should I get all the fields in User and UserNicknames and then do the logic or there is … -
How can we pass another field to Create Model Mixin?
Model: class ShopItem(models.Model): id = models.AutoField(db_column='ID', primary_key=True) name = models.CharField(db_column='Name', max_length=255) price = models.IntegerField(db_column='Price', default=0) description = models.CharField(db_column='Description', max_length=63) seller_id = models.ForeignKey(Seller, models.DO_NOTHING, db_column='SellerID') View: class SellerItemAPIView(GenericAPIView, ListModelMixin, CreateModelMixin, UpdateModelMixin): serializer_class = ShopItemSerializer permission_classes = [AllowAny] def get_seller(self, *args, **kwargs): phone_number = self.kwargs.get('phone_number') seller = Seller.objects.filter(Q(user_id__phone_number=phone_number))[0] return seller def post(self, request): seller = self.get_seller() return self.create(request, seller_id=seller.id) Is there any way to use this Creat method with another field? It now give me this error: { "seller_id": [ "This field is required." ] } -
Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/accounts/signup/signup
I am getting page not found 404 ERROR, in Django. Even though i have mapped the URL correctly both in the main app and this app. urlpatterns = [ path('',views.mainpage,name='main'), path("signup/",views.signup,name='signup'), path("login/",views.login,name='login'), path("logout/",views.logout,name='logout') ] Now the below url is of the main app where I have included the urls.py of sub-app which is accounts. urlpatterns = [ path('',include('trial.urls')), path('accounts/',include('accounts.urls')), path('admin/', admin.site.urls), ] This is the URL mapping of the app name accounts, used to handle the account and registration details. The error is in this path http://127.0.0.1:8000/accounts/signup/signup Where as it works finely up to the below mentioned path. http://127.0.0.1:8000/accounts/signup Can anyone suggest me or help me finding out where it going wrong. What it should happen is, http://127.0.0.1:8000/accounts/signup after this path when we click submit it should create a user in database and return or redirect the page to login page, with a message user created. Below is the code of views.py of the accounts app. def signup(request): if request.method == 'POST': firstname = request.POST['first_name'] password1 = request.POST['password1'] user = User.objects.create_user(firstname=first_name,lastname=last_name,username =username ,email=email,password=password1) user.save(); print("USER CREATED SUCCESSFULLY") return redirect('/login.html') Anyone help me out what is going wrong. Thank you. -
Read time out issue while installing latest django version using pip
File "c:\users\hp\envs\dell\lib\site-packages\pip_vendor\urllib3\response.py", line 442, in _error_catcher raise ReadTimeoutError(self._pool, None, "Read timed out.") pip._vendor.urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. -
Django: using multi pk in views.py
In django project my url.py looks like: urlpatterns = [ path('', views.home,name='home'), path('customer/<str:customer_id>', views.customer, name='customer'), path('create_order/<str:customer_id>', views.createOrder, name='create_order'), path('update_order/<str:order_id>', views.updateOrder, name='update_order'), path('delete_order/<str:order_id>', views.deleteOrder, name='delete_order'), ] and I have form.py with the following content: class OrderForm(ModelForm): class Meta: model = Order fields = ['product', 'status'] and finally my views.py has these functions: def createOrder(request, customer_id): customer = Customer.objects.get(id=customer_id) form = OrderForm(initial={'customer': customer}) if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): form.save() return redirect('/') context = {'customer':customer, 'form': form} return render(request, 'accounts/order_form.html', context) def updateOrder(request, order_id): order = Order.objects.get(id=order_id) form = OrderForm(instance=order) print(form) if request.method == 'POST': form = OrderForm(request.POST, instance=order) if form.is_valid(): form.save() return redirect('/') context = {'form': form} return render(request, 'accounts/order_form.html', context) Here in function updateOrder, I need to use customer name and I don't know how to grab it. I have tried to use both order_id and customer_id in urlpatterns but no result! I don't need to get all fields from form.py even customer field. -
handling multiple GenericRelations in django admin
I have multiple GenericRelations from Office to Picture for multiple sets of pictures. I'm having trouble with including them in the admin panel. With the current setup If I add 1 image to HomeSlideshow and two images to OfficeSlideshow and save, I will get three images in both HomeSlideshow and OfficeSlideshow. models.py class Office(models.Model): home_slideshow = GenericRelation(Picture) office_slideshow = GenericRelation(Picture) office_text = QuillField() manifesto_slideshow = GenericRelation(Picture, blank=True) manifesto_text = QuillField(blank=True) employees_pictures = models.ImageField() employees_text = QuillField() class Picture(models.Model): title = models.CharField(max_length=30, blank=True) image = models.ImageField() content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey("content_type", "object_id") def __str__(self): return self.title admin.py from django.contrib import admin from django.contrib.contenttypes.admin import GenericTabularInline from modeltranslation.admin import TranslationAdmin from pictures.models import Picture from .models import Office class HomeSlideshowInline(GenericTabularInline): model = Picture verbose_name = "Picture" verbose_name_plural = "Home-Slideshow" extra = 1 readonly_fields = ("image_preview",) def image_preview(self, obj): if obj.image: return mark_safe( '<img src="{url}" width="70" height="70" />'.format(url=obj.image.url) ) else: return "No image" class OfficeSlideshowInline(GenericTabularInline): model = Picture verbose_name = "Picture" verbose_name_plural = "Office-Slideshow" extra = 1 readonly_fields = ("image_preview",) def image_preview(self, obj): if obj.image: return mark_safe( '<img src="{url}" width="70" height="70" />'.format(url=obj.image.url) ) else: return "No image" class OfficeAdmin(TranslationAdmin): inlines = [HomeSlideshowInline, OfficeSlideshowInline, ManifestoSlideshowInline] admin.site.register(Office, OfficeAdmin) So far, … -
Compare date of datetime object in filter django
I use django 3.1.0 I have a release_time field(a DateTimeFeild) in my model, and i want to retrieve those records that have been released in current date. here is my model: class Test(models.Model): title = models.CharField(max_length=100) release_time = models.DateTimeField() end_time = models.DateTimeField() I use the following line to get my data: cur_time = localtime() // django.utils.timezone.localtime Test.objects.filter(release_time__date=cur_time.date()) This always returns an empty query set. I am sure that there are records that have this condition. PLease tell me am I doing this wrong?? -
getting error while rendering contact form and header title from database together in django
form.py i want to render data to my database together with a contact form attatched but when i try to do that it give an hmtl page instead of my index template def home(request): base = BaseHeader.objects.all() if request.method == 'GET': form = contactForm() else: form = contactForm(request.POST) if form.is_valid(): form.save() name = form.cleaned_data['name'] email = form.cleaned_data['email'] Phonenumber = form.cleaned_data['Phonenumber'] try: send_mail( 'Subject here', 'Here is the message.', 'from@gmail.com', ['to@gmail.com'], fail_silently=False,) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('home') return render(request, 'index.html', {'form': form},{'menu_titles': base}) -
Django file installation
I am practicing django for last 5 days.I have a doubt in that topic.I installed django in a new virtual environment for my first project. My question is , if I want to start another django project should I want to install django again in the new project directory -
Deducting the value of one django field in a model class from another model class
I am looking for a way to subtract from a field named total in the first class, which i get by multiplying the price and the quantity. It works well and the result is evident in the database. I would like, after calculating the total, to deduct that field by referencing it in my second class. Basically, the sales input value - the referenced total object should return a profit/loss and store that in a field named profit in the second class. I have tried a few ways, it posts the sales value but not the calculated value in terms of profit/loss. Is there something I am overlooking or I am oversimplifying the code? from django.db import models import datetime from django.utils import timezone from numpy import array class CowData(models.Model): title = models.CharField(max_length=20, default="") user = models.CharField(max_length=20, null=False) feed = models.CharField(max_length=20, null=True) quantity = models.PositiveIntegerField() price = models.PositiveIntegerField() total = models.PositiveIntegerField(editable=True, blank=True, null=True, unique=True) # here i calculate the total by multiplying the price and the total def save(self, *args, **kwargs): self.total = array(self.total) self.total = self.price * self.quantity super(CowData, self).save(*args, **kwargs) class Sales(models.Model): # total = models.ForeignKey(CowData, to_field='total', on_delete=models.CASCADE, default=False) sales = models.PositiveIntegerField() profit = models.PositiveIntegerField() # What I …